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.
Define events for object attributes.
These are typically defined on the class-bound descriptor for the
target class.
For example, to register a listener that will receive the
:meth:`_orm.AttributeEvents.append` event::
from sqlalchemy import event
@event.listens_for(MyClass.collection, "append", propagate=True)
def my_append_listener(target, value, initiator):
print("received append event for target: %s" % target)
Listeners have the option to return a possibly modified version of the
value, when the :paramref:`.AttributeEvents.retval` flag is passed to
:func:`.event.listen` or :func:`.event.listens_for`, such as below,
illustrated using the :meth:`_orm.AttributeEvents.set` event::
def validate_phone(target, value, oldvalue, initiator):
"Strip non-numeric characters from a phone number"
return re.sub(r"\D", "", value)
# setup listener on UserContact.phone attribute, instructing
# it to use the return value
listen(UserContact.phone, "set", validate_phone, retval=True)
A validation function like the above can also raise an exception
such as :exc:`ValueError` to halt the operation.
The :paramref:`.AttributeEvents.propagate` flag is also important when
applying listeners to mapped classes that also have mapped subclasses,
as when using mapper inheritance patterns::
@event.listens_for(MySuperClass.attr, "set", propagate=True)
def receive_set(target, value, initiator):
print("value set: %s" % target)
The full list of modifiers available to the :func:`.event.listen`
and :func:`.event.listens_for` functions are below.
:param active_history=False: When True, indicates that the
"set" event would like to receive the "old" value being
replaced unconditionally, even if this requires firing off
database loads. Note that ``active_history`` can also be
set directly via :func:`.column_property` and
:func:`_orm.relationship`.
:param propagate=False: When True, the listener function will
be established not just for the class attribute given, but
for attributes of the same name on all current subclasses
of that class, as well as all future subclasses of that
class, using an additional listener that listens for
instrumentation events.
:param raw=False: When True, the "target" argument to the
event will be the :class:`.InstanceState` management
object, rather than the mapped instance itself.
:param retval=False: when True, the user-defined event
listening must return the "value" argument from the
function. This gives the listening function the opportunity
to change the value that is ultimately used for a "set"
or "append" event.
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 :