Participer au site avec un Tip
Rechercher
 

Améliorations / Corrections

Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.

Emplacement :

Description des améliorations :

Module « sqlalchemy »

Classe « TypeDecorator »

Informations générales

Héritage

builtins.object
    Traversible
        TypeEngine
    builtins.object
        SchemaEventTarget
            TypeDecorator

Définition

class TypeDecorator(SchemaEventTarget, TypeEngine):

Description [extrait de TypeDecorator.__doc__]

Allows the creation of types which add additional functionality
    to an existing type.

    This method is preferred to direct subclassing of SQLAlchemy's
    built-in types as it ensures that all required functionality of
    the underlying type is kept in place.

    Typical usage::

      import sqlalchemy.types as types

      class MyType(types.TypeDecorator):
          '''Prefixes Unicode values with "PREFIX:" on the way in and
          strips it off on the way out.
          '''

          impl = types.Unicode

          cache_ok = True

          def process_bind_param(self, value, dialect):
              return "PREFIX:" + value

          def process_result_value(self, value, dialect):
              return value[7:]

          def copy(self, **kw):
              return MyType(self.impl.length)

    The class-level ``impl`` attribute is required, and can reference any
    :class:`.TypeEngine` class.  Alternatively, the :meth:`load_dialect_impl`
    method can be used to provide different type classes based on the dialect
    given; in this case, the ``impl`` variable can reference
    ``TypeEngine`` as a placeholder.

    The :attr:`.TypeDecorator.cache_ok` class-level flag indicates if this
    custom :class:`.TypeDecorator` is safe to be used as part of a cache key.
    This flag defaults to ``None`` which will initially generate a warning
    when the SQL compiler attempts to generate a cache key for a statement
    that uses this type.  If the :class:`.TypeDecorator` is not guaranteed
    to produce the same bind/result behavior and SQL generation
    every time, this flag should be set to ``False``; otherwise if the
    class produces the same behavior each time, it may be set to ``True``.
    See :attr:`.TypeDecorator.cache_ok` for further notes on how this works.

    Types that receive a Python type that isn't similar to the ultimate type
    used may want to define the :meth:`TypeDecorator.coerce_compared_value`
    method. This is used to give the expression system a hint when coercing
    Python objects into bind parameters within expressions. Consider this
    expression::

        mytable.c.somecol + datetime.date(2009, 5, 15)

    Above, if "somecol" is an ``Integer`` variant, it makes sense that
    we're doing date arithmetic, where above is usually interpreted
    by databases as adding a number of days to the given date.
    The expression system does the right thing by not attempting to
    coerce the "date()" value into an integer-oriented bind parameter.

    However, in the case of ``TypeDecorator``, we are usually changing an
    incoming Python type to something new - ``TypeDecorator`` by default will
    "coerce" the non-typed side to be the same type as itself. Such as below,
    we define an "epoch" type that stores a date value as an integer::

        class MyEpochType(types.TypeDecorator):
            impl = types.Integer

            epoch = datetime.date(1970, 1, 1)

            def process_bind_param(self, value, dialect):
                return (value - self.epoch).days

            def process_result_value(self, value, dialect):
                return self.epoch + timedelta(days=value)

    Our expression of ``somecol + date`` with the above type will coerce the
    "date" on the right side to also be treated as ``MyEpochType``.

    This behavior can be overridden via the
    :meth:`~TypeDecorator.coerce_compared_value` method, which returns a type
    that should be used for the value of the expression. Below we set it such
    that an integer value will be treated as an ``Integer``, and any other
    value is assumed to be a date and will be treated as a ``MyEpochType``::

        def coerce_compared_value(self, op, value):
            if isinstance(value, int):
                return Integer()
            else:
                return self

    .. warning::

       Note that the **behavior of coerce_compared_value is not inherited
       by default from that of the base type**.
       If the :class:`.TypeDecorator` is augmenting a
       type that requires special logic for certain types of operators,
       this method **must** be overridden.  A key example is when decorating
       the :class:`_postgresql.JSON` and :class:`_postgresql.JSONB` types;
       the default rules of :meth:`.TypeEngine.coerce_compared_value` should
       be used in order to deal with operators like index operations::

            class MyJsonType(TypeDecorator):
                impl = postgresql.JSON

                cache_ok = True

                def coerce_compared_value(self, op, value):
                    return self.impl.coerce_compared_value(op, value)

       Without the above step, index operations such as ``mycol['foo']``
       will cause the index value ``'foo'`` to be JSON encoded.

    

Constructeur(s)

Signature du constructeur Description
__init__(self, *args, **kwargs) Construct a :class:`.TypeDecorator`. [extrait de __init__.__doc__]

Liste des attributs statiques

Nom de l'attribut Valeur
cache_okNone
coerce_to_is_types(<class 'NoneType'>,)
dispatch<sqlalchemy.event.base.DDLEventsDispatch object at 0x7f40cbc2af40>
hashableTrue
should_evaluate_noneFalse

Attributs statiques hérités de la classe TypeEngine

sort_key_function

Liste des propriétés

Nom de la propriétéDescription
comparator_factory
python_typeReturn the Python type object expected to be returned [extrait de __doc__]
sort_key_function

Liste des opérateurs

Opérateurs hérités de la classe object

__eq__, __ge__, __gt__, __le__, __lt__, __ne__

Liste des méthodes

Toutes les méthodes Méthodes d'instance Méthodes statiques Méthodes dépréciées
Signature de la méthodeDescription
__getattr__(self, key) Proxy all other undefined accessors to the underlying [extrait de __getattr__.__doc__]
__repr__(self)
bind_expression(self, bindparam)
bind_processor(self, dialect) Provide a bound value processing function for the [extrait de bind_processor.__doc__]
coerce_compared_value(self, op, value) Suggest a type for a 'coerced' Python value in an expression. [extrait de coerce_compared_value.__doc__]
column_expression(self, column)
Comparator(expr) A :class:`.TypeEngine.Comparator` that is specific to [extrait de Comparator.__doc__]
compare_values(self, x, y) Given two values, compare them for equality. [extrait de compare_values.__doc__]
copy(self, **kw) Produce a copy of this :class:`.TypeDecorator` instance. [extrait de copy.__doc__]
get_dbapi_type(self, dbapi) Return the DBAPI type object represented by this [extrait de get_dbapi_type.__doc__]
literal_processor(self, dialect) Provide a literal processing function for the given [extrait de literal_processor.__doc__]
load_dialect_impl(self, dialect) Return a :class:`.TypeEngine` object corresponding to a dialect. [extrait de load_dialect_impl.__doc__]
process_bind_param(self, value, dialect) Receive a bound parameter value to be converted. [extrait de process_bind_param.__doc__]
process_literal_param(self, value, dialect) Receive a literal parameter value to be rendered inline within [extrait de process_literal_param.__doc__]
process_result_value(self, value, dialect) Receive a result-row column value to be converted. [extrait de process_result_value.__doc__]
result_processor(self, dialect, coltype) Provide a result value processing function for the given [extrait de result_processor.__doc__]
type_engine(self, dialect) Return a dialect-specific :class:`.TypeEngine` instance [extrait de type_engine.__doc__]

Méthodes héritées de la classe TypeEngine

__init_subclass__, __str__, __subclasshook__, adapt, as_generic, comparator_factory, compare_against_backend, compile, copy_value, dialect_impl, evaluates_none, with_variant

Méthodes héritées de la classe Traversible

__class_getitem__, get_children

Méthodes héritées de la classe object

__delattr__, __dir__, __format__, __getattribute__, __hash__, __reduce__, __reduce_ex__, __setattr__, __sizeof__