• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python orm.synonym函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sqlalchemy.orm.synonym函数的典型用法代码示例。如果您正苦于以下问题:Python synonym函数的具体用法?Python synonym怎么用?Python synonym使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了synonym函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_evaluate_double_synonym_attr

    def test_evaluate_double_synonym_attr(self):
        class Foo(object):
            pass
        mapper(Foo, self.tables.users, properties={
            'uname': synonym("name"),
            'ufoo': synonym('uname')
        })

        s = Session()
        jill = s.query(Foo).get(3)
        s.query(Foo).update(
            {Foo.ufoo: 'moonbeam'},
            synchronize_session='evaluate')
        eq_(jill.ufoo, 'moonbeam')
开发者ID:CyberCollins,项目名称:sqlalchemy,代码行数:14,代码来源:test_update_delete.py


示例2: MongoReference

def MongoReference(field, ref_cls, queryset=None):
    """
    Reference to a MongoDB document.

    The value is cached until an assignment is made.

    To use a custom queryset (instead of the default `ref_cls.objects`),
    pass it as the `queryset` kwarg.
    """
    if queryset is None:
        queryset = ref_cls.objects

    def _get(obj):
        if not hasattr(obj, '_%s__cache' % field):
            ref_id = getattr(obj, field)
            if ref_id is None:
                ref = None
            else:
                ref = queryset.get(pk=ref_id)
            setattr(obj, '_%s__cache' % field, ref)
        return getattr(obj, '_%s__cache' % field)

    def _set(obj, val):
        if hasattr(obj, '_%s__cache' % field):
            delattr(obj, '_%s__cache' % field)
        if isinstance(val, ref_cls):
            val = val.pk
        if isinstance(val, ObjectId):
            val = str(val)
        setattr(obj, field, val)

    return synonym(field, descriptor=property(_get, _set))
开发者ID:closeio,项目名称:flask-common,代码行数:32,代码来源:db.py


示例3: setup_orm

def setup_orm():
    tables = meta.metadata.tables
    columns = tables['group_mailing_list_messages'].c
    orm.mapper(GroupMailingListMessage,
               tables['group_mailing_list_messages'],
               inherits=ContentItem,
               polymorphic_identity='mailing_list_message',
               polymorphic_on=tables['content_items'].c.content_type,
               properties = {
                             'reply_to': relation(GroupMailingListMessage,
                                                  backref=backref('replies'),
                                                  foreign_keys=(columns.reply_to_message_machine_id),
                                                  primaryjoin=columns.id == columns.reply_to_message_machine_id,
                                                  remote_side=(columns.id)),
                             'thread': relation(GroupMailingListMessage,
                                                post_update=True,
                                                order_by=[asc(columns.sent)],
                                                backref=backref('posts'),
                                                foreign_keys=(columns.thread_message_machine_id),
                                                primaryjoin=columns.id == columns.thread_message_machine_id,
                                                remote_side=(columns.id)),
                             'author': relation(User,
                                                backref=backref('messages')),
                             'group': relation(Group,
                                               primaryjoin=(columns.group_id == tables['groups'].c.id)),
                             'attachments': synonym("files")
                             })
开发者ID:nous-consulting,项目名称:ututi,代码行数:27,代码来源:mailing.py


示例4: test_synonym_comparable

    def test_synonym_comparable(self):
        users = self.tables.users

        class User(object):
            class Comparator(PropComparator):
                pass

            def _getValue(self):
                return self._value

            def _setValue(self, value):
                setattr(self, "_value", value)

            value = property(_getValue, _setValue)

        mapper(
            User, users, properties={"uid": synonym("id"), "foobar": comparable_property(User.Comparator, User.value)}
        )

        sess = create_session()
        u = User()
        u.name = "ed"
        sess.add(u)
        sess.flush()
        sess.expunge(u)
        sess.merge(u)
开发者ID:pugong,项目名称:sqlalchemy,代码行数:26,代码来源:test_merge.py


示例5: _set_password

 def _set_password(self, password):
     if password:
         self._password = generate_password_hash(password)
         password_descriptor = property(self._get_password,
                                        self._set_password)
         password = synonym('_password',
                            descriptor=password_descriptor)
开发者ID:brisiacorona,项目名称:ProyectoFinalTDD,代码行数:7,代码来源:models.py


示例6: _get_password

    def _get_password(self):
    	return self._password

	def _set_password(self, password):
		self._password = hash_password(password)

	password = property(_get_password, _set_password)
	password = synonym('_password', descriptor=password)

	def __init__(self, username, password, name, email):
		self.username = username
		self.name = name
		self.email = email
		self.password = password

		@classmethod
		def get_by_username(cls, username):
			return DBSession.query(cls).filter(cls.username == username).first()

		@classmethod
		def check_password(cls, username, password):
			user = cls.get_by_username(username)
			if not user:
				return False
			return crypt.check(user.password, password)
