當前位置: 首頁>>代碼示例>>Python>>正文


Python collection.converter方法代碼示例

本文整理匯總了Python中sqlalchemy.orm.collections.collection.converter方法的典型用法代碼示例。如果您正苦於以下問題:Python collection.converter方法的具體用法?Python collection.converter怎麽用?Python collection.converter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sqlalchemy.orm.collections.collection的用法示例。


在下文中一共展示了collection.converter方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: converter

# 需要導入模塊: from sqlalchemy.orm.collections import collection [as 別名]
# 或者: from sqlalchemy.orm.collections.collection import converter [as 別名]
def converter(fn):
        """Tag the method as the collection converter.

        This optional method will be called when a collection is being
        replaced entirely, as in::

            myobj.acollection = [newvalue1, newvalue2]

        The converter method will receive the object being assigned and should
        return an iterable of values suitable for use by the ``appender``
        method.  A converter must not assign values or mutate the collection,
        its sole job is to adapt the value the user provides into an iterable
        of values for the ORM's use.

        The default converter implementation will use duck-typing to do the
        conversion.  A dict-like collection will be convert into an iterable
        of dictionary values, and other types will simply be iterated::

            @collection.converter
            def convert(self, other): ...

        If the duck-typing of the object does not match the type of this
        collection, a TypeError is raised.

        Supply an implementation of this method if you want to expand the
        range of possible types that can be assigned in bulk or perform
        validation on the values about to be assigned.

        """
        fn._sa_instrument_role = 'converter'
        return fn 
開發者ID:jpush,項目名稱:jbox,代碼行數:33,代碼來源:collections.py

示例2: _locate_roles_and_methods

# 需要導入模塊: from sqlalchemy.orm.collections import collection [as 別名]
# 或者: from sqlalchemy.orm.collections.collection import converter [as 別名]
def _locate_roles_and_methods(cls):
    """search for _sa_instrument_role-decorated methods in
    method resolution order, assign to roles.

    """

    roles = {}
    methods = {}

    for supercls in cls.__mro__:
        for name, method in vars(supercls).items():
            if not util.callable(method):
                continue

            # note role declarations
            if hasattr(method, '_sa_instrument_role'):
                role = method._sa_instrument_role
                assert role in ('appender', 'remover', 'iterator',
                                'linker', 'converter')
                roles.setdefault(role, name)

            # transfer instrumentation requests from decorated function
            # to the combined queue
            before, after = None, None
            if hasattr(method, '_sa_instrument_before'):
                op, argument = method._sa_instrument_before
                assert op in ('fire_append_event', 'fire_remove_event')
                before = op, argument
            if hasattr(method, '_sa_instrument_after'):
                op = method._sa_instrument_after
                assert op in ('fire_append_event', 'fire_remove_event')
                after = op
            if before:
                methods[name] = before + (after, )
            elif after:
                methods[name] = None, None, after
    return roles, methods 
開發者ID:jpush,項目名稱:jbox,代碼行數:39,代碼來源:collections.py

示例3: converter

# 需要導入模塊: from sqlalchemy.orm.collections import collection [as 別名]
# 或者: from sqlalchemy.orm.collections.collection import converter [as 別名]
def converter(fn):
        """Tag the method as the collection converter.

        This optional method will be called when a collection is being
        replaced entirely, as in::

            myobj.acollection = [newvalue1, newvalue2]

        The converter method will receive the object being assigned and should
        return an iterable of values suitable for use by the ``appender``
        method.  A converter must not assign values or mutate the collection,
        its sole job is to adapt the value the user provides into an iterable
        of values for the ORM's use.

        The default converter implementation will use duck-typing to do the
        conversion.  A dict-like collection will be convert into an iterable
        of dictionary values, and other types will simply be iterated::

            @collection.converter
            def convert(self, other): ...

        If the duck-typing of the object does not match the type of this
        collection, a TypeError is raised.

        Supply an implementation of this method if you want to expand the
        range of possible types that can be assigned in bulk or perform
        validation on the values about to be assigned.

        """
        fn._sa_instrument_role = "converter"
        return fn 
開發者ID:sqlalchemy,項目名稱:sqlalchemy,代碼行數:33,代碼來源:collections.py

示例4: _locate_roles_and_methods

# 需要導入模塊: from sqlalchemy.orm.collections import collection [as 別名]
# 或者: from sqlalchemy.orm.collections.collection import converter [as 別名]
def _locate_roles_and_methods(cls):
    """search for _sa_instrument_role-decorated methods in
    method resolution order, assign to roles.

    """

    roles = {}
    methods = {}

    for supercls in cls.__mro__:
        for name, method in vars(supercls).items():
            if not callable(method):
                continue

            # note role declarations
            if hasattr(method, "_sa_instrument_role"):
                role = method._sa_instrument_role
                assert role in (
                    "appender",
                    "remover",
                    "iterator",
                    "converter",
                )
                roles.setdefault(role, name)

            # transfer instrumentation requests from decorated function
            # to the combined queue
            before, after = None, None
            if hasattr(method, "_sa_instrument_before"):
                op, argument = method._sa_instrument_before
                assert op in ("fire_append_event", "fire_remove_event")
                before = op, argument
            if hasattr(method, "_sa_instrument_after"):
                op = method._sa_instrument_after
                assert op in ("fire_append_event", "fire_remove_event")
                after = op
            if before:
                methods[name] = before + (after,)
            elif after:
                methods[name] = None, None, after
    return roles, methods 
開發者ID:sqlalchemy,項目名稱:sqlalchemy,代碼行數:43,代碼來源:collections.py

示例5: test_dict_subclass4

# 需要導入模塊: from sqlalchemy.orm.collections import collection [as 別名]
# 或者: from sqlalchemy.orm.collections.collection import converter [as 別名]
def test_dict_subclass4(self):
        # tests #2654
        with testing.expect_deprecated(
            r"The collection.converter\(\) handler is deprecated and will "
            "be removed in a future release.  Please refer to the "
            "AttributeEvents"
        ):

            class MyDict(collections.MappedCollection):
                def __init__(self):
                    super(MyDict, self).__init__(lambda value: "k%d" % value)

                @collection.converter
                def _convert(self, dictlike):
                    for key, value in dictlike.items():
                        yield value + 5

        class Foo(object):
            pass

        instrumentation.register_class(Foo)
        attributes.register_attribute(
            Foo, "attr", uselist=True, typecallable=MyDict, useobject=True
        )

        f = Foo()
        f.attr = {"k1": 1, "k2": 2}

        eq_(f.attr, {"k7": 7, "k6": 6}) 
開發者ID:sqlalchemy,項目名稱:sqlalchemy,代碼行數:31,代碼來源:test_deprecations.py

示例6: converter

# 需要導入模塊: from sqlalchemy.orm.collections import collection [as 別名]
# 或者: from sqlalchemy.orm.collections.collection import converter [as 別名]
def converter(fn):
        """Tag the method as the collection converter.

        This optional method will be called when a collection is being
        replaced entirely, as in::

            myobj.acollection = [newvalue1, newvalue2]

        The converter method will receive the object being assigned and should
        return an iterable of values suitable for use by the ``appender``
        method.  A converter must not assign values or mutate the collection,
        it's sole job is to adapt the value the user provides into an iterable
        of values for the ORM's use.

        The default converter implementation will use duck-typing to do the
        conversion.  A dict-like collection will be convert into an iterable
        of dictionary values, and other types will simply be iterated::

            @collection.converter
            def convert(self, other): ...

        If the duck-typing of the object does not match the type of this
        collection, a TypeError is raised.

        Supply an implementation of this method if you want to expand the
        range of possible types that can be assigned in bulk or perform
        validation on the values about to be assigned.

        """
        fn._sa_instrument_role = 'converter'
        return fn 
開發者ID:binhex,項目名稱:moviegrabber,代碼行數:33,代碼來源:collections.py

示例7: adapt_like_to_iterable

# 需要導入模塊: from sqlalchemy.orm.collections import collection [as 別名]
# 或者: from sqlalchemy.orm.collections.collection import converter [as 別名]
def adapt_like_to_iterable(self, obj):
        """Converts collection-compatible objects to an iterable of values.

        Can be passed any type of object, and if the underlying collection
        determines that it can be adapted into a stream of values it can
        use, returns an iterable of values suitable for append()ing.

        This method may raise TypeError or any other suitable exception
        if adaptation fails.

        If a converter implementation is not supplied on the collection,
        a default duck-typing-based implementation is used.

        """
        converter = self._data()._sa_converter
        if converter is not None:
            return converter(obj)

        setting_type = util.duck_type_collection(obj)
        receiving_type = util.duck_type_collection(self._data())

        if obj is None or setting_type != receiving_type:
            given = obj is None and 'None' or obj.__class__.__name__
            if receiving_type is None:
                wanted = self._data().__class__.__name__
            else:
                wanted = receiving_type.__name__

            raise TypeError(
                "Incompatible collection type: %s is not %s-like" % (
                    given, wanted))

        # If the object is an adapted collection, return the (iterable)
        # adapter.
        if getattr(obj, '_sa_adapter', None) is not None:
            return obj._sa_adapter
        elif setting_type == dict:
            if util.py3k:
                return obj.values()
            else:
                return getattr(obj, 'itervalues', obj.values)()
        else:
            return iter(obj) 
