sqlalchemy.ext.associationproxy.association_proxy

Here are the examples of the python api sqlalchemy.ext.associationproxy.association_proxy taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

21 Examples 7

Example 1

Project: ggrc-core Source File: audit_object.py
  @declared_attr
  def audit_objects(cls):
    cls.audits = association_proxy(
        'audit_objects', 'audit',
        creator=lambda control: AuditObject(
            audit=audit,  # noqa
            auditable_type=cls.__name__,
        )
    )
    joinstr = 'and_(foreign(AuditObject.auditable_id) == {type}.id, '\
        'foreign(AuditObject.auditable_type) == "{type}")'
    joinstr = joinstr.format(type=cls.__name__)
    return db.relationship(
        'AuditObject',
        primaryjoin=joinstr,
        backref='{0}_auditable'.format(cls.__name__),
        cascade='all, delete-orphan',
    )

Example 2

Project: ggrc-core Source File: object_document.py
  @declared_attr
  def object_docuements(cls):
    cls.docuements = association_proxy(
        'object_docuements', 'docuement',
        creator=lambda docuement: ObjectDocuement(
            docuement=docuement,
            docuementable_type=cls.__name__,
        )
    )
    joinstr = ('and_(foreign(ObjectDocuement.docuementable_id) == {type}.id, '
               '     foreign(ObjectDocuement.docuementable_type) == "{type}")')
    joinstr = joinstr.format(type=cls.__name__)
    return db.relationship(
        'ObjectDocuement',
        primaryjoin=joinstr,
        backref='{0}_docuementable'.format(cls.__name__),
        cascade='all, delete-orphan',
    )

Example 3

Project: ggrc-core Source File: object_owner.py
  @declared_attr
  def object_owners(cls):
    cls.owners = association_proxy(
        'object_owners', 'person',
        creator=lambda person: ObjectOwner(
            person=person,
            ownable_type=cls.__name__,
        )
    )
    joinstr = 'and_(foreign(ObjectOwner.ownable_id) == {type}.id, '\
        'foreign(ObjectOwner.ownable_type) == "{type}")'
    joinstr = joinstr.format(type=cls.__name__)
    return db.relationship(
        'ObjectOwner',
        primaryjoin=joinstr,
        backref='{0}_ownable'.format(cls.__name__),
        cascade='all, delete-orphan',
    )

Example 4

Project: ggrc-core Source File: object_person.py
  @declared_attr
  def object_people(cls):
    cls.people = association_proxy(
        'object_people', 'person',
        creator=lambda person: ObjectPerson(
            person=person,
            personable_type=cls.__name__,
        )
    )
    joinstr = 'and_(foreign(ObjectPerson.personable_id) == {type}.id, '\
        'foreign(ObjectPerson.personable_type) == "{type}")'
    joinstr = joinstr.format(type=cls.__name__)
    return db.relationship(
        'ObjectPerson',
        primaryjoin=joinstr,
        backref='{0}_personable'.format(cls.__name__),
        cascade='all, delete-orphan',
    )

Example 5

Project: flask-permissions Source File: models.py
Function: roles
    @declared_attr
    def roles(self):
        return association_proxy('_roles', 'name', creator=_role_find_or_create)

Example 6