开发者ID:mpeshev,项目名称:Pyramid-Ticketing,代码行数:25,代码来源:models.py


示例7: test_synonym_comparable

    def test_synonym_comparable(self):
        users = self.tables.users

        class User(object):

           class Comparator(PropComparator):
               pass

           def _getValue(self):
               return self._value

           def _setValue(self, value):
               setattr(self, '_value', value)

           value = property(_getValue, _setValue)

        mapper(User, users, properties={
            'uid':synonym('id'),
            'foobar':comparable_property(User.Comparator,User.value),
        })

        sess = create_session()
        u = User()
        u.name = 'ed'
        sess.add(u)
        sess.flush()
        sess.expunge(u)
        sess.merge(u)
开发者ID:23andMe,项目名称:sqlalchemy,代码行数:28,代码来源:test_merge.py


示例8: test_evaluate_double_synonym_attr

    def test_evaluate_double_synonym_attr(self):
        class Foo(object):
            pass

        mapper(
            Foo,
            self.tables.users,
            properties={"uname": synonym("name"), "ufoo": synonym("uname")},
        )

        s = Session()
        jill = s.query(Foo).get(3)
        s.query(Foo).update(
            {Foo.ufoo: "moonbeam"}, synchronize_session="evaluate"
        )
        eq_(jill.ufoo, "moonbeam")
开发者ID:monetate,项目名称:sqlalchemy,代码行数:16,代码来源:test_update_delete.py


示例9: start

 def start(cls):
     return synonym(
         "_start",
         descriptor=property(
             cls._start_getter,
             cls._start_setter,
         )
     )
开发者ID:noflame,项目名称:stalker,代码行数:8,代码来源:mixins.py


示例10: end

 def end(cls):
     return synonym(
         "_end",
         descriptor=property(
             cls._end_getter,
             cls._end_setter
         )
     )
开发者ID:noflame,项目名称:stalker,代码行数:8,代码来源:mixins.py


示例11: json_synonym

def json_synonym(name):
    """Use json to serialize python objects for db storage."""
    def getter(self):
        return json.loads(getattr(self, name), decode_datetime=True)

    def setter(self, entry):
        setattr(self, name, unicode(json.dumps(entry, encode_datetime=True)))

    return synonym(name, descriptor=property(getter, setter))
开发者ID:Farbdose,项目名称:Flexget,代码行数:9,代码来源:database.py


示例12: status

    def status(cls):
        def get_status(self):
            return self._status

        def set_status(self, value):
            if self._status != value:
                self._status = value
                signal_execution_status_change.send(self)

        return synonym('_status', descriptor=property(get_status, set_status))
开发者ID:mdpearson,项目名称:COSMOS-2.0,代码行数:10,代码来源:Execution.py


示例13: test_synonym_group_bug

    def test_synonym_group_bug(self):
        orders, Order = self.tables.orders, self.classes.Order

        mapper(Order, orders, properties={
            'isopen':synonym('_isopen', map_column=True),
            'description':deferred(orders.c.description, group='foo')
        })

        sess = create_session()
        o1 = sess.query(Order).get(1)
        eq_(o1.description, "order 1")
开发者ID:DeepakAlevoor,项目名称:sqlalchemy,代码行数:11,代码来源:test_deferred.py


示例14: target_entity_type

    def target_entity_type(cls):
        return synonym(
            "_target_entity_type",
            descriptor=property(
                fget=cls._target_entity_type_getter,
                doc="""The entity type which this object is valid for.

                Usually it is set to the TargetClass directly.
                """
            )
        )
开发者ID:noflame,项目名称:stalker,代码行数:11,代码来源:mixins.py


示例15: test_evaluate_synonym_string

    def test_evaluate_synonym_string(self):
        class Foo(object):
            pass

        mapper(Foo, self.tables.users, properties={"uname": synonym("name")})

        s = Session()
        jill = s.query(Foo).get(3)
        s.query(Foo).update(
            {"uname": "moonbeam"}, synchronize_session="evaluate"
        )
        eq_(jill.uname, "moonbeam")
开发者ID:monetate,项目名称:sqlalchemy,代码行数:12,代码来源:test_update_delete.py


示例16: safe_pickle_synonym

def safe_pickle_synonym(name):
    """Used to store Entry instances into a PickleType column in the database.

    In order to ensure everything can be loaded after code changes, makes sure no custom python classes are pickled.
    """

    def only_builtins(item):
        """Casts all subclasses of builtin types to their builtin python type. Works recursively on iterables.

        Raises ValueError if passed an object that doesn't subclass a builtin type.
        """

        supported_types = [str, unicode, int, float, long, bool, datetime]
        # dict, list, tuple and set are also supported, but handled separately

        if type(item) in supported_types:
            return item
        elif isinstance(item, dict):
            result = {}
            for key, value in item.iteritems():
                try:
                    result[key] = only_builtins(value)
                except TypeError:
                    continue
            return result
        elif isinstance(item, (list, tuple, set)):
            result = []
            for value in item:
                try:
                    result.append(only_builtins(value))
                except ValueError:
                    continue
            if isinstance(item, list):
                return result
            elif isinstance(item, tuple):
                return tuple(result)
            else:
                return set(result)
        else:
            for s_type in supported_types:
                if isinstance(item, s_type):
                    return s_type(item)

        # If item isn't a subclass of a builtin python type, raise ValueError.
        raise TypeError('%r is not a subclass of a builtin python type.' % type(item))

    def getter(self):
        return getattr(self, name)

    def setter(self, entry):
        setattr(self, name, only_builtins(entry))

    return synonym(name, descriptor=property(getter, setter))
开发者ID:StunMan,项目名称:Flexget,代码行数:53,代码来源:database.py


示例17: entry_synonym

def entry_synonym(name):
    """Use json to serialize python objects for db storage."""

    def only_builtins(item):
        supported_types = (str, unicode, int, float, long, bool, datetime)
        # dict, list, tuple and set are also supported, but handled separately

        if isinstance(item, supported_types):
            return item
        elif isinstance(item, Mapping):
            result = {}
            for key, value in item.items():
                try:
                    result[key] = only_builtins(value)
                except TypeError:
                    continue
            return result
        elif isinstance(item, (list, tuple, set)):
            result = []
            for value in item:
                try:
                    result.append(only_builtins(value))
                except ValueError:
                    continue
            if isinstance(item, list):
                return result
            elif isinstance(item, tuple):
                return tuple(result)
            else:
                return set(result)
        elif isinstance(item, qualities.Quality):
            return item.name
        else:
            for s_type in supported_types:
                if isinstance(item, s_type):
                    return s_type(item)

        # If item isn't a subclass of a builtin python type, raise ValueError.
        raise TypeError('%r is not of type Entry.' % type(item))

    def getter(self):
        return Entry(json.loads(getattr(self, name), decode_datetime=True))

    def setter(self, entry):
        if isinstance(entry, Entry) or isinstance(entry, dict):
            setattr(
                self, name, unicode(json.dumps(only_builtins(dict(entry)), encode_datetime=True))
            )
        else:
            raise TypeError('%r is not of type Entry or dict.' % type(entry))

    return synonym(name, descriptor=property(getter, setter))
开发者ID:Flexget,项目名称:Flexget,代码行数:52,代码来源:database.py


示例18: text_date_synonym

def text_date_synonym(name):
    """Converts Y-M-D date strings into datetime objects"""

    def getter(self):
        return getattr(self, name)

    def setter(self, value):
        if isinstance(value, basestring):
            setattr(self, name, datetime.strptime(value, '%Y-%m-%d'))
        else:
            setattr(self, name, value)

    return synonym(name, descriptor=property(getter, setter))
开发者ID:achuprin,项目名称:Flexget,代码行数:13,代码来源:database.py


示例19: test_evaluate_synonym_string

    def test_evaluate_synonym_string(self):
        class Foo(object):
            pass
        mapper(Foo, self.tables.users, properties={
            'uname': synonym("name", )
        })

        s = Session()
        jill = s.query(Foo).get(3)
        s.query(Foo).update(
            {'uname': 'moonbeam'},
            synchronize_session='evaluate')
        eq_(jill.uname, 'moonbeam')
开发者ID:CyberCollins,项目名称:sqlalchemy,代码行数:13,代码来源:test_update_delete.py


示例20: duration

    def duration(self):
        return synonym(
            '_duration',
            descriptor=property(
                self._duration_getter,
                self._duration_setter,
                doc="""Duration of the entity.

                It is a datetime.timedelta instance. Showing the difference of
                the :attr:`.start` and the :attr:`.end`. If edited it changes
                the :attr:`.end` attribute value."""
            )
        )
开发者ID:noflame,项目名称:stalker,代码行数:13,代码来源:mixins.py



注:本文中的sqlalchemy.orm.synonym函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python orm.undefer函数代码示例发布时间:2022-05-27
下一篇:
Python orm.subqueryload_all函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap