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 :

Vous êtes un professionnel et vous avez besoin d'une formation ? Programmation Python
Les compléments
Voir le programme détaillé
Module « sqlalchemy »

Classe « TypeDecorator »

Informations générales

Héritage

builtins.object
    Generic
builtins.object
    Visitable
        TypeEngine
builtins.object
    TypeEngineMixin
        ExternalType
builtins.object
    EventTarget
        SchemaEventTarget
            TypeDecorator

Définition

class TypeDecorator(SchemaEventTarget, ExternalType, TypeEngine):

help(TypeDecorator)

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

        cache_ok = True

        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::

        from sqlalchemy import JSON
        from sqlalchemy import TypeDecorator


        class MyJsonType(TypeDecorator):
            impl = 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.

   Similarly, when working with the :class:`.ARRAY` datatype, the
   type coercion for index operations (e.g. ``mycol[5]``) is also
   handled by :meth:`.TypeDecorator.coerce_compared_value`, where
   again a simple override is sufficient unless special rules are needed
   for particular operators::

        from sqlalchemy import ARRAY
        from sqlalchemy import TypeDecorator


        class MyArrayType(TypeDecorator):
            impl = ARRAY

            cache_ok = True

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

Constructeur(s)

Signature du constructeur Description
__init__(self, *args: 'Any', **kwargs: 'Any') 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 0x0000020D9F843260>
hashableTrue
impl_instance<sqlalchemy.util.langhelpers._memoized_property object at 0x0000020D9F654E90>
render_bind_castFalse
render_literal_castFalse
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 python_type.__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: 'str') -> 'Any' Proxy all other undefined accessors to the underlying [extrait de __getattr__.__doc__]
__repr__(self) -> 'str'
bind_expression(self, bindparam: 'BindParameter[_T]') -> 'Optional[ColumnElement[_T]]' Given a bind value (i.e. a :class:`.BindParameter` instance), [extrait de bind_expression.__doc__]
bind_processor(self, dialect: 'Dialect') -> 'Optional[_BindProcessorType[_T]]' Provide a bound value processing function for the [extrait de bind_processor.__doc__]
coerce_compared_value(self, op: 'Optional[OperatorType]', value: 'Any') -> 'Any' Suggest a type for a 'coerced' Python value in an expression. [extrait de coerce_compared_value.__doc__]
column_expression(self, column: 'ColumnElement[_T]') -> 'Optional[ColumnElement[_T]]' Given a SELECT column expression, return a wrapping SQL expression. [extrait de column_expression.__doc__]
Comparator(expr: 'ColumnElement[_CT]') A :class:`.TypeEngine.Comparator` that is specific to [extrait de Comparator.__doc__]
compare_values(self, x: 'Any', y: 'Any') -> 'bool' Given two values, compare them for equality. [extrait de compare_values.__doc__]
copy(self, **kw: 'Any') -> 'Self' Produce a copy of this :class:`.TypeDecorator` instance. [extrait de copy.__doc__]
get_dbapi_type(self, dbapi: 'ModuleType') -> 'Optional[Any]' Return the DBAPI type object represented by this [extrait de get_dbapi_type.__doc__]
literal_processor(self, dialect: 'Dialect') -> 'Optional[_LiteralProcessorType[_T]]' Provide a literal processing function for the given [extrait de literal_processor.__doc__]
load_dialect_impl(self, dialect: 'Dialect') -> 'TypeEngine[Any]' Return a :class:`.TypeEngine` object corresponding to a dialect. [extrait de load_dialect_impl.__doc__]
process_bind_param(self, value: 'Optional[_T]', dialect: 'Dialect') -> 'Any' Receive a bound parameter value to be converted. [extrait de process_bind_param.__doc__]
process_literal_param(self, value: 'Optional[_T]', dialect: 'Dialect') -> 'str' Receive a literal parameter value to be rendered inline within [extrait de process_literal_param.__doc__]
process_result_value(self, value: 'Optional[Any]', dialect: 'Dialect') -> 'Optional[_T]' Receive a result-row column value to be converted. [extrait de process_result_value.__doc__]
result_processor(self, dialect: 'Dialect', coltype: 'Any') -> 'Optional[_ResultProcessorType[_T]]' Provide a result value processing function for the given [extrait de result_processor.__doc__]
type_engine(self, dialect: 'Dialect') -> 'TypeEngine[Any]' Return a dialect-specific :class:`.TypeEngine` instance [extrait de type_engine.__doc__]

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

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

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

__class_getitem__, __init_subclass__

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

__class_getitem__, __init_subclass__

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

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

Vous êtes un professionnel et vous avez besoin d'une formation ? Programmation Python
Les compléments
Voir le programme détaillé