本文整理汇总了Python中sqlalchemy.orm.collections.attribute_mapped_collection函数的典型用法代码示例。如果您正苦于以下问题:Python attribute_mapped_collection函数的具体用法?Python attribute_mapped_collection怎么用?Python attribute_mapped_collection使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了attribute_mapped_collection函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: transaction_meta_factory
def transaction_meta_factory(self):
"""
Creates TransactionMeta class.
"""
class TransactionMeta(
self.declarative_base,
TransactionMetaBase
):
__tablename__ = 'transaction_meta'
TransactionMeta.transaction_log = sa.orm.relationship(
self.transaction_log_cls,
backref=sa.orm.backref(
'meta_relation',
collection_class=attribute_mapped_collection('key')
),
primaryjoin=(
'%s.id == TransactionMeta.transaction_id' %
self.transaction_log_cls.__name__
),
foreign_keys=[TransactionMeta.transaction_id]
)
self.transaction_log_cls.meta = association_proxy(
'meta_relation',
'value',
creator=lambda key, value: TransactionMeta(key=key, value=value)
)
return TransactionMeta
示例2: test_merge_irregular_collection
def test_merge_irregular_collection(self):
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
mapper(
User,
users,
properties={
"addresses": relationship(
mapper(Address, addresses),
backref="user",
collection_class=attribute_mapped_collection("email_address"),
)
},
)
u1 = User(id=7, name="fred")
u1.addresses["[email protected]"] = Address(email_address="[email protected]")
sess = create_session()
sess.merge(u1)
sess.flush()
assert list(u1.addresses.keys()) == ["[email protected]"]
示例3: InitMapper
def InitMapper( cls, metadata, Parameter, ParameterType, DesignQuantity ):
mapper( cls, inherits = Parameter, polymorphic_identity = ParameterType, properties = {
'_quantity' : relation( DesignQuantity,
collection_class = attribute_mapped_collection('design'))
})
cls.quantity = association_proxy('_quantity', 'quantity', creator = lambda k, v: DesignQuantity( design = k, quantity = v ) )
示例4: InitMapper
def InitMapper( cls, metadata, Parameter, ParameterType, ResourceQuantity ):
mapper( cls, inherits = Parameter, polymorphic_identity = ParameterType, properties = {
'_quantity' : relation( ResourceQuantity,
collection_class = attribute_mapped_collection('resource'))
})
cls.quantity = association_proxy('_quantity', 'quantity', creator = lambda k, v: ResourceQuantity( resource = k, **v ) )
示例5: _variables
def _variables(cls):
# Camelcase the tablename to give the Variable inner class
# here a specific class name; necessary for reporting on
# classes
class_name = \
"".join(x.title() for x in cls.vars_tablename[:-1].split('_'))
# Because we are constructing Variable inner class with the
# 3-arg `type` function, we need to pull out all SA columns
# given that initialization order matters for SA!
#
# * Defines the primary key with correct ordering
# * Captures references, as seen in _repr_columns
parent_id = Column(ForeignKey(
'%s.id' % cls.__tablename__), primary_key=True)
key = Column(String(255), primary_key=True)
value = Column(JSONType)
Variable = type(class_name, (Base,), {
'__tablename__': cls.vars_tablename,
'parent_id': parent_id,
'key': key,
'value': value,
'_repr_columns': [key, value]})
# Need a reference for the association proxy to lookup the
# Variable class so it can reference
cls.variable_class = Variable
return relationship(
Variable,
collection_class=attribute_mapped_collection('key'),
cascade='all, delete-orphan', lazy="joined")
示例6: test_merge_irregular_collection
def test_merge_irregular_collection(self):
mapper(User, users, properties={
'addresses': relationship(
mapper(Address, addresses),
backref='user',
collection_class=attribute_mapped_collection('email_address')),
})
u1 = User(id=7, name='fred')
u1.addresses['[email protected]'] = Address(email_address='[email protected]')
sess = create_session()
sess.merge(u1)
sess.flush()
assert u1.addresses.keys() == ['[email protected]']
示例7: test_validator_bulk_dict_set
def test_validator_bulk_dict_set(self):
users, addresses, Address = (
self.tables.users,
self.tables.addresses,
self.classes.Address,
)
class User(fixtures.ComparableEntity):
@validates("addresses", include_removes=True)
def validate_address(self, key, item, remove):
if not remove:
assert isinstance(item, str)
else:
assert isinstance(item, Address)
item = Address(email_address=item)
return item
mapper(
User,
users,
properties={
"addresses": relationship(
Address,
collection_class=collections.attribute_mapped_collection(
"email_address"
),
)
},
)
mapper(Address, addresses)
u1 = User()
u1.addresses["e1"] = "e1"
u1.addresses["e2"] = "e2"
eq_(
u1.addresses,
{
"e1": Address(email_address="e1"),
"e2": Address(email_address="e2"),
},
)
u1.addresses = {"e3": "e3", "e4": "e4"}
eq_(
u1.addresses,
{
"e3": Address(email_address="e3"),
"e4": Address(email_address="e4"),
},
)
示例8: setup
def setup():
"""
Set up ORM.
Does not create any database tables, see :py:func:`create_tables`
for that.
"""
global resource_metadata_table
if resource_metadata_table is None:
log.debug('Defining resource metadata table')
resource_metadata_table = Table(
RESOURCE_METADATA_TABLE_NAME,
metadata,
Column('resource_id', types.UnicodeText, ForeignKey('resource.id',
ondelete='CASCADE', onupdate='CASCADE'), nullable=False,
primary_key=True),
Column('last_extracted', types.DateTime),
Column('last_url', types.UnicodeText),
Column('last_format', types.UnicodeText),
Column('task_id', types.UnicodeText)
)
mapper(
ResourceMetadata,
resource_metadata_table,
properties={
'_meta': relationship(ResourceMetadatum, collection_class=
attribute_mapped_collection('key'),
cascade='all, delete, delete-orphan'),
}
)
else:
log.debug('Resource metadata table already defined')
global resource_metadatum_table
if resource_metadatum_table is None:
log.debug('Defining resource metadatum table')
resource_metadatum_table = Table(
RESOURCE_METADATUM_TABLE_NAME,
metadata,
Column('id', types.Integer, nullable=False, primary_key=True),
Column('resource_id', types.UnicodeText, ForeignKey(
RESOURCE_METADATA_TABLE_NAME + '.resource_id',
ondelete='CASCADE', onupdate='CASCADE'), nullable=False),
Column('key', types.UnicodeText, nullable=False),
Column('value', types.UnicodeText)
)
mapper(ResourceMetadatum, resource_metadatum_table)
else:
log.debug('Resource metadatum table already defined')
示例9: test_attribute_mapped_collection
def test_attribute_mapped_collection(self):
users, addresses = self.tables.users, self.tables.addresses
mapper(User, users, properties={
'addresses': relationship(
Address,
collection_class=attribute_mapped_collection('email_address')
)
})
mapper(Address, addresses)
u1 = User()
u1.addresses = {"email1": Address(email_address="email1")}
for loads, dumps in picklers():
repickled = loads(dumps(u1))
eq_(u1.addresses, repickled.addresses)
eq_(repickled.addresses['email1'],
Address(email_address="email1"))
示例10: variable_association
def variable_association(cls):
name = cls.__name__
discriminator = name.lower()
# Defines a polymorphic class to distinguish variables stored
# for regions, cells, etc.
cls.variable_assoc_cls = assoc_cls = type(
"%sVariableAssociation" % name,
(VariableAssociation,),
{
'__tablename__': None, # because mapping into a shared table
'__mapper_args__': {
'polymorphic_identity': discriminator
}
})
def _assoc_creator(kv):
assoc = assoc_cls()
for key, value in kv.items():
assoc.variables[key] = Variable(key=key, value=value)
return assoc
cls._variables = association_proxy(
'variable_association', 'variables', creator=_assoc_creator)
# Using a composite associative proxy here enables returning the
# underlying values for a given key, as opposed to the
# Variable object; we need both.
cls.variables = association_proxy(
'variable_association', 'values', creator=_assoc_creator)
def with_characteristic(self, key, value):
return self._variables.any(key=key, value=value)
cls.with_characteristic = classmethod(with_characteristic)
rel = relationship(
assoc_cls,
collection_class=attribute_mapped_collection('key'),
cascade='all, delete-orphan', lazy='joined',
single_parent=True,
backref=backref('parent', uselist=False))
return rel
示例11: setup
def setup(self):
class B(object):
def __init__(self, key, elem):
self.key = key
self.elem = elem
class A(object):
elements = association_proxy("orig", "elem", creator=B)
m = MetaData()
a = Table('a', m, Column('id', Integer, primary_key=True))
b = Table('b', m, Column('id', Integer, primary_key=True),
Column('aid', Integer, ForeignKey('a.id')))
mapper(A, a, properties={
'orig':relationship(B, collection_class=attribute_mapped_collection('key'))
})
mapper(B, b)
self.A = A
self.B = B
示例12: assign_translations
def assign_translations(self):
"""
Assigns translations relationship for translatable model. The assigned
attribute is a relationship to all translation locales.
"""
mapper = sa.orm.class_mapper(self.parent_cls)
if not mapper.has_property('_translations'):
foreign_keys = [
getattr(self.translation_cls, column_key)
for column_key in get_primary_keys(self.parent_cls).keys()
]
mapper.add_property('_translations', sa.orm.relationship(
self.translation_cls,
primaryjoin=sa.and_(*self.primary_key_conditions),
foreign_keys=foreign_keys,
collection_class=attribute_mapped_collection('locale'),
comparator_factory=TranslationComparator,
cascade='all, delete-orphan',
passive_deletes=option(self.parent_cls, 'passive_deletes'),
))
示例13: InitMapper
def InitMapper( cls, metadata, Design, Component ):
cls.__table__ = Table( cls.__tablename__, metadata,
Column('design_id', ForeignKey( Design.id ), primary_key = True ),
Column('component_id', ForeignKey( Component.id ), primary_key = True ),
Column('amount', Integer, nullable = False, default = 1 ))
cols = cls.__table__.c
Index('ix_%s_design_component' % cls.__tablename__, cols.design_id, cols.component_id)
mapper( cls, cls.__table__, properties = {
'design': relation( Design,
uselist = False ),
'component': relation( Component,
uselist = False )
})
class_mapper( Design ).add_property( '_components',
relation( cls, collection_class = attribute_mapped_collection('component') ))
Design.components = association_proxy('_components', 'amount', creator = lambda k,v: cls( component = k, amount = v ) )
示例14: InitMapper
def InitMapper( cls, metadata, Component, Property ):
cls.__table__ = Table( cls.__tablename__, metadata,
Column('component_id', Integer, ForeignKey( Component.id ), primary_key = True ),
Column('property_id', Integer, ForeignKey( Property.id ), primary_key = True ),
Column('value', Text, nullable = False, default = """(lambda (design) 1)""" ))
cols = cls.__table__.c
Index('ix_%s_component_property' % cls.__tablename__, cols.component_id, cols.property_id)
mapper( cls, cls.__table__, properties = {
'component': relation( Component,
uselist = False ),
'property': relation( Property,
uselist = False )
})
class_mapper( Component ).add_property( '_properties',
relation( cls, collection_class = attribute_mapped_collection('property') ))
Component.properties = association_proxy('_properties', 'value', creator = lambda k,v: cls( property = k, value = v ) )
示例15: __init__
def __init__(self):
try:
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import mapper, relationship
from sqlalchemy.orm.collections import attribute_mapped_collection
except ImportError:
raise ImportError('Interaction with SQL based databases requires SQLAlchemy')
self.metadata = MetaData()
self.framework = Table('framework', self.metadata,
Column('id', Integer, primary_key=True),
Column('name', String(250)))
self.argument = Table('argument', self.metadata,
Column('id', Integer, primary_key=True),
Column('name', String(250)),
Column('framework_id', Integer, ForeignKey('framework.id')))
self.attack= Table('attack', self.metadata,
Column('id', Integer, primary_key=True),
Column('attacker_id', Integer, ForeignKey('argument.id')),
Column('target_id', Integer, ForeignKey('argument.id')))
mapper(al.ArgumentationFramework, self.framework, properties={
'argument' : relationship(al.Argument, backref='framework'),
'arguments' : relationship(al.Argument,
collection_class=attribute_mapped_collection('name'),
cascade="all, delete-orphan")
})
mapper(al.Argument, self.argument, properties={
'attacks' : relationship(al.Argument,
secondary=self.attack,
primaryjoin=self.argument.c.id==self.attack.c.attacker_id,
secondaryjoin=self.argument.c.id==self.attack.c.target_id,
collection_class=set)
})