開發者ID:jpush,項目名稱:jbox,代碼行數:45,代碼來源:collections.py

示例8: test_name_setup

# 需要導入模塊: from sqlalchemy.orm.collections import collection [as 別名]
# 或者: from sqlalchemy.orm.collections.collection import converter [as 別名]
def test_name_setup(self):
        with testing.expect_deprecated(
            r"The collection.converter\(\) handler is deprecated and will "
            "be removed in a future release.  Please refer to the "
            "AttributeEvents"
        ):

            class Base(object):
                @collection.iterator
                def base_iterate(self, x):
                    return "base_iterate"

                @collection.appender
                def base_append(self, x):
                    return "base_append"

                @collection.converter
                def base_convert(self, x):
                    return "base_convert"

                @collection.remover
                def base_remove(self, x):
                    return "base_remove"

        from sqlalchemy.orm.collections import _instrument_class

        _instrument_class(Base)

        eq_(Base._sa_remover(Base(), 5), "base_remove")
        eq_(Base._sa_appender(Base(), 5), "base_append")
        eq_(Base._sa_iterator(Base(), 5), "base_iterate")
        eq_(Base._sa_converter(Base(), 5), "base_convert")

        with testing.expect_deprecated(
            r"The collection.converter\(\) handler is deprecated and will "
            "be removed in a future release.  Please refer to the "
            "AttributeEvents"
        ):

            class Sub(Base):
                @collection.converter
                def base_convert(self, x):
                    return "sub_convert"

                @collection.remover
                def sub_remove(self, x):
                    return "sub_remove"

        _instrument_class(Sub)

        eq_(Sub._sa_appender(Sub(), 5), "base_append")
        eq_(Sub._sa_remover(Sub(), 5), "sub_remove")
        eq_(Sub._sa_iterator(Sub(), 5), "base_iterate")
        eq_(Sub._sa_converter(Sub(), 5), "sub_convert") 
開發者ID:sqlalchemy,項目名稱:sqlalchemy,代碼行數:56,代碼來源:test_deprecations.py

示例9: adapt_like_to_iterable

# 需要導入模塊: from sqlalchemy.orm.collections import collection [as 別名]
# 或者: from sqlalchemy.orm.collections.collection import converter [as 別名]
def adapt_like_to_iterable(self, obj):
        """Converts collection-compatible objects to an iterable of values.

        Can be passed any type of object, and if the underlying collection
        determines that it can be adapted into a stream of values it can
        use, returns an iterable of values suitable for append()ing.

        This method may raise TypeError or any other suitable exception
        if adaptation fails.

        If a converter implementation is not supplied on the collection,
        a default duck-typing-based implementation is used.

        """
        converter = self._data()._sa_converter
        if converter is not None:
            return converter(obj)

        setting_type = util.duck_type_collection(obj)
        receiving_type = util.duck_type_collection(self._data())

        if obj is None or setting_type != receiving_type:
            given = obj is None and 'None' or obj.__class__.__name__
            if receiving_type is None:
                wanted = self._data().__class__.__name__
            else:
                wanted = receiving_type.__name__

            raise TypeError(
                "Incompatible collection type: %s is not %s-like" % (
                given, wanted))

        # If the object is an adapted collection, return the (iterable)
        # adapter.
        if getattr(obj, '_sa_adapter', None) is not None:
            return obj._sa_adapter
        elif setting_type == dict:
            if util.py3k:
                return obj.values()
            else:
                return getattr(obj, 'itervalues', obj.values)()
        else:
            return iter(obj) 
開發者ID:binhex,項目名稱:moviegrabber,代碼行數:45,代碼來源:collections.py


注:本文中的sqlalchemy.orm.collections.collection.converter方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。