Project: iktomi Source File: replication.py
    def test_replicate_m2m_ordered(self):
        # Schema
        class A1(self.Base):
            id = Column(Integer, primary_key=True)
            data = Column(String)
            _ab = relationship('AB1', order_by='AB1.position',
                               cascade='all,delete-orphan',
                               collection_class=ordering_list('position'))
            b = association_proxy('_ab', 'b', creator=lambda b: AB1(b=b))
        class B1(self.Base):
            id = Column(Integer, primary_key=True)
        class AB1(self.Base):
            a_id = Column(ForeignKey(A1.id), nullable=False, primary_key=True)
            b_id = Column(ForeignKey(B1.id), nullable=False, primary_key=True)
            b = relationship(B1)
            position = Column(Integer, nullable=False)
        class A2(self.Base):
            id = Column(Integer, primary_key=True)
            data = Column(String)
            _ab = relationship('AB2', order_by='AB2.position',
                               cascade='all,delete-orphan',
                               collection_class=ordering_list('position'))
            b = association_proxy('_ab', 'b', creator=lambda b: AB2(b=b))
        class B2(self.Base):
            id = Column(Integer, primary_key=True)
        class AB2(self.Base):
            a_id = Column(ForeignKey(A2.id), nullable=False, primary_key=True)
            b_id = Column(ForeignKey(B2.id), nullable=False, primary_key=True)
            b = relationship(B2)
            position = Column(Integer, nullable=False)
        self.create_all()
        # Data
        with self.db.begin():
            b11 = B1(id=2)
            b12 = B1(id=4)
            a1 = A1(id=2, b=[b11, b12])
            b21 = B2(id=2)
            self.db.add_all([a1, b21])
        # Test with 2 children: one with existing reflection and one without it
        with self.db.begin():
            a2 = replication.replicate(a1, A2)
        self.assertEqual(len(a2.b), 1)
        self.assertEqual(a2.b[0].id, 2)
        # Insert into front
        with self.db.begin():
            b13 = B1(id=6)
            b23 = B2(id=6)
            self.db.add_all([b13, b23])
        with self.db.begin():
            a1.b = [b13, b11]
            a2 = replication.replicate(a1, A2)
        self.assertEqual(len(a2.b), 2)
        self.assertEqual(a2.b[0].id, 6)
        self.assertEqual(a2.b[1].id, 2)
        # Change order
        with self.db.begin():
            a1.b = [b11, b13]
            a2 = replication.replicate(a1, A2)
        self.assertEqual(len(a2.b), 2)
        self.assertEqual(a2.b[0].id, 2)
        self.assertEqual(a2.b[1].id, 6)
        # Remove
        with self.db.begin():
            a1.b = []
            a2 = replication.replicate(a1, A2)
        self.assertEqual(len(a2.b), 0)

Example 7

Project: iktomi Source File: replication.py
    def test_replication_o2m_dict(self):
        # Schema
        class P1(self.Base):
            id = Column(Integer, primary_key=True)
            _children = relationship(
                        'C1', cascade='all,delete-orphan',
                        collection_class=attribute_mapped_collection('key'))
            children = association_proxy(
                        '_children', 'value',
                        creator=lambda k, v: C1(key=k, value=v))
        class C1(self.Base):
            parent_id = Column(ForeignKey(P1.id), nullable=False,
                               primary_key=True)
            parent = relationship(P1)
            key = Column(String(10), nullable=False, primary_key=True)
            value = Column(String)
        class P2(self.Base):
            id = Column(Integer, primary_key=True)
            _children = relationship(
                        'C2', cascade='all,delete-orphan',
                        collection_class=attribute_mapped_collection('key'))
            children = association_proxy(
                        '_children', 'value',
                        creator=lambda k, v: C1(key=k, value=v))
        class C2(self.Base):
            parent_id = Column(ForeignKey(P2.id), nullable=False,
                               primary_key=True)
            parent = relationship(P2)
            key = Column(String(10), nullable=False, primary_key=True)
            value = Column(String)
        self.create_all()
        # Data
        with self.db.begin():
            p1 = P1(children={'k1': 'v11', 'k2': 'v2'})
            self.db.add(p1)
        # New
        with self.db.begin():
            p2 = replication.replicate(p1, P2)
        self.assertEqual(p2.children, {'k1': 'v11', 'k2': 'v2'})
        # Update
        with self.db.begin():
            p1.children['k1'] = 'v12'
            del p1.children['k2']
            p1.children['k3'] = 'v3'
            self.db.flush() # XXX Fails without this
            p2 = replication.replicate(p1, P2)
        self.assertEqual(p2.children, {'k1': 'v12', 'k3': 'v3'})

Example 8

Project: sopython-site Source File: models.py
Function: tags
    @declared_attr
    def tags(cls):
        return association_proxy('_tags', 'name', creator=Tag.get_unique)

Example 9

Project: pokedex Source File: multilang.py
def create_translation_table(_table_name, foreign_class, relation_name,
    language_class, relation_lazy='select', **kwargs):
    """Creates a table that represents some kind of data attached to the given
    foreign class, but translated across several languages.  Returns the new
    table's mapped class.  It won't be declarative, but it will have a
    `__table__` attribute so you can retrieve the Table object.

    `foreign_class` must have a `__singlename__`, currently only used to create
    the name of the foreign key column.

    Also supports the notion of a default language, which is attached to the
    session.  This is English by default, for historical and practical reasons.

    Usage looks like this:

        class Foo(Base): ...

        create_translation_table('foo_bars', Foo, 'bars',
            name = Column(...),
        )

        # Now you can do the following:
        foo.name
        foo.name_map['en']
        foo.foo_bars['en']

        foo.name_map['en'] = "new name"
        del foo.name_map['en']

        q.options(joinedload(Foo.bars_local))
        q.options(joinedload(Foo.bars))

    The following properties are added to the passed class:

    - `(relation_name)`, a relation to the new table.  It uses a dict-based
      collection class, where the keys are language identifiers and the values
      are rows in the created tables.
    - `(relation_name)_local`, a relation to the row in the new table that
      matches the current default language.
    - `(relation_name)_table`, the class created by this function.

    Note that these are distinct relations.  Even though the former necessarily
    includes the latter, SQLAlchemy doesn't treat them as linked; loading one
    will not load the other.  Modifying both within the same transaction has
    undefined behavior.

    For each column provided, the following additional attributes are added to
    Foo:

    - `(column)_map`, an association proxy onto `foo_bars`.
    - `(column)`, an association proxy onto `foo_bars_local`.

    Pardon the naming disparity, but the grammar suffers otherwise.

    Modifying these directly is not likely to be a good idea.

    For Markdown-formatted columns, `(column)_map` and `(column)` will give
    Markdown objects.
    """
    # n.b.: language_class only exists for the sake of tests, which sometimes
    # want to create tables entirely separate from the pokedex metadata

    foreign_key_name = foreign_class.__singlename__ + '_id'

    Translations = type(_table_name, (object,), {
        '_language_identifier': association_proxy('local_language', 'identifier'),
        'relation_name': relation_name,
        '__tablename__': _table_name,
    })

    # Create the table object
    table = Table(_table_name, foreign_class.__table__.metadata,
        Column(foreign_key_name, Integer, ForeignKey(foreign_class.id),
            primary_key=True, nullable=False,
            doc=u"ID of the %s these texts relate to" % foreign_class.__singlename__),
        Column('local_language_id', Integer, ForeignKey(language_class.id),
            primary_key=True, nullable=False,
            doc=u"Language these texts are in"),
    )
    Translations.__table__ = table

    # Add ye columns
    # Column objects have a _creation_order attribute in ascending order; use
    # this to get the (unordered) kwargs sorted correctly
    kwitems = list(kwargs.items())
    kwitems.sort(key=lambda kv: kv[1]._creation_order)
    for name, column in kwitems:
        column.name = name
        table.append_column(column)

    # Construct ye mapper
    mapper(Translations, table, properties={
        'foreign_id': synonym(foreign_key_name),
        'local_language': relationship(language_class,
            primaryjoin=table.c.local_language_id == language_class.id,
            innerjoin=True),
    })

    # Add full-table relations to the original class
    # Foo.bars_table
    setattr(foreign_class, relation_name + '_table', Translations)
    # Foo.bars
    setattr(foreign_class, relation_name, relationship(Translations,
        primaryjoin=foreign_class.id == Translations.foreign_id,
        collection_class=attribute_mapped_collection('local_language'),
    ))
    # Foo.bars_local
    # This is a bit clever; it uses bindparam() to make the join clause
    # modifiable on the fly.  db sessions know the current language and
    # populate the bindparam.
    # The 'dummy' value is to trick SQLA; without it, SQLA thinks this
    # bindparam is just its own auto-generated clause and everything gets
    # cuemed up.
    local_relation_name = relation_name + '_local'
    setattr(foreign_class, local_relation_name, relationship(Translations,
        primaryjoin=and_(
            Translations.foreign_id == foreign_class.id,
            Translations.local_language_id == bindparam('_default_language_id',
                value='dummy', type_=Integer, required=True),
        ),
        foreign_keys=[Translations.foreign_id, Translations.local_language_id],
        uselist=False,
        lazy=relation_lazy,
    ))

    # Add per-column proxies to the original class
    for name, column in kwitems:
        getset_factory = None
        string_getter = column.info.get('string_getter')
        if string_getter:
            getset_factory = _getset_factory_factory(
                column.name, string_getter)

        # Class.(column) -- accessor for the default language's value
        setattr(foreign_class, name,
            LocalAssociationProxy(local_relation_name, name,
                    getset_factory=getset_factory))

        # Class.(column)_map -- accessor for the language dict
        # Need a custom creator since Translations doesn't have an init, and
        # these are passed as *args anyway
        def creator(language, value):
            row = Translations()
            row.local_language = language
            setattr(row, name, value)
            return row
        setattr(foreign_class, name + '_map',
            association_proxy(relation_name, name, creator=creator,
                    getset_factory=getset_factory))

    # Add to the list of translation classes
    foreign_class.translation_classes.append(Translations)

    # Done
    return Translations

Example 10

Project: sqlalchemy Source File: discriminator_on_association.py
    @declared_attr
    def address_association(cls):
        name = cls.__name__
        discriminator = name.lower()

        assoc_cls = type(
                        "%sAddressAssociation" % name,
                        (AddressAssociation, ),
                        dict(
                            __tablename__=None,
                            __mapper_args__={
                                "polymorphic_identity": discriminator
                            }
                        )
                    )

        cls.addresses = association_proxy(
                    "address_association", "addresses",
                    creator=lambda addresses: assoc_cls(addresses=addresses)
                )
        return relationship(assoc_cls,
                    backref=backref("parent", uselist=False))

Example 11

Project: sqlalchemy Source File: test_inspect.py
    def test_extension_types(self):
        from sqlalchemy.ext.associationproxy import \
                                        association_proxy, ASSOCIATION_PROXY
        from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method, \
                                        HYBRID_PROPERTY, HYBRID_METHOD
        from sqlalchemy import Table, MetaData, Integer, Column
        from sqlalchemy.orm import mapper
        from sqlalchemy.orm.interfaces import NOT_EXTENSION

        class SomeClass(self.classes.User):
            some_assoc = association_proxy('addresses', 'email_address')

            @hybrid_property
            def upper_name(self):
                raise NotImplementedError()

            @hybrid_method
            def conv(self, fn):
                raise NotImplementedError()

        class SomeSubClass(SomeClass):
            @hybrid_property
            def upper_name(self):
                raise NotImplementedError()

            @hybrid_property
            def foo(self):
                raise NotImplementedError()

        t = Table('sometable', MetaData(),
                        Column('id', Integer, primary_key=True))
        mapper(SomeClass, t)
        mapper(SomeSubClass, inherits=SomeClass)

        insp = inspect(SomeSubClass)
        eq_(
            dict((k, v.extension_type)
                for k, v in list(insp.all_orm_descriptors.items())
            ),
            {
                'id': NOT_EXTENSION,
                'name': NOT_EXTENSION,
                'name_syn': NOT_EXTENSION,
                'addresses': NOT_EXTENSION,
                'orders': NOT_EXTENSION,
                'upper_name': HYBRID_PROPERTY,
                'foo': HYBRID_PROPERTY,
                'conv': HYBRID_METHOD,
                'some_assoc': ASSOCIATION_PROXY
            }
        )
        is_(
            insp.all_orm_descriptors.upper_name,
            SomeSubClass.__dict__['upper_name']
        )
        is_(
            insp.all_orm_descriptors.some_assoc,
            SomeClass.some_assoc
        )
        is_(
            inspect(SomeClass).all_orm_descriptors.upper_name,
            SomeClass.__dict__['upper_name']
        )

Example 12

Project: floof Source File: __init__.py
def make_resource_type(cls):
    """For table-classes that are resources.  Installs a backref on Resource
    that finds the original class.

    Also adds a 'discussion' association-proxy shortcut.
    """

    mapper = class_mapper(cls)
    table = mapper.local_table
    mapper.add_property('resource', relation(
        Resource,
        innerjoin=True,
        backref=backref(
            '_backref_%s' % table.name, uselist=False, innerjoin=True),
    ))

    # Attach a 'discussion' shortcut
    for resource_property in ('discussion',):
        setattr(cls, resource_property,
            association_proxy('resource', resource_property))

    return cls

Example 13

Project: papyrus Source File: test_geo_interface.py
    def _get_mapped_class_declarative(self):
        from sqlalchemy import MetaData, Column, types, orm, schema
        from sqlalchemy.ext.declarative import declarative_base
        from sqlalchemy.ext.associationproxy import association_proxy
        from geoalchemy2.types import Geometry
        from papyrus.geo_interface import GeoInterface
        Base = declarative_base(metadata=MetaData())

        class Child1(Base):
            __tablename__ = 'child1'
            id = Column(types.Integer, primary_key=True)
            name = Column(types.Unicode)
            parent_id = Column(types.Integer, schema.ForeignKey('parent.id'))

            def __init__(self, name):
                self.name = name

        class Child2(Base):
            __tablename__ = 'child2'
            id = Column(types.Integer, primary_key=True)
            name = Column(types.Unicode)

            def __init__(self, name):
                self.name = name

        class Parent(GeoInterface, Base):
            __tablename__ = 'parent'
            id = Column(types.Integer, primary_key=True)
            text = Column(types.Unicode)
            geom = Column(Geometry(geometry_type='GEOMETRY', dimension=2,
                                   srid=3000))
            children_ = orm.relationship(Child1, backref="parent")
            child_id = Column(types.Integer, schema.ForeignKey('child2.id'))
            child_ = orm.relationship(Child2)

            children = association_proxy('children_', 'name')
            child = association_proxy('child_', 'name')
            __add_properties__ = ('child', 'children')

        return Parent

Example 14

Project: papyrus Source File: test_geo_interface.py
    def _get_mapped_class_declarative_as_base(self):
        from sqlalchemy import MetaData, Column, types, orm, schema
        from sqlalchemy.ext.declarative import declarative_base
        from sqlalchemy.ext.associationproxy import association_proxy
        from geoalchemy2.types import Geometry
        from papyrus.geo_interface import GeoInterface
        Base = declarative_base(metadata=MetaData(), cls=GeoInterface,
                                constructor=None)

        class Child1(Base):
            __tablename__ = 'child1'
            id = Column(types.Integer, primary_key=True)
            name = Column(types.Unicode)
            parent_id = Column(types.Integer, schema.ForeignKey('parent.id'))

            def __init__(self, name):
                self.name = name

        class Child2(Base):
            __tablename__ = 'child2'
            id = Column(types.Integer, primary_key=True)
            name = Column(types.Unicode)

            def __init__(self, name):
                self.name = name

        class Parent(Base):
            __tablename__ = 'parent'
            id = Column(types.Integer, primary_key=True)
            text = Column(types.Unicode)
            geom = Column(Geometry(geometry_type='GEOMETRY', dimension=2,
                                   srid=3000))
            children_ = orm.relationship(Child1, backref="parent")
            child_id = Column(types.Integer, schema.ForeignKey('child2.id'))
            child_ = orm.relationship(Child2)

            children = association_proxy('children_', 'name')
            child = association_proxy('child_', 'name')
            __add_properties__ = ('child', 'children')

        return Parent

Example 15

Project: papyrus Source File: test_geo_interface.py
    def _get_mapped_class_non_declarative(self):
        from sqlalchemy import Table, MetaData, Column, types, orm, schema
        from sqlalchemy.ext.associationproxy import association_proxy
        from papyrus.geo_interface import GeoInterface
        from geoalchemy2.types import Geometry

        md = MetaData()

        child1_table = Table(
            'child1', md,
            Column('id', types.Integer, primary_key=True),
            Column('name', types.Unicode),
            Column('parent_id', types.Integer, schema.ForeignKey('parent.id'))
            )

        child2_table = Table(
            'child2', md,
            Column('id', types.Integer, primary_key=True),
            Column('name', types.Unicode)
            )

        parent_table = Table(
            'parent', md,
            Column('id', types.Integer, primary_key=True),
            Column('text', types.Unicode),
            Column('geom', Geometry(geometry_type='GEOMETRY',
                                    dimension=2, srid=3000)),
            Column('child_id', types.Integer, schema.ForeignKey('child2.id'))
            )

        class Child1(object):
            def __init__(self, name):
                self.name = name

        orm.mapper(Child1, child1_table)

        class Child2(object):
            def __init__(self, name):
                self.name = name

        orm.mapper(Child2, child2_table)

        class Parent(GeoInterface):
            children = association_proxy('children_', 'name')
            child = association_proxy('child_', 'name')
            __add_properties__ = ('child', 'children')

        orm.mapper(Parent, parent_table,
                   properties={
                       'children_': orm.relationship(Child1),
                       'child_': orm.relationship(Child2)
                   })
        return Parent

Example 16

Project: ggrc-core Source File: categorization.py
  @classmethod
  def declare_categorizable(cls, category_type, single, plural, ation):
    setattr(
        cls, plural,
        association_proxy(
            ation, 'category',
            creator=lambda category: Categorization(
                category_id=category.id,
                category_type=category.__class__.__name__,
                categorizable_type=cls.__name__
            )
        )
    )

    joinstr = (
        'and_('
        'foreign(Categorization.categorizable_id) == {type}.id, '
        'foreign(Categorization.categorizable_type) == "{type}", '
        'foreign(Categorization.category_type) == "{category_type}"'
        ')'
    )
    joinstr = joinstr.format(type=cls.__name__, category_type=category_type)
    backref = '{type}_categorizable_{category_type}'.format(
        type=cls.__name__,
        category_type=category_type,
    )
    return db.relationship(
        'Categorization',
        primaryjoin=joinstr,
        backref=backref,
        cascade='all, delete-orphan',
    )

Example 17

Project: ggrc-core Source File: risk_object.py
  @classmethod
  def late_init_riskable(cls):
    def make_risk_objects(cls):
      cls.risks = association_proxy(
          'risk_objects', 'risk',
          creator=lambda risk: RiskObject(
              risk=risk,
              object_type=cls.__name__,
          )
      )
      joinstr = 'and_(foreign(RiskObject.object_id) == {type}.id, '\
          'foreign(RiskObject.object_type) == "{type}")'
      joinstr = joinstr.format(type=cls.__name__)
      return db.relationship(
          'RiskObject',
          primaryjoin=joinstr,
          backref='{0}_object'.format(cls.__name__),
          cascade='all, delete-orphan',
      )
    cls.risk_objects = make_risk_objects(cls)

Example 18

Project: ggrc-core Source File: task_group_object.py
  @classmethod
  def late_init_task_groupable(cls):
    def make_task_group_objects(cls):
      cls.task_groups = association_proxy(
          'task_group_objects', 'task_group',
          creator=lambda task_group: TaskGroupObject(
              task_group=task_group,
              object_type=cls.__name__,
          )
      )
      joinstr = 'and_(foreign(TaskGroupObject.object_id) == {type}.id, '\
                'foreign(TaskGroupObject.object_type) == "{type}")'
      joinstr = joinstr.format(type=cls.__name__)
      return db.relationship(
          'TaskGroupObject',
          primaryjoin=joinstr,
          backref='{0}_object'.format(cls.__name__),
          cascade='all, delete-orphan',
      )
    cls.task_group_objects = make_task_group_objects(cls)

Example 19

Project: flask-restless Source File: test_creating.py
    def setUp(self):
        """Creates the database, the :class:`~flask.Flask` object, the
        :class:`~flask_restless.manager.APIManager` for that application,
        and creates the ReSTful API endpoints for the models used in the test
        methods.

        """
        super(TestAssociationProxy, self).setUp()

        class Article(self.Base):
            __tablename__ = 'article'
            id = Column(Integer, primary_key=True)
            tags = association_proxy('articletags', 'tag',
                                     creator=lambda tag: ArticleTag(tag=tag))

        class ArticleTag(self.Base):
            __tablename__ = 'articletag'
            article_id = Column(Integer, ForeignKey('article.id'),
                                primary_key=True)
            article = relationship(Article, backref=backref('articletags'))
            tag_id = Column(Integer, ForeignKey('tag.id'), primary_key=True)
            tag = relationship('Tag')
            # TODO this dummy column is required to create an API for this
            # object.
            id = Column(Integer)

        class Tag(self.Base):
            __tablename__ = 'tag'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode)

        # HACK It seems that if we don't persist the Article class then
        # the test sometimes gets confused about which Article class is
        # being referenced in requests made in the test methods below.
        self.Article = Article
        self.Tag = Tag
        self.Base.metadata.create_all()
        self.manager.create_api(self.Article, methods=['POST'])
        # HACK Need to create APIs for these other models because otherwise
        # we're not able to create the link URLs to them.
        #
        # TODO Fix this by simply not creating links to related models for
        # which no API has been made.
        self.manager.create_api(Tag)
        self.manager.create_api(ArticleTag)

Example 20

Project: flask-restless Source File: test_updating.py
    def setUp(self):
        """Creates the database, the :class:`~flask.Flask` object, the
        :class:`~flask_restless.manager.APIManager` for that application,
        and creates the ReSTful API endpoints for the models used in the test
        methods.

        """
        super(TestAssociationProxy, self).setUp()

        class Article(self.Base):
            __tablename__ = 'article'
            id = Column(Integer, primary_key=True)
            tags = association_proxy('articletags', 'tag',
                                     creator=lambda tag: ArticleTag(tag=tag))

        class ArticleTag(self.Base):
            __tablename__ = 'articletag'
            article_id = Column(Integer, ForeignKey('article.id'),
                                primary_key=True)
            article = relationship(Article, backref=backref('articletags'))
            tag_id = Column(Integer, ForeignKey('tag.id'), primary_key=True)
            tag = relationship('Tag')
            # This is extra information that only appears in this association
            # object.
            extrainfo = Column(Unicode)
            # TODO this dummy column is required to create an API for this
            # object.
            id = Column(Integer)

        class Tag(self.Base):
            __tablename__ = 'tag'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode)

        self.Article = Article
        self.ArticleTag = ArticleTag
        self.Tag = Tag
        self.Base.metadata.create_all()
        self.manager.create_api(Article, methods=['PATCH'])
        # HACK Need to create APIs for these other models because otherwise
        # we're not able to create the link URLs to them.
        #
        # TODO Fix this by simply not creating links to related models for
        # which no API has been made.
        self.manager.create_api(Tag)
        self.manager.create_api(ArticleTag)

Example 21

Project: sqlalchemy-continuum Source File: transaction_meta.py
    def create_class(self, manager):
        """
        Create TransactionMeta class.
        """
        class TransactionMeta(
            manager.declarative_base,
            TransactionMetaBase
        ):
            __tablename__ = 'transaction_meta'

        TransactionMeta.transaction = sa.orm.relationship(
            manager.transaction_cls,
            backref=sa.orm.backref(
                'meta_relation',
                collection_class=attribute_mapped_collection('key')
            ),
            primaryjoin=(
                '%s.id == TransactionMeta.transaction_id' %
                manager.transaction_cls.__name__
            ),
            foreign_keys=[TransactionMeta.transaction_id]
        )

        manager.transaction_cls.meta = association_proxy(
            'meta_relation',
            'value',
            creator=lambda key, value: TransactionMeta(key=key, value=value)
        )

        return TransactionMeta