本文整理汇总了Python中sqlalchemy.util.to_list函数的典型用法代码示例。如果您正苦于以下问题:Python to_list函数的具体用法?Python to_list怎么用?Python to_list使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_list函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _aliasize_orderby
def _aliasize_orderby(self, orderby, copy=True):
if copy:
return self.aliasizer.copy_and_process(util.to_list(orderby))
else:
orderby = util.to_list(orderby)
self.aliasizer.process_list(orderby)
return orderby
示例2: group_by
def group_by(self, criterion):
"""apply one or more GROUP BY criterion to the query and return the newly resulting ``Query``"""
q = self._clone()
if q._group_by is False:
q._group_by = util.to_list(criterion)
else:
q._group_by.extend(util.to_list(criterion))
return q
示例3: _get
def _get(self, key, ident=None, reload=False, lockmode=None):
lockmode = lockmode or self.lockmode
if not reload and not self.always_refresh and lockmode is None:
try:
return self.session._get(key)
except KeyError:
pass
if ident is None:
ident = key[1]
else:
ident = util.to_list(ident)
i = 0
params = {}
for primary_key in self.primary_key_columns:
params[primary_key._label] = ident[i]
# if there are not enough elements in the given identifier, then
# use the previous identifier repeatedly. this is a workaround for the issue
# in [ticket:185], where a mapper that uses joined table inheritance needs to specify
# all primary keys of the joined relationship, which includes even if the join is joining
# two primary key (and therefore synonymous) columns together, the usual case for joined table inheritance.
if len(ident) > i + 1:
i += 1
try:
statement = self.compile(self._get_clause, lockmode=lockmode)
return self._select_statement(statement, params=params, populate_existing=reload, version_check=(lockmode is not None))[0]
except IndexError:
return None
示例4: __init__
def __init__(self, app=None, use_native_unicode=True,
session_extensions=None, session_options=None):
self.use_native_unicode = use_native_unicode
self.session_extensions = to_list(session_extensions, []) + \
[_SignallingSessionExtension()]
if session_options is None:
session_options = {}
session_options.setdefault(
'scopefunc', connection_stack.__ident_func__
)
self.session = self.create_scoped_session(session_options)
self.Model = self.make_declarative_base()
self._engine_lock = Lock()
if app is not None:
self.app = app
self.init_app(app)
else:
self.app = None
_include_sqlalchemy(self)
self.Query = BaseQuery
示例5: _register_attribute
def _register_attribute(self, class_, callable_=None, impl_class=None, **kwargs):
self.logger.info("%s register managed %s attribute" % (self, (self.uselist and "collection" or "scalar")))
attribute_ext = util.to_list(self.parent_property.extension) or []
if self.parent_property.backref:
attribute_ext.append(self.parent_property.backref.extension)
if self.key in self.parent._validators:
attribute_ext.append(mapperutil.Validator(self.key, self.parent._validators[self.key]))
sessionlib.register_attribute(
class_,
self.key,
uselist=self.uselist,
useobject=True,
extension=attribute_ext,
trackparent=True,
typecallable=self.parent_property.collection_class,
callable_=callable_,
comparator=self.parent_property.comparator,
parententity=self.parent,
impl_class=impl_class,
**kwargs
)
示例6: __should_skip_for
def __should_skip_for(self, cls):
if hasattr(cls, '__requires__'):
def test_suite(): return 'ok'
for requirement in cls.__requires__:
check = getattr(requires, requirement)
if check(test_suite)() != 'ok':
# The requirement will perform messaging.
return True
if cls.__unsupported_on__:
spec = testing.db_spec(*cls.__unsupported_on__)
if spec(testing.db):
print "'%s' unsupported on DB implementation '%s'" % (
cls.__class__.__name__, testing.db.name)
return True
if getattr(cls, '__only_on__', None):
spec = testing.db_spec(*util.to_list(cls.__only_on__))
if not spec(testing.db):
print "'%s' unsupported on DB implementation '%s'" % (
cls.__class__.__name__, testing.db.name)
return True
if (getattr(cls, '__skip_if__', False)):
for c in getattr(cls, '__skip_if__'):
if c():
print "'%s' skipped by %s" % (
cls.__class__.__name__, c.__name__)
return True
for rule in getattr(cls, '__excluded_on__', ()):
if testing._is_excluded(*rule):
print "'%s' unsupported on DB %s version %s" % (
cls.__class__.__name__, testing.db.name,
_server_version())
return True
return False
示例7: _filter_or_exclude
def _filter_or_exclude(self, negate, kwargs):
q = self
negate_if = lambda expr: expr if not negate else ~expr
column = None
for arg, value in kwargs.iteritems():
for token in arg.split('__'):
if column is None:
column = _entity_descriptor(q._joinpoint_zero(), token)
if column.impl.uses_objects:
q = q.join(column)
column = None
elif token in self.OPERATORS:
op = self.OPERATORS[token]
if isinstance(value, (list, tuple)):
value = [value]
q = q.filter(negate_if(op(column, *to_list(value))))
column = None
else:
raise ValueError('No idea what to do with %r' % token)
if column is not None:
q = q.filter(negate_if(column == value))
column = None
q = q.reset_joinpoint()
return q
示例8: _do_skips
def _do_skips(self, cls):
if hasattr(cls, '__requires__'):
def test_suite(): return 'ok'
test_suite.__name__ = cls.__name__
for requirement in cls.__requires__:
check = getattr(requires, requirement)
check(test_suite)()
if cls.__unsupported_on__:
spec = testing.db_spec(*cls.__unsupported_on__)
if spec(testing.db):
raise SkipTest(
"'%s' unsupported on DB implementation '%s'" % (
cls.__name__, testing.db.name)
)
if getattr(cls, '__only_on__', None):
spec = testing.db_spec(*util.to_list(cls.__only_on__))
if not spec(testing.db):
raise SkipTest(
"'%s' unsupported on DB implementation '%s'" % (
cls.__name__, testing.db.name)
)
if getattr(cls, '__skip_if__', False):
for c in getattr(cls, '__skip_if__'):
if c():
raise SkipTest("'%s' skipped by %s" % (
cls.__name__, c.__name__)
)
for db, op, spec in getattr(cls, '__excluded_on__', ()):
testing.exclude(db, op, spec, "'%s' unsupported on DB %s version %s" % (
cls.__name__, testing.db.name,
testing._server_version()))
示例9: driver
def driver(drivername):
"""Return `True` or `False` if the drivername is matching the current
configuration. `drivername` can be a list.
"""
engine = get_engine()
drivers = to_list(drivername)
return engine.url.drivername in drivers
示例10: column_mapped_collection
def column_mapped_collection(mapping_spec):
"""A dictionary-based collection type with column-based keying.
Returns a MappedCollection factory with a keying function generated
from mapping_spec, which may be a Column or a sequence of Columns.
The key value must be immutable for the lifetime of the object. You
can not, for example, map on foreign key values if those key values will
change during the session, i.e. from None to a database-assigned integer
after a session flush.
"""
from sqlalchemy.orm.util import _state_mapper
from sqlalchemy.orm.attributes import instance_state
cols = [expression._no_literals(q) for q in util.to_list(mapping_spec)]
if len(cols) == 1:
def keyfunc(value):
state = instance_state(value)
m = _state_mapper(state)
return m._get_state_attr_by_column(state, cols[0])
else:
mapping_spec = tuple(cols)
def keyfunc(value):
state = instance_state(value)
m = _state_mapper(state)
return tuple(m._get_state_attr_by_column(state, c)
for c in mapping_spec)
return lambda: MappedCollection(keyfunc)
示例11: __get_paths
def __get_paths(self, query, raiseerr):
path = None
entity = None
l = []
# _current_path implies we're in a secondary load
# with an existing path
current_path = list(query._current_path)
if self.mapper:
entity = self.__find_entity(query, self.mapper, raiseerr)
mapper = entity.mapper
path_element = entity.path_entity
for key in util.to_list(self.key):
if isinstance(key, basestring):
tokens = key.split('.')
else:
tokens = [key]
for token in tokens:
if isinstance(token, basestring):
if not entity:
entity = query._entity_zero()
path_element = entity.path_entity
mapper = entity.mapper
prop = mapper.get_property(token, resolve_synonyms=True, raiseerr=raiseerr)
key = token
elif isinstance(token, PropComparator):
prop = token.property
if not entity:
entity = self.__find_entity(query, token.parententity, raiseerr)
if not entity:
return []
path_element = entity.path_entity
key = prop.key
else:
raise sa_exc.ArgumentError("mapper option expects string key or list of attributes")
if current_path and key == current_path[1]:
current_path = current_path[2:]
continue
if prop is None:
return []
path = build_path(path_element, prop.key, path)
l.append(path)
if getattr(token, '_of_type', None):
path_element = mapper = token._of_type
else:
path_element = mapper = getattr(prop, 'mapper', None)
if path_element:
path_element = path_element.base_mapper
# if current_path tokens remain, then
# we didn't have an exact path match.
if current_path:
return []
return l
示例12: __init__
def __init__(self, stmt):
if isinstance(stmt, expression.ScalarSelect):
stmt = stmt.element
elif not isinstance(stmt, expression.SelectBase):
stmt = expression.select(util.to_list(stmt))
super(nested, self).__init__(stmt)
self.type = NestedResult()
示例13: mapper
def mapper(*args, **kwargs):
"""
Add our own database mapper, not the new sqlalchemy 0.4
session aware mapper.
"""
kwargs['extension'] = extensions = to_list(kwargs.get('extension', []))
extensions.append(ManagerExtension())
return orm.mapper(*args, **kwargs)
示例14: setup_query
def setup_query(self, context, eagertable=None, parentclauses=None, parentmapper=None, **kwargs):
"""Add a left outer join to the statement thats being constructed."""
if parentmapper is None:
localparent = context.mapper
else:
localparent = parentmapper
if self.mapper in context.recursion_stack:
return
else:
context.recursion_stack.add(self.parent)
statement = context.statement
if hasattr(statement, '_outerjoin'):
towrap = statement._outerjoin
elif isinstance(localparent.mapped_table, schema.Table):
# if the mapper is against a plain Table, look in the from_obj of the select statement
# to join against whats already there.
for (fromclause, finder) in [(x, sql_util.TableFinder(x)) for x in statement.froms]:
# dont join against an Alias'ed Select. we are really looking either for the
# table itself or a Join that contains the table. this logic still might need
# adjustments for scenarios not thought of yet.
if not isinstance(fromclause, sql.Alias) and localparent.mapped_table in finder:
towrap = fromclause
break
else:
raise exceptions.InvalidRequestError("EagerLoader cannot locate a clause with which to outer join to, in query '%s' %s" % (str(statement), self.localparent.mapped_table))
else:
# if the mapper is against a select statement or something, we cant handle that at the
# same time as a custom FROM clause right now.
towrap = localparent.mapped_table
try:
clauses = self.clauses[parentclauses]
except KeyError:
clauses = EagerLoader.AliasedClauses(self, parentclauses)
self.clauses[parentclauses] = clauses
if context.mapper not in self.clauses_by_lead_mapper:
self.clauses_by_lead_mapper[context.mapper] = clauses
if self.secondaryjoin is not None:
statement._outerjoin = sql.outerjoin(towrap, clauses.eagersecondary, clauses.eagerprimary).outerjoin(clauses.eagertarget, clauses.eagersecondaryjoin)
if self.order_by is False and self.secondary.default_order_by() is not None:
statement.order_by(*clauses.eagersecondary.default_order_by())
else:
statement._outerjoin = towrap.outerjoin(clauses.eagertarget, clauses.eagerprimary)
if self.order_by is False and clauses.eagertarget.default_order_by() is not None:
statement.order_by(*clauses.eagertarget.default_order_by())
if clauses.eager_order_by:
statement.order_by(*util.to_list(clauses.eager_order_by))
statement.append_from(statement._outerjoin)
for value in self.select_mapper.props.values():
value.setup(context, eagertable=clauses.eagertarget, parentclauses=clauses, parentmapper=self.select_mapper)
示例15: select_from
def select_from(self, from_obj):
"""Set the `from_obj` parameter of the query.
`from_obj` is a list of one or more tables.
"""
new = self._clone()
new._from_obj = list(new._from_obj) + util.to_list(from_obj)
return new