本文整理汇总了Python中sqlalchemy.orm.class_mapper函数的典型用法代码示例。如果您正苦于以下问题:Python class_mapper函数的具体用法?Python class_mapper怎么用?Python class_mapper使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了class_mapper函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: copy_model_object
def copy_model_object(cls, model, found=None):
"""
:param model: model to make a copy of
:param found: used when function is called recursivly. Found is used to track references if two entities have references to each other both ways, will loop for ever
:return: a copy of the model object, without primary keys set
"""
if found is None:
found = []
result = model.__class__()
pk_keys = set([c.key for c in class_mapper(model.__class__).primary_key])
for p in class_mapper(model.__class__).columns:
if p.key not in pk_keys:
result.__setattr__(p.key, model.__getattribute__(p.key))
for name, relation in class_mapper(model.__class__).relationships.items():
if relation not in found:
found.append(relation)
if relation.uselist:
for child in model.__getattribute__(name):
result.__getattribute__(name).append(cls.copy_model_object(child, found))
else:
result.__setattr__(name, cls.copy_model_object(model.__getattribute__(name), found))
return result
开发者ID:Trondheim-kommune,项目名称:Tilskuddsbasen,代码行数:25,代码来源:base_repo.py
示例2: get_models
def get_models(self):
"""return a dict containing all model names as key and url as value"""
models = {}
if isinstance(self.model, list):
for model in self.model:
key = model.__name__
models[key] = model_url(self.collection_name, model_name=key)
else:
for key, obj in self.model.__dict__.iteritems():
if not key.startswith("_"):
if Document is not None:
try:
if issubclass(obj, Document):
models[key] = model_url(self.collection_name, model_name=key)
continue
except:
pass
try:
class_mapper(obj)
except:
continue
if not isinstance(obj, type):
continue
models[key] = model_url(self.collection_name, model_name=key)
return models
开发者ID:netconstructor,项目名称:formalchemy,代码行数:25,代码来源:controller.py
示例3: is_class_sa_mapped
def is_class_sa_mapped(klass):
try:
class_mapper(klass)
except UnmappedInstanceError:
return False
return True
开发者ID:kruser,项目名称:zualoo,代码行数:7,代码来源:_sqlalchemy.py
示例4: __init__
def __init__(self, config=None):
TweetsDB.__init__(self, config=config)
try:
self.tweet_mapper = class_mapper(ElectTweetObj)
except UnmappedClassError:
self.tweet_mapper = mapper(ElectTweetObj,self.tweet_table)
try:
self.user_mapper = class_mapper(ElectUserObj)
except UnmappedClassError:
self.user_mapper = mapper(ElectUserObj,self.user_table)
try:
self.user_meta_mapper = class_mapper(ElectUserMetaObj)
except UnmappedClassError:
self.user_meta_mapper = mapper(ElectUserMetaObj,self.user_meta_table)
try:
self.friend_mapper = class_mapper(ElectFriendObj)
except UnmappedClassError:
self.friend_mapper = mapper(ElectFriendObj,self.friends_table)
try:
self.follower_mapper = class_mapper(ElectFollowerObj)
except UnmappedClassError:
self.follower_mapper = mapper(ElectFollowerObj,self.followers_table)
开发者ID:xuchen509,项目名称:Sample-Projects,代码行数:27,代码来源:ElectTweetsDB.py
示例5: models
def models(self, **kwargs):
"""Models index page"""
request = self.request
models = {}
if isinstance(self.model, list):
for model in self.model:
key = model.__name__
models[key] = self.route_url(key, request.format)
else:
for key, obj in self.model.__dict__.iteritems():
if not key.startswith('_'):
if Document is not None:
try:
if issubclass(obj, Document):
models[key] = self.route_url(key, request.format)
continue
except:
pass
try:
class_mapper(obj)
except:
continue
if not isinstance(obj, type):
continue
models[key] = self.route_url(key, request.format)
return self.render(models=models)
开发者ID:Alwnikrotikz,项目名称:formalchemy,代码行数:26,代码来源:admin.py
示例6: setUp
def setUp(test):
placelesssetup.setUp()
# Attempt to initialize mappers only if their not already mapped.
try:
orm.class_mapper(schema.Content)
except orm.exc.UnmappedClassError:
schema.initialize_mapper()
component.provideAdapter(transform.StringTransform)
component.provideAdapter(transform.IntegerTransform)
component.provideAdapter(transform.FloatTransform)
component.provideAdapter(transform.DateTimeTransform)
component.provideAdapter(transform.LinesTransform)
component.provideAdapter(transform.BooleanTransform)
component.provideAdapter(transform.FileTransform)
component.provideAdapter(transform.PhotoTransform)
component.provideAdapter(transform.ReferenceTransform)
component.provideUtility(peer.PeerRegistry())
component.provideAdapter(
peer.PeerFactory,
(interfaces.IMirrored, interfaces.ISchemaTransformer))
component.provideAdapter(transform.SchemaTransformer,
(interfaces.IMirrored, interfaces.IMetaData))
component.provideAdapter(serializer.Serializer, (interfaces.IMirrored,))
component.provideAdapter(
operation.OperationFactory, (interfaces.IMirrored,))
component.provideUtility(operation.OperationBufferFactory())
开发者ID:jasonheffner,项目名称:contentmirror,代码行数:30,代码来源:base.py
示例7: test_mapper_args_declared_attr_two
def test_mapper_args_declared_attr_two(self):
# same as test_mapper_args_declared_attr, but we repeat
# ComputedMapperArgs on both classes for no apparent reason.
class ComputedMapperArgs:
@declared_attr
def __mapper_args__(cls):
if cls.__name__ == 'Person':
return {'polymorphic_on': cls.discriminator}
else:
return {'polymorphic_identity': cls.__name__}
class Person(Base, ComputedMapperArgs):
__tablename__ = 'people'
id = Column(Integer, primary_key=True)
discriminator = Column('type', String(50))
class Engineer(Person, ComputedMapperArgs):
pass
configure_mappers()
assert class_mapper(Person).polymorphic_on \
is Person.__table__.c.type
eq_(class_mapper(Engineer).polymorphic_identity, 'Engineer')
开发者ID:Julian,项目名称:sqlalchemy,代码行数:26,代码来源:test_mixin.py
示例8: reflect
def reflect(cls):
def _get_attribute(cls, p):
manager = manager_of_class(cls)
return manager[p.key]
pkeys = [c.key for c in class_mapper(cls).primary_key]
# attributes we're interested in
attrs = []
for p in class_mapper(cls).iterate_properties:
attr = _get_attribute(cls, p)
if getattr(p, '_is_polymorphic_discriminator', False):
continue
if isinstance(attr.impl, DynamicAttributeImpl):
continue
if isinstance(p, SynonymProperty):
continue
if isinstance(attr.impl, CollectionAttributeImpl):
continue
if isinstance(attr.impl, ScalarObjectAttributeImpl):
continue
if attr.key in pkeys:
continue
if isinstance(attr.impl, ScalarAttributeImpl):
attrs.append(attr)
#fields.AttributeField(attr, self)
return attrs
开发者ID:sergeyv,项目名称:webapp,代码行数:31,代码来源:auto_schema.py
示例9: on_after_update
def on_after_update(mapper, connection, target):
request = getattr(target, '_request', None)
from .documents import BaseDocument
# Reindex old one-to-one related object
committed_state = attributes.instance_state(target).committed_state
columns = set()
for field, value in committed_state.items():
if isinstance(value, BaseDocument):
obj_session = object_session(value)
# Make sure object is not updated yet
if not obj_session.is_modified(value):
obj_session.expire(value)
index_object(value, with_refs=False,
request=request)
else:
id_pos = field.rfind('_id')
if id_pos >= 0:
rel_name = field[:id_pos]
rel = mapper.relationships.get(rel_name, False)
if rel and any(c.name == field for c in rel.local_columns):
columns.add(rel_name)
# Reload `target` to get access to processed fields values
columns = columns.union([c.name for c in class_mapper(target.__class__).columns])
object_session(target).expire(target, attribute_names=columns)
index_object(target, request=request, with_refs=False, nested_only=True)
# Reindex the item's parents. This must be done after the child has been processes
for parent, children_field in target.get_parent_documents(nested_only=True):
columns = [c.name for c in class_mapper(parent.__class__).columns]
object_session(parent).expire(parent, attribute_names=columns)
ES(parent.__class__.__name__).index_nested_document(parent, children_field, target)
开发者ID:geniusproject,项目名称:nefertari-sqla,代码行数:33,代码来源:signals.py
示例10: test_non_propagating_mixin
def test_non_propagating_mixin(self):
class NoJoinedTableNameMixin:
@declared_attr
def __tablename__(cls):
if decl.has_inherited_table(cls):
return None
return cls.__name__.lower()
class BaseType(Base, NoJoinedTableNameMixin):
discriminator = Column('type', String(50))
__mapper_args__ = dict(polymorphic_on=discriminator)
id = Column(Integer, primary_key=True)
value = Column(Integer())
class Specific(BaseType):
__mapper_args__ = dict(polymorphic_identity='specific')
eq_(BaseType.__table__.name, 'basetype')
eq_(list(BaseType.__table__.c.keys()), ['type', 'id', 'value'])
assert Specific.__table__ is BaseType.__table__
assert class_mapper(Specific).polymorphic_on \
is BaseType.__table__.c.type
eq_(class_mapper(Specific).polymorphic_identity, 'specific')
开发者ID:Julian,项目名称:sqlalchemy,代码行数:27,代码来源:test_mixin.py
示例11: get_trigger_tables
def get_trigger_tables():
"""Determines which tables need to have triggers set on them.
Returns a dictionary of table names (key) with a dictionary (value) that
provides additional information about a table:
* list of primary keys for each table.
* whether it's an entity table
"""
tables = collections.OrderedDict() # mapping of table names to their models and their "kind" (direct or not)
for _, entity in SCHEMA.items():
# Entity table itself
mapped_class = class_mapper(entity.model)
tables[mapped_class.mapped_table.name] = {
"model": entity.model,
"is_direct": True,
"has_gid": mapped_class.has_property('gid'),
}
# Tables that contain the referenced column
# TODO(roman): maybe come up with a better description above
for path in unique_split_paths([path for field in entity.fields
for path in field.paths if field.trigger]):
model = last_model_in_path(entity.model, path)
if model is not None:
table_name = class_mapper(model).mapped_table.name
if table_name not in tables:
tables[table_name] = {
"model": model,
"is_direct": False,
}
return tables
开发者ID:metabrainz,项目名称:sir,代码行数:32,代码来源:__init__.py
示例12: __init__
def __init__(self, config = None):
BaseDB.__init__(self, config=config)
self.db = DBManager(config=config)
self.session = self.db.session
self.tweet_table = self.db.get_table(TWEETS_TABLE_NAME)
self.user_table = self.db.get_table(USER_TABLE_NAME)
self.user_meta_table = self.db.get_table(USER_META_TABLE_NAME)
self.friends_table = self.db.get_table(FRIENDS_TABLE_NAME)
self.followers_table = self.db.get_table(FOLLOWERS_TABLE_NAME)
try:
self.tweet_mapper = class_mapper(TweetObj)
except UnmappedClassError:
self.tweet_mapper = mapper(TweetObj,self.tweet_table)
try:
self.user_mapper = class_mapper(userObj)
except UnmappedClassError:
self.user_mapper = mapper(userObj,self.user_table)
try:
self.user_meta_mapper = class_mapper(userMetaObj)
except UnmappedClassError:
self.user_meta_mapper = mapper(userMetaObj,self.user_meta_table)
try:
self.friend_mapper = class_mapper(friendObj)
except UnmappedClassError:
self.friend_mapper = mapper(friendObj,self.friends_table)
try:
self.follower_mapper = class_mapper(followerObj)
except UnmappedClassError:
self.follower_mapper = mapper(followerObj,self.followers_table)
开发者ID:xuchen509,项目名称:Sample-Projects,代码行数:34,代码来源:TweetsDB.py
示例13: test_polymorphic_option
def test_polymorphic_option(self):
"""
Test that polymorphic loading sets state.load_path with its
actual mapper on a subclass, and not the superclass mapper.
"""
paths = []
class MyOption(interfaces.MapperOption):
propagate_to_loaders = True
def process_query_conditionally(self, query):
paths.append(query._current_path)
sess = create_session()
names = ['dilbert', 'pointy haired boss']
dilbert, boss = (
sess.query(Person)
.options(MyOption())
.filter(Person.name.in_(names))
.order_by(Person.name).all())
dilbert.machines
boss.paperwork
eq_(paths,
[(class_mapper(Engineer), 'machines'),
(class_mapper(Boss), 'paperwork')])
开发者ID:NoNo1234,项目名称:the_walking_project,代码行数:26,代码来源:test_polymorphic_rel.py
示例14: add_model
def add_model(self, model):
try:
class_mapper(model)
except:
raise ConfigError('%s is not a valid model.')
if model not in self.model_list:
self.model_list.append(model)
开发者ID:akun,项目名称:workin,代码行数:7,代码来源:groups.py
示例15: models
def models(self, **kwargs):
"""Models index page"""
request = self.request
models = {}
if isinstance(request.models, list):
for model in request.models:
if has_permission('view', model, request):
key = model.__name__
models[key] = request.fa_url(key, request.format)
else:
for key, obj in request.models.__dict__.iteritems():
if not key.startswith('_'):
if Document is not None:
try:
if issubclass(obj, Document):
if has_permission('view', obj, request):
models[key] = request.fa_url(key, request.format)
continue
except:
pass
try:
class_mapper(obj)
except:
continue
if not isinstance(obj, type):
continue
if has_permission('view', obj, request):
models[key] = request.fa_url(key, request.format)
if kwargs.get('json'):
return models
return self.render(models=models)
开发者ID:bbinet,项目名称:pyramid_formalchemy,代码行数:31,代码来源:views.py
示例16: _modify_params_for_relationships
def _modify_params_for_relationships(self, entity, params, delete_first=True):
mapper = class_mapper(entity)
relations = self.get_relations(entity)
for relation in relations:
if relation in params:
prop = mapper.get_property(relation)
target = prop.argument
if inspect.isfunction(target):
target = target()
value = params[relation]
if value:
if prop.uselist and isinstance(value, list):
target_obj = []
for v in value:
try:
object_mapper(v)
target_obj.append(v)
except UnmappedInstanceError:
if hasattr(target, 'primary_key'):
pk = target.primary_key
else:
pk = class_mapper(target).primary_key
if isinstance(v, basestring) and "/" in v:
v = map(self._adapt_type, v.split("/"), pk)
v = tuple(v)
else:
v = self._adapt_type(v, pk[0])
#only add those items that come back
new_v = self.session.query(target).get(v)
if new_v is not None:
target_obj.append(new_v)
elif prop.uselist:
try:
object_mapper(value)
target_obj = [value]
except UnmappedInstanceError:
mapper = target
if not isinstance(target, Mapper):
mapper = class_mapper(target)
if isinstance(mapper.primary_key[0].type, Integer):
value = int(value)
target_obj = [self.session.query(target).get(value)]
else:
try:
object_mapper(value)
target_obj = value
except UnmappedInstanceError:
if isinstance(value, basestring) and "/" in value:
value = map(self._adapt_type, value.split("/"), prop.remote_side)
value = tuple(value)
else:
value = self._adapt_type(value, prop.remote_side[0])
target_obj = self.session.query(target).get(value)
params[relation] = target_obj
else:
del params[relation]
return params
开发者ID:kamroot,项目名称:mc27,代码行数:59,代码来源:provider.py
示例17: test_insp_relationship_prop
def test_insp_relationship_prop(self):
User = self.classes.User
Address = self.classes.Address
prop = inspect(User.addresses)
is_(prop, User.addresses)
is_(prop.parent, class_mapper(User))
is_(prop._parentmapper, class_mapper(User))
is_(prop.mapper, class_mapper(Address))
开发者ID:afeide,项目名称:LuoYunCloud,代码行数:8,代码来源:test_inspect.py
示例18: is_model_mapped
def is_model_mapped(domain_model):
# try get mapper to force UnmappedClassError
try:
orm.class_mapper(domain_model)
return True
except orm.exc.UnmappedClassError:
# unmapped class e.g. Address, Version
return False
开发者ID:BenoitTalbot,项目名称:bungeni-portal,代码行数:8,代码来源:catalyst.py
示例19: all_rels_including_subclasses
def all_rels_including_subclasses(model_cls):
return remove_duplicates(
class_mapper(model_cls).relationships.items() +
flatten(
[class_mapper(subcls).relationships.items()
for subcls in all_subclasses(model_cls)]
)
)
开发者ID:inkmonk,项目名称:flask-sqlalchemy-booster,代码行数:8,代码来源:utils.py
示例20: __init__
def __init__(self, cls, excludes=None, includes=None, nullables=None):
self.cls = cls
self._mapper = class_mapper(cls)
self.excludes = excludes or set()
self.includes = includes or set()
self.nullables = nullables or {}
self.pkeys = [col.name for col in self._mapper.primary_key]
self.fkeys = {}
self.rkeys = {}
self.attrs = {}
self.fields = set()
self.relationships = set()
self.references = set()
self.collections = set()
if self.includes and self.excludes:
raise ValueError("includes and excludes parameters are exclusive, specify only one of them")
for p in self._mapper.iterate_properties:
if isinstance(p, ColumnProperty):
self.attrs[p.key] = p.columns[0]
self.fields.add(p.key)
elif isinstance(p, RelationshipProperty):
if callable(p.argument):
cls = p.argument()
else:
cls = p.argument.class_
self.attrs[p.key] = cls
self.relationships.add(p.key)
self.rkeys[p.key] = [col.name for col in class_mapper(cls).primary_key]
if p.uselist:
self.collections.add(p.key)
else:
self.references.add(p.key)
self.fkeys[p.key] = OrderedDict()
for col in p._calculated_foreign_keys:
if col.table in self._mapper.tables:
for f in col.foreign_keys:
self.fkeys[p.key][col.name] = f.column.name
if not self.fkeys[p.key]:
self.fkeys.pop(p.key)
else:
msg = "Unsupported property type: {}".format(type(p))
NotImplementedError(msg)
self._log = getLogger(__name__)
self._log.debug("Registry created.")
self._log.debug("Keys: %s", self.pkeys)
self._log.debug("Foreign Keys: %s", self.fkeys)
self._log.debug("Fieds: %s", self.fields)
self._log.debug("Relationships: %s", self.relationships)
self._log.debug("Relationships Keys: %s, %s", self.rkeys.keys(), self.rkeys.values())
self._log.debug("References: %s", self.references)
self._log.debug("Collections: %s", self.collections)
开发者ID:domenkozar,项目名称:ColanderAlchemy,代码行数:58,代码来源:utils.py
注:本文中的sqlalchemy.orm.class_mapper函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论