本文整理汇总了Python中sqlalchemy.orm.query.Query方法的典型用法代码示例。如果您正苦于以下问题:Python query.Query方法的具体用法?Python query.Query怎么用?Python query.Query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.orm.query
的用法示例。
在下文中一共展示了query.Query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_unreconciled
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def test_unreconciled(self):
Transaction()
m_db = Mock()
m_q = Mock(spec_set=Query)
m_filt = Mock(spec_set=Query)
m_db.query.return_value = m_q
m_q.filter.return_value = m_filt
res = Transaction.unreconciled(m_db)
assert res == m_filt
assert len(m_db.mock_calls) == 2
assert m_db.mock_calls[0] == call.query(Transaction)
kall = m_db.mock_calls[1]
assert kall[0] == 'query().filter'
expected1 = Transaction.reconcile.__eq__(null())
expected2 = Transaction.date.__ge__(date(2017, 3, 17))
expected3 = Transaction.account.has(reconcile_trans=True)
assert len(kall[1]) == 3
assert str(expected1) == str(kall[1][0])
assert binexp_to_dict(expected2) == binexp_to_dict(kall[1][1])
assert str(expected3) == str(kall[1][2])
示例2: orm_get_page
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def orm_get_page(q, per_page, place, backwards):
"""Get a page from an SQLAlchemy ORM query.
:param q: The :class:`Query` to paginate.
:param per_page: Number of rows per page.
:param place: Keyset representing the place after which to start the page.
:param backwards: If ``True``, reverse pagination direction.
:returns: :class:`Page`
"""
result_type = orm_result_type(q)
paging_result = perform_paging(q=q,
per_page=per_page,
place=place,
backwards=backwards,
orm=True)
page = orm_page_from_rows(paging_result,
result_type,
per_page,
backwards,
current_marker=place)
return page
示例3: _aliases_from_query
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def _aliases_from_query(cls, query: Query) -> 'Dict[str, _MapperEntity]':
"""
Get aliases from SQLAlchemy query.
Args:
query: SQLAlchemy query.
Returns:
Dictionary of model aliases.
"""
aliases = {
(mapper._target, mapper.name): mapper.entity
for mapper in query._join_entities
}
return aliases
示例4: resolve_connection
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def resolve_connection(cls, connection_type, model, info, args, resolved):
if resolved is None:
resolved = cls.get_query(model, info, **args)
if isinstance(resolved, Query):
_len = resolved.count()
else:
_len = len(resolved)
connection = connection_from_list_slice(
resolved,
args,
slice_start=0,
list_length=_len,
list_slice_length=_len,
connection_type=connection_type,
pageinfo_type=PageInfo,
edge_type=connection_type.Edge,
)
connection.iterable = resolved
connection.length = _len
return connection
示例5: count
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def count(session, query):
"""Returns the count of the specified `query`.
This function employs an optimization that bypasses the
:meth:`sqlalchemy.orm.Query.count` method, which can be very slow for large
queries.
"""
counts = query.selectable.with_only_columns([func.count()])
num_results = session.execute(counts.order_by(None)).scalar()
if num_results is None or query._limit:
return query.count()
return num_results
# This code comes from <http://stackoverflow.com/a/6798042/108197>, which is
# licensed under the Creative Commons Attribution-ShareAlike License version
# 3.0 Unported.
#
# That is an answer originally authored by the user
# <http://stackoverflow.com/users/500584/agf> to the question
# <http://stackoverflow.com/q/6760685/108197>.
#
# TODO This code is for simultaneous Python 2 and 3 usage. It can be greatly
# simplified when removing Python 2 support.
示例6: paginator
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def paginator(self, query: Query, options: PaginatorOptions):
if options is None:
return query
if options.sort_column:
column = getattr(self.model, options.sort_column) if \
options.sort_column in self.model.__dict__ \
else options.sort_column
criterion = column if not options.sort_descending else desc(column)
query = query.order_by(criterion)
if options.page_size:
query = query. \
offset(options.page_size * options.page_number). \
limit(options.page_size)
return query
示例7: test_before_compile
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def test_before_compile(self):
@event.listens_for(query.Query, "before_compile", retval=True)
def no_deleted(query):
for desc in query.column_descriptions:
if desc["type"] is User:
entity = desc["expr"]
query = query.filter(entity.id != 10)
return query
User = self.classes.User
s = Session()
q = s.query(User).filter_by(id=7)
self.assert_compile(
q,
"SELECT users.id AS users_id, users.name AS users_name "
"FROM users "
"WHERE users.id = :id_1 AND users.id != :id_2",
checkparams={"id_2": 10, "id_1": 7},
)
示例8: test_alters_entities
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def test_alters_entities(self):
User = self.classes.User
@event.listens_for(query.Query, "before_compile", retval=True)
def fn(query):
return query.add_columns(User.name)
s = Session()
q = s.query(User.id).filter_by(id=7)
self.assert_compile(
q,
"SELECT users.id AS users_id, users.name AS users_name "
"FROM users "
"WHERE users.id = :id_1",
checkparams={"id_1": 7},
)
eq_(q.all(), [(7, "jack")])
示例9: test_to_query_args
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def test_to_query_args(self):
User = self.classes.User
sub_bq = self.bakery(lambda s: s.query(User.name))
q = Query([], None)
assert_raises_message(
sa_exc.ArgumentError,
"Given Query needs to be associated with a Session",
sub_bq.to_query,
q,
)
assert_raises_message(
TypeError,
"Query or Session object expected, got .*'int'.*",
sub_bq.to_query,
5,
)
示例10: modify_query_fixture
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def modify_query_fixture(self):
def set_event(bake_ok):
event.listen(
Query,
"before_compile",
_modify_query,
retval=True,
bake_ok=bake_ok,
)
return m1
m1 = mock.Mock()
def _modify_query(query):
m1(query.column_descriptions[0]["entity"])
query = query.enable_assertions(False).filter(
literal_column("1") == 1
)
return query
yield set_event
event.remove(Query, "before_compile", _modify_query)
示例11: get_tag
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def get_tag(tag, user=None):
"""Get tag info
# noqa: E501
:param tag: Name of the tag
:type tag: str
:rtype: Tag
"""
try:
session = Database.get_session()
q = session.query(Tag).filter(Tag.tag == tag) # type: Query
if q.count() == 0:
return Error(code=404, message="Tag not found"), 404
return q[0].to_swagger_model(user=user)
except Exception as e:
return handle_exception(e)
示例12: test_ipsec_conn_get_local_subnets
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def test_ipsec_conn_get_local_subnets(self):
subnet1 = _uuid()
subnet2 = _uuid()
expected_subnets = [subnet1, subnet2]
local_epg = {'id': _uuid(),
'type': v_constants.SUBNET_ENDPOINT,
'endpoints': expected_subnets}
query_mock = mock.patch.object(query.Query, 'all').start()
query_mock.return_value = expected_subnets
subnets = self.validator._get_local_subnets(self.context, local_epg)
self.assertEqual(expected_subnets, subnets)
示例13: test_validate_ipsec_conn_for_endpoints
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def test_validate_ipsec_conn_for_endpoints(self):
"""Check upper-level validation method for endpoint groups.
Tests the happy path for doing general validation of the IPSec
connection, calling all the sub-checks for an endpoint group case.
"""
subnet1 = {'id': _uuid(), 'ip_version': 4}
subnet2 = {'id': _uuid(), 'ip_version': 4}
local_subnets = [subnet1, subnet2]
local_epg_id = _uuid()
local_epg = {'id': local_epg_id,
'type': v_constants.SUBNET_ENDPOINT,
'endpoints': local_subnets}
# Mock getting the subnets from the IDs
query_mock = mock.patch.object(query.Query, 'all').start()
query_mock.return_value = local_subnets
# Mock that subnet is on router
port_mock = mock.patch.object(self.core_plugin, "get_ports").start()
port_mock.side_effect = ['dummy info', 'more dummy info']
peer_epg_id = _uuid()
peer_cidrs = ['10.10.10.10/24', '20.20.20.20/24']
peer_epg = {'id': peer_epg_id,
'type': v_constants.CIDR_ENDPOINT,
'endpoints': peer_cidrs}
ipsec_sitecon = {'local_ep_group_id': local_epg_id,
'local_epg_subnets': local_epg,
'peer_ep_group_id': peer_epg_id,
'peer_epg_cidrs': peer_epg,
'mtu': 2000,
'dpd_action': 'hold',
'dpd_interval': 30,
'dpd_timeout': 120}
local_version = None
vpnservice = {'router_id': _uuid()}
self.validator.validate_ipsec_site_connection(
self.context, ipsec_sitecon, local_version, vpnservice)
# NOTE: Following are tests for the older API, providing some additional
# coverage.
示例14: test_unreconciled
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def test_unreconciled(self):
m_db = Mock()
m_q = Mock(spec_set=Query)
m_filt = Mock(spec_set=Query)
m_db.query.return_value = m_q
m_q.filter.return_value = m_filt
res = OFXTransaction.unreconciled(m_db)
assert res == m_filt
assert len(m_db.mock_calls) == 2
assert m_db.mock_calls[0] == call.query(OFXTransaction)
kall = m_db.mock_calls[1]
assert kall[0] == 'query().filter'
expected1 = OFXTransaction.reconcile.__eq__(null())
cutoff = datetime(2017, 3, 17, 0, 0, 0, tzinfo=UTC)
expected2 = OFXTransaction.date_posted.__ge__(cutoff)
expected3 = OFXTransaction.account.has(reconcile_trans=True)
assert len(kall[1]) == 8
assert str(expected1) == str(kall[1][0])
assert binexp_to_dict(expected2) == binexp_to_dict(kall[1][1])
assert str(kall[1][2]) == str(expected3)
assert str(
OFXTransaction.is_payment.__ne__(True)
) == str(kall[1][3])
assert str(
OFXTransaction.is_late_fee.__ne__(True)
) == str(kall[1][4])
assert str(
OFXTransaction.is_interest_charge.__ne__(True)
) == str(kall[1][5])
assert str(
OFXTransaction.is_other_fee.__ne__(True)
) == str(kall[1][6])
assert str(
OFXTransaction.is_interest_payment.__ne__(True)
) == str(kall[1][7])
示例15: item_count
# 需要导入模块: from sqlalchemy.orm import query [as 别名]
# 或者: from sqlalchemy.orm.query import Query [as 别名]
def item_count(self):
if isinstance(self.collection, Query):
return self.collection.count()
elif isinstance(self.collection,list):
return len(self.collection)
else:
raise NotImplementedError