The ORM includes a wide variety of hooks available for subscription.
For an introduction to the most commonly used ORM events, see the section Tracking Object and Session Changes with Events. The event system in general is discussed at Events. Non-ORM events such as those regarding connections and low-level statement execution are described in Core Events.
sqlalchemy.orm.events.
AttributeEvents
¶Bases: sqlalchemy.event.base.Events
Define events for object attributes.
These are typically defined on the class-bound descriptor for the target class.
e.g.:
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 AttributeEvents.retval
flag is passed to
event.listen()
or event.listens_for()
:
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 ValueError
to halt the operation.
The 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 event.listen()
and event.listens_for()
functions are below.
Parameters: |
|
---|
append
(target, value, initiator)¶Receive a collection append event.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass.some_attribute, 'append')
def receive_append(target, value, initiator):
"listen for the 'append' event"
# ... (event handling logic) ...
The append event is invoked for each element as it is appended to the collection. This occurs for single-item appends as well as for a “bulk replace” operation.
Parameters: |
|
---|---|
Returns: | if the event was registered with |
See also
AttributeEvents
- background on listener options such
as propagation to subclasses.
bulk_replace
(target, values, initiator)¶Receive a collection ‘bulk replace’ event.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass.some_attribute, 'bulk_replace')
def receive_bulk_replace(target, values, initiator):
"listen for the 'bulk_replace' event"
# ... (event handling logic) ...
This event is invoked for a sequence of values as they are incoming to a bulk collection set operation, which can be modified in place before the values are treated as ORM objects. This is an “early hook” that runs before the bulk replace routine attempts to reconcile which objects are already present in the collection and which are being removed by the net replace operation.
It is typical that this method be combined with use of the
AttributeEvents.append()
event. When using both of these
events, note that a bulk replace operation will invoke
the AttributeEvents.append()
event for all new items,
even after AttributeEvents.bulk_replace()
has been invoked
for the collection as a whole. In order to determine if an
AttributeEvents.append()
event is part of a bulk replace,
use the symbol OP_BULK_REPLACE
to test the
incoming initiator:
from sqlalchemy.orm.attributes import OP_BULK_REPLACE
@event.listens_for(SomeObject.collection, "bulk_replace")
def process_collection(target, values, initiator):
values[:] = [_make_value(value) for value in values]
@event.listens_for(SomeObject.collection, "append", retval=True)
def process_collection(target, value, initiator):
# make sure bulk_replace didn't already do it
if initiator is None or initiator.op is not OP_BULK_REPLACE:
return _make_value(value)
else:
return value
New in version 1.2.
Parameters: |
|
---|
See also
AttributeEvents
- background on listener options such
as propagation to subclasses.
dispose_collection
(target, collection, collection_adapter)¶Receive a ‘collection dispose’ event.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass.some_attribute, 'dispose_collection')
def receive_dispose_collection(target, collection, collection_adapter):
"listen for the 'dispose_collection' event"
# ... (event handling logic) ...
This event is triggered for a collection-based attribute when a collection is replaced, that is:
u1.addresses.append(a1)
u1.addresses = [a2, a3] # <- old collection is disposed
The old collection received will contain its previous contents.
Changed in version 1.2: The collection passed to
AttributeEvents.dispose_collection()
will now have its
contents before the dispose intact; previously, the collection
would be empty.
New in version 1.0.0: the AttributeEvents.init_collection()
and AttributeEvents.dispose_collection()
events supersede
the collection.linker
hook.
See also
AttributeEvents
- background on listener options such
as propagation to subclasses.
init_collection
(target, collection, collection_adapter)¶Receive a ‘collection init’ event.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass.some_attribute, 'init_collection')
def receive_init_collection(target, collection, collection_adapter):
"listen for the 'init_collection' event"
# ... (event handling logic) ...
This event is triggered for a collection-based attribute, when the initial “empty collection” is first generated for a blank attribute, as well as for when the collection is replaced with a new one, such as via a set event.
E.g., given that User.addresses
is a relationship-based
collection, the event is triggered here:
u1 = User()
u1.addresses.append(a1) # <- new collection
and also during replace operations:
u1.addresses = [a2, a3] # <- new collection
Parameters: |
|
---|
New in version 1.0.0: the AttributeEvents.init_collection()
and AttributeEvents.dispose_collection()
events supersede
the orm.collection.linker
hook.
See also
AttributeEvents
- background on listener options such
as propagation to subclasses.
init_scalar
(target, value, dict_)¶Receive a scalar “init” event.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass.some_attribute, 'init_scalar')
def receive_init_scalar(target, value, dict_):
"listen for the 'init_scalar' event"
# ... (event handling logic) ...
This event is invoked when an uninitialized, unpersisted scalar attribute is accessed, e.g. read:
x = my_object.some_attribute
The ORM’s default behavior when this occurs for an un-initialized
attribute is to return the value None
; note this differs from
Python’s usual behavior of raising AttributeError
. The
event here can be used to customize what value is actually returned,
with the assumption that the event listener would be mirroring
a default generator that is configured on the Core Column
object as well.
Since a default generator on a Column
might also produce
a changing value such as a timestamp, the
AttributeEvents.init_scalar()
event handler can also be used to set the newly returned value, so
that a Core-level default generation function effectively fires off
only once, but at the moment the attribute is accessed on the
non-persisted object. Normally, no change to the object’s state
is made when an uninitialized attribute is accessed (much older
SQLAlchemy versions did in fact change the object’s state).
If a default generator on a column returned a particular constant, a handler might be used as follows:
SOME_CONSTANT = 3.1415926
class MyClass(Base):
# ...
some_attribute = Column(Numeric, default=SOME_CONSTANT)
@event.listens_for(
MyClass.some_attribute, "init_scalar",
retval=True, propagate=True)
def _init_some_attribute(target, dict_, value):
dict_['some_attribute'] = SOME_CONSTANT
return SOME_CONSTANT
Above, we initialize the attribute MyClass.some_attribute
to the
value of SOME_CONSTANT
. The above code includes the following
features:
SOME_CONSTANT
in the given dict_
,
we indicate that this value is to be persisted to the database.
This supersedes the use of SOME_CONSTANT
in the default generator
for the Column
. The active_column_defaults.py
example given at Attribute Instrumentation illustrates using
the same approach for a changing default, e.g. a timestamp
generator. In this particular example, it is not strictly
necessary to do this since SOME_CONSTANT
would be part of the
INSERT statement in either case.retval=True
flag, the value we return
from the function will be returned by the attribute getter.
Without this flag, the event is assumed to be a passive observer
and the return value of our function is ignored.propagate=True
flag is significant if the mapped class
includes inheriting subclasses, which would also make use of this
event listener. Without this flag, an inheriting subclass will
not use our event handler.In the above example, the attribute set event
AttributeEvents.set()
as well as the related validation feature
provided by orm.validates
is not invoked when we apply our
value to the given dict_
. To have these events to invoke in
response to our newly generated value, apply the value to the given
object as a normal attribute set operation:
SOME_CONSTANT = 3.1415926
@event.listens_for(
MyClass.some_attribute, "init_scalar",
retval=True, propagate=True)
def _init_some_attribute(target, dict_, value):
# will also fire off attribute set events
target.some_attribute = SOME_CONSTANT
return SOME_CONSTANT
When multiple listeners are set up, the generation of the value
is “chained” from one listener to the next by passing the value
returned by the previous listener that specifies retval=True
as the value
argument of the next listener.
New in version 1.1.
Parameters: |
|
---|
See also
AttributeEvents
- background on listener options such
as propagation to subclasses.
Attribute Instrumentation - see the
active_column_defaults.py
example.
modified
(target, initiator)¶Receive a ‘modified’ event.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass.some_attribute, 'modified')
def receive_modified(target, initiator):
"listen for the 'modified' event"
# ... (event handling logic) ...
This event is triggered when the attributes.flag_modified()
function is used to trigger a modify event on an attribute without
any specific value being set.
New in version 1.2.
Parameters: |
|
---|
See also
AttributeEvents
- background on listener options such
as propagation to subclasses.
remove
(target, value, initiator)¶Receive a collection remove event.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass.some_attribute, 'remove')
def receive_remove(target, value, initiator):
"listen for the 'remove' event"
# ... (event handling logic) ...
Parameters: |
|
---|---|
Returns: | No return value is defined for this event. |
See also
AttributeEvents
- background on listener options such
as propagation to subclasses.
set
(target, value, oldvalue, initiator)¶Receive a scalar set event.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass.some_attribute, 'set')
def receive_set(target, value, oldvalue, initiator):
"listen for the 'set' event"
# ... (event handling logic) ...
# named argument style (new in 0.9)
@event.listens_for(SomeClass.some_attribute, 'set', named=True)
def receive_set(**kw):
"listen for the 'set' event"
target = kw['target']
value = kw['value']
# ... (event handling logic) ...
Parameters: |
|
---|---|
Returns: | if the event was registered with |
See also
AttributeEvents
- background on listener options such
as propagation to subclasses.
sqlalchemy.orm.events.
MapperEvents
¶Bases: sqlalchemy.event.base.Events
Define events specific to mappings.
e.g.:
from sqlalchemy import event
def my_before_insert_listener(mapper, connection, target):
# execute a stored procedure upon INSERT,
# apply the value to the row to be inserted
target.calculated_value = connection.scalar(
"select my_special_function(%d)"
% target.special_number)
# associate the listener function with SomeClass,
# to execute during the "before_insert" hook
event.listen(
SomeClass, 'before_insert', my_before_insert_listener)
Available targets include:
propagate=True
flag)Mapper
objectsMapper
class itself and the mapper()
function indicate listening for all mappers.Mapper events provide hooks into critical sections of the
mapper, including those related to object instrumentation,
object loading, and object persistence. In particular, the
persistence methods before_insert()
,
and before_update()
are popular
places to augment the state being persisted - however, these
methods operate with several significant restrictions. The
user is encouraged to evaluate the
SessionEvents.before_flush()
and
SessionEvents.after_flush()
methods as more
flexible and user-friendly hooks in which to apply
additional database state during a flush.
When using MapperEvents
, several modifiers are
available to the event.listen()
function.
Parameters: |
|
---|
after_configured
()¶Called after a series of mappers have been configured.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'after_configured')
def receive_after_configured():
"listen for the 'after_configured' event"
# ... (event handling logic) ...
The MapperEvents.after_configured()
event is invoked
each time the orm.configure_mappers()
function is
invoked, after the function has completed its work.
orm.configure_mappers()
is typically invoked
automatically as mappings are first used, as well as each time
new mappers have been made available and new mapper use is
detected.
Contrast this event to the MapperEvents.mapper_configured()
event, which is called on a per-mapper basis while the configuration
operation proceeds; unlike that event, when this event is invoked,
all cross-configurations (e.g. backrefs) will also have been made
available for any mappers that were pending.
Also contrast to MapperEvents.before_configured()
,
which is invoked before the series of mappers has been configured.
This event can only be applied to the Mapper
class
or mapper()
function, and not to individual mappings or
mapped classes. It is only invoked for all mappings as a whole:
from sqlalchemy.orm import mapper
@event.listens_for(mapper, "after_configured")
def go():
# ...
Theoretically this event is called once per
application, but is actually called any time new mappers
have been affected by a orm.configure_mappers()
call. If new mappings are constructed after existing ones have
already been used, this event will likely be called again. To ensure
that a particular event is only called once and no further, the
once=True
argument (new in 0.9.4) can be applied:
from sqlalchemy.orm import mapper
@event.listens_for(mapper, "after_configured", once=True)
def go():
# ...
after_delete
(mapper, connection, target)¶Receive an object instance after a DELETE statement has been emitted corresponding to that instance.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'after_delete')
def receive_after_delete(mapper, connection, target):
"listen for the 'after_delete' event"
# ... (event handling logic) ...
This event is used to emit additional SQL statements on the given connection as well as to perform application specific bookkeeping related to a deletion event.
The event is often called for a batch of objects of the same class after their DELETE statements have been emitted at once in a previous step.
Warning
Mapper-level flush events only allow very limited operations,
on attributes local to the row being operated upon only,
as well as allowing any SQL to be emitted on the given
Connection
. Please read fully the notes
at Mapper-level Events for guidelines on using
these methods; generally, the SessionEvents.before_flush()
method should be preferred for general on-flush changes.
Parameters: |
|
---|---|
Returns: | No return value is supported by this event. |
See also
after_insert
(mapper, connection, target)¶Receive an object instance after an INSERT statement is emitted corresponding to that instance.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'after_insert')
def receive_after_insert(mapper, connection, target):
"listen for the 'after_insert' event"
# ... (event handling logic) ...
This event is used to modify in-Python-only state on the instance after an INSERT occurs, as well as to emit additional SQL statements on the given connection.
The event is often called for a batch of objects of the
same class after their INSERT statements have been
emitted at once in a previous step. In the extremely
rare case that this is not desirable, the
mapper()
can be configured with batch=False
,
which will cause batches of instances to be broken up
into individual (and more poorly performing)
event->persist->event steps.
Warning
Mapper-level flush events only allow very limited operations,
on attributes local to the row being operated upon only,
as well as allowing any SQL to be emitted on the given
Connection
. Please read fully the notes
at Mapper-level Events for guidelines on using
these methods; generally, the SessionEvents.before_flush()
method should be preferred for general on-flush changes.
Parameters: |
|
---|---|
Returns: | No return value is supported by this event. |
See also
after_update
(mapper, connection, target)¶Receive an object instance after an UPDATE statement is emitted corresponding to that instance.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'after_update')
def receive_after_update(mapper, connection, target):
"listen for the 'after_update' event"
# ... (event handling logic) ...
This event is used to modify in-Python-only state on the instance after an UPDATE occurs, as well as to emit additional SQL statements on the given connection.
This method is called for all instances that are
marked as “dirty”, even those which have no net changes
to their column-based attributes, and for which
no UPDATE statement has proceeded. An object is marked
as dirty when any of its column-based attributes have a
“set attribute” operation called or when any of its
collections are modified. If, at update time, no
column-based attributes have any net changes, no UPDATE
statement will be issued. This means that an instance
being sent to after_update()
is
not a guarantee that an UPDATE statement has been
issued.
To detect if the column-based attributes on the object have net
changes, and therefore resulted in an UPDATE statement, use
object_session(instance).is_modified(instance,
include_collections=False)
.
The event is often called for a batch of objects of the
same class after their UPDATE statements have been emitted at
once in a previous step. In the extremely rare case that
this is not desirable, the mapper()
can be
configured with batch=False
, which will cause
batches of instances to be broken up into individual
(and more poorly performing) event->persist->event
steps.
Warning
Mapper-level flush events only allow very limited operations,
on attributes local to the row being operated upon only,
as well as allowing any SQL to be emitted on the given
Connection
. Please read fully the notes
at Mapper-level Events for guidelines on using
these methods; generally, the SessionEvents.before_flush()
method should be preferred for general on-flush changes.
Parameters: |
|
---|---|
Returns: | No return value is supported by this event. |
See also
before_configured
()¶Called before a series of mappers have been configured.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'before_configured')
def receive_before_configured():
"listen for the 'before_configured' event"
# ... (event handling logic) ...
The MapperEvents.before_configured()
event is invoked
each time the orm.configure_mappers()
function is
invoked, before the function has done any of its work.
orm.configure_mappers()
is typically invoked
automatically as mappings are first used, as well as each time
new mappers have been made available and new mapper use is
detected.
This event can only be applied to the Mapper
class
or mapper()
function, and not to individual mappings or
mapped classes. It is only invoked for all mappings as a whole:
from sqlalchemy.orm import mapper
@event.listens_for(mapper, "before_configured")
def go():
# ...
Contrast this event to MapperEvents.after_configured()
,
which is invoked after the series of mappers has been configured,
as well as MapperEvents.before_mapper_configured()
and MapperEvents.mapper_configured()
, which are both invoked
on a per-mapper basis.
Theoretically this event is called once per
application, but is actually called any time new mappers
are to be affected by a orm.configure_mappers()
call. If new mappings are constructed after existing ones have
already been used, this event will likely be called again. To ensure
that a particular event is only called once and no further, the
once=True
argument (new in 0.9.4) can be applied:
from sqlalchemy.orm import mapper
@event.listens_for(mapper, "before_configured", once=True)
def go():
# ...
New in version 0.9.3.
before_delete
(mapper, connection, target)¶Receive an object instance before a DELETE statement is emitted corresponding to that instance.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'before_delete')
def receive_before_delete(mapper, connection, target):
"listen for the 'before_delete' event"
# ... (event handling logic) ...
This event is used to emit additional SQL statements on the given connection as well as to perform application specific bookkeeping related to a deletion event.
The event is often called for a batch of objects of the same class before their DELETE statements are emitted at once in a later step.
Warning
Mapper-level flush events only allow very limited operations,
on attributes local to the row being operated upon only,
as well as allowing any SQL to be emitted on the given
Connection
. Please read fully the notes
at Mapper-level Events for guidelines on using
these methods; generally, the SessionEvents.before_flush()
method should be preferred for general on-flush changes.
Parameters: |
|
---|---|
Returns: | No return value is supported by this event. |
See also
before_insert
(mapper, connection, target)¶Receive an object instance before an INSERT statement is emitted corresponding to that instance.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'before_insert')
def receive_before_insert(mapper, connection, target):
"listen for the 'before_insert' event"
# ... (event handling logic) ...
This event is used to modify local, non-object related attributes on the instance before an INSERT occurs, as well as to emit additional SQL statements on the given connection.
The event is often called for a batch of objects of the
same class before their INSERT statements are emitted at
once in a later step. In the extremely rare case that
this is not desirable, the mapper()
can be
configured with batch=False
, which will cause
batches of instances to be broken up into individual
(and more poorly performing) event->persist->event
steps.
Warning
Mapper-level flush events only allow very limited operations,
on attributes local to the row being operated upon only,
as well as allowing any SQL to be emitted on the given
Connection
. Please read fully the notes
at Mapper-level Events for guidelines on using
these methods; generally, the SessionEvents.before_flush()
method should be preferred for general on-flush changes.
Parameters: |
|
---|---|
Returns: | No return value is supported by this event. |
See also
before_mapper_configured
(mapper, class_)¶Called right before a specific mapper is to be configured.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'before_mapper_configured')
def receive_before_mapper_configured(mapper, class_):
"listen for the 'before_mapper_configured' event"
# ... (event handling logic) ...
This event is intended to allow a specific mapper to be skipped during
the configure step, by returning the orm.interfaces.EXT_SKIP
symbol which indicates to the configure_mappers()
call that this
particular mapper (or hierarchy of mappers, if propagate=True
is
used) should be skipped in the current configuration run. When one or
more mappers are skipped, the he “new mappers” flag will remain set,
meaning the configure_mappers()
function will continue to be
called when mappers are used, to continue to try to configure all
available mappers.
In comparison to the other configure-level events,
MapperEvents.before_configured()
,
MapperEvents.after_configured()
, and
MapperEvents.mapper_configured()
, the
:meth;`.MapperEvents.before_mapper_configured` event provides for a
meaningful return value when it is registered with the retval=True
parameter.
New in version 1.3.
e.g.:
from sqlalchemy.orm import EXT_SKIP
Base = declarative_base()
DontConfigureBase = declarative_base()
@event.listens_for(
DontConfigureBase,
"before_mapper_configured", retval=True, propagate=True)
def dont_configure(mapper, cls):
return EXT_SKIP
before_update
(mapper, connection, target)¶Receive an object instance before an UPDATE statement is emitted corresponding to that instance.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'before_update')
def receive_before_update(mapper, connection, target):
"listen for the 'before_update' event"
# ... (event handling logic) ...
This event is used to modify local, non-object related attributes on the instance before an UPDATE occurs, as well as to emit additional SQL statements on the given connection.
This method is called for all instances that are
marked as “dirty”, even those which have no net changes
to their column-based attributes. An object is marked
as dirty when any of its column-based attributes have a
“set attribute” operation called or when any of its
collections are modified. If, at update time, no
column-based attributes have any net changes, no UPDATE
statement will be issued. This means that an instance
being sent to before_update()
is
not a guarantee that an UPDATE statement will be
issued, although you can affect the outcome here by
modifying attributes so that a net change in value does
exist.
To detect if the column-based attributes on the object have net
changes, and will therefore generate an UPDATE statement, use
object_session(instance).is_modified(instance,
include_collections=False)
.
The event is often called for a batch of objects of the
same class before their UPDATE statements are emitted at
once in a later step. In the extremely rare case that
this is not desirable, the mapper()
can be
configured with batch=False
, which will cause
batches of instances to be broken up into individual
(and more poorly performing) event->persist->event
steps.
Warning
Mapper-level flush events only allow very limited operations,
on attributes local to the row being operated upon only,
as well as allowing any SQL to be emitted on the given
Connection
. Please read fully the notes
at Mapper-level Events for guidelines on using
these methods; generally, the SessionEvents.before_flush()
method should be preferred for general on-flush changes.
Parameters: |
|
---|---|
Returns: | No return value is supported by this event. |
See also
instrument_class
(mapper, class_)¶Receive a class when the mapper is first constructed, before instrumentation is applied to the mapped class.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'instrument_class')
def receive_instrument_class(mapper, class_):
"listen for the 'instrument_class' event"
# ... (event handling logic) ...
This event is the earliest phase of mapper construction. Most attributes of the mapper are not yet initialized.
This listener can either be applied to the Mapper
class overall, or to any un-mapped class which serves as a base
for classes that will be mapped (using the propagate=True
flag):
Base = declarative_base()
@event.listens_for(Base, "instrument_class", propagate=True)
def on_new_class(mapper, cls_):
" ... "
Parameters: |
---|
mapper_configured
(mapper, class_)¶Called when a specific mapper has completed its own configuration
within the scope of the configure_mappers()
call.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'mapper_configured')
def receive_mapper_configured(mapper, class_):
"listen for the 'mapper_configured' event"
# ... (event handling logic) ...
The MapperEvents.mapper_configured()
event is invoked
for each mapper that is encountered when the
orm.configure_mappers()
function proceeds through the current
list of not-yet-configured mappers.
orm.configure_mappers()
is typically invoked
automatically as mappings are first used, as well as each time
new mappers have been made available and new mapper use is
detected.
When the event is called, the mapper should be in its final
state, but not including backrefs that may be invoked from
other mappers; they might still be pending within the
configuration operation. Bidirectional relationships that
are instead configured via the
orm.relationship.back_populates
argument
will be fully available, since this style of relationship does not
rely upon other possibly-not-configured mappers to know that they
exist.
For an event that is guaranteed to have all mappers ready
to go including backrefs that are defined only on other
mappings, use the MapperEvents.after_configured()
event; this event invokes only after all known mappings have been
fully configured.
The MapperEvents.mapper_configured()
event, unlike
MapperEvents.before_configured()
or
MapperEvents.after_configured()
,
is called for each mapper/class individually, and the mapper is
passed to the event itself. It also is called exactly once for
a particular mapper. The event is therefore useful for
configurational steps that benefit from being invoked just once
on a specific mapper basis, which don’t require that “backref”
configurations are necessarily ready yet.
Parameters: |
---|
sqlalchemy.orm.events.
InstanceEvents
¶Bases: sqlalchemy.event.base.Events
Define events specific to object lifecycle.
e.g.:
from sqlalchemy import event
def my_load_listener(target, context):
print "on load!"
event.listen(SomeClass, 'load', my_load_listener)
Available targets include:
propagate=True
flag)Mapper
objectsMapper
class itself and the mapper()
function indicate listening for all mappers.Instance events are closely related to mapper events, but are more specific to the instance and its instrumentation, rather than its system of persistence.
When using InstanceEvents
, several modifiers are
available to the event.listen()
function.
Parameters: |
|
---|
expire
(target, attrs)¶Receive an object instance after its attributes or some subset have been expired.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'expire')
def receive_expire(target, attrs):
"listen for the 'expire' event"
# ... (event handling logic) ...
‘keys’ is a list of attribute names. If None, the entire state was expired.
Parameters: |
|
---|
first_init
(manager, cls)¶Called when the first instance of a particular mapping is called.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'first_init')
def receive_first_init(manager, cls):
"listen for the 'first_init' event"
# ... (event handling logic) ...
This event is called when the __init__
method of a class
is called the first time for that particular class. The event
invokes before __init__
actually proceeds as well as before
the InstanceEvents.init()
event is invoked.
init
(target, args, kwargs)¶Receive an instance when its constructor is called.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'init')
def receive_init(target, args, kwargs):
"listen for the 'init' event"
# ... (event handling logic) ...
This method is only called during a userland construction of
an object, in conjunction with the object’s constructor, e.g.
its __init__
method. It is not called when an object is
loaded from the database; see the InstanceEvents.load()
event in order to intercept a database load.
The event is called before the actual __init__
constructor
of the object is called. The kwargs
dictionary may be
modified in-place in order to affect what is passed to
__init__
.
Parameters: |
|
---|
init_failure
(target, args, kwargs)¶Receive an instance when its constructor has been called, and raised an exception.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'init_failure')
def receive_init_failure(target, args, kwargs):
"listen for the 'init_failure' event"
# ... (event handling logic) ...
This method is only called during a userland construction of
an object, in conjunction with the object’s constructor, e.g.
its __init__
method. It is not called when an object is loaded
from the database.
The event is invoked after an exception raised by the __init__
method is caught. After the event
is invoked, the original exception is re-raised outwards, so that
the construction of the object still raises an exception. The
actual exception and stack trace raised should be present in
sys.exc_info()
.
Parameters: |
|
---|
load
(target, context)¶Receive an object instance after it has been created via
__new__
, and after initial attribute population has
occurred.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'load')
def receive_load(target, context):
"listen for the 'load' event"
# ... (event handling logic) ...
This typically occurs when the instance is created based on incoming result rows, and is only called once for that instance’s lifetime.
Note that during a result-row load, this method is called upon the first row received for this instance. Note that some attributes and collections may or may not be loaded or even initialized, depending on what’s present in the result rows.
The InstanceEvents.load()
event is also available in a
class-method decorator format called orm.reconstructor()
.
Parameters: |
|
---|
pickle
(target, state_dict)¶Receive an object instance when its associated state is being pickled.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'pickle')
def receive_pickle(target, state_dict):
"listen for the 'pickle' event"
# ... (event handling logic) ...
Parameters: |
|
---|
refresh
(target, context, attrs)¶Receive an object instance after one or more attributes have been refreshed from a query.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'refresh')
def receive_refresh(target, context, attrs):
"listen for the 'refresh' event"
# ... (event handling logic) ...
Contrast this to the InstanceEvents.load()
method, which
is invoked when the object is first loaded from a query.
Parameters: |
|
---|
See also
refresh_flush
(target, flush_context, attrs)¶Receive an object instance after one or more attributes have been refreshed within the persistence of the object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'refresh_flush')
def receive_refresh_flush(target, flush_context, attrs):
"listen for the 'refresh_flush' event"
# ... (event handling logic) ...
This event is the same as InstanceEvents.refresh()
except
it is invoked within the unit of work flush process, and the values
here typically come from the process of handling an INSERT or
UPDATE, such as via the RETURNING clause or from Python-side default
values.
New in version 1.0.5.
Parameters: |
|
---|
unpickle
(target, state_dict)¶Receive an object instance after its associated state has been unpickled.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass, 'unpickle')
def receive_unpickle(target, state_dict):
"listen for the 'unpickle' event"
# ... (event handling logic) ...
Parameters: |
|
---|
sqlalchemy.orm.events.
SessionEvents
¶Bases: sqlalchemy.event.base.Events
Define events specific to Session
lifecycle.
e.g.:
from sqlalchemy import event
from sqlalchemy.orm import sessionmaker
def my_before_commit(session):
print "before commit!"
Session = sessionmaker()
event.listen(Session, "before_commit", my_before_commit)
The listen()
function will accept
Session
objects as well as the return result
of sessionmaker()
and scoped_session()
.
Additionally, it accepts the Session
class which
will apply listeners to all Session
instances
globally.
after_attach
(session, instance)¶Execute after an instance is attached to a session.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'after_attach')
def receive_after_attach(session, instance):
"listen for the 'after_attach' event"
# ... (event handling logic) ...
This is called after an add, delete or merge.
Note
As of 0.8, this event fires off after the item
has been fully associated with the session, which is
different than previous releases. For event
handlers that require the object not yet
be part of session state (such as handlers which
may autoflush while the target object is not
yet complete) consider the
new before_attach()
event.
after_begin
(session, transaction, connection)¶Execute after a transaction is begun on a connection
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'after_begin')
def receive_after_begin(session, transaction, connection):
"listen for the 'after_begin' event"
# ... (event handling logic) ...
Parameters: |
|
---|
after_bulk_delete
(delete_context)¶Execute after a bulk delete operation to the session.
Example argument forms:
from sqlalchemy import event
# standard decorator style (arguments as of 0.9)
@event.listens_for(SomeSessionOrFactory, 'after_bulk_delete')
def receive_after_bulk_delete(delete_context):
"listen for the 'after_bulk_delete' event"
# ... (event handling logic) ...
# DEPRECATED calling style (pre-0.9, will be removed in a future release)
@event.listens_for(SomeSessionOrFactory, 'after_bulk_delete')
def receive_after_bulk_delete(session, query, query_context, result):
"listen for the 'after_bulk_delete' event"
# ... (event handling logic) ...
Deprecated since version 0.9: The SessionEvents.after_bulk_delete
event now accepts the
arguments delete_context
.
Support for listener functions which accept the previous
argument signature(s) listed above as “deprecated” will be
removed in a future release.
This is called as a result of the Query.delete()
method.
Parameters: | delete_context¶ – a “delete context” object which contains details about the update, including these attributes:
|
---|
after_bulk_update
(update_context)¶Execute after a bulk update operation to the session.
Example argument forms:
from sqlalchemy import event
# standard decorator style (arguments as of 0.9)
@event.listens_for(SomeSessionOrFactory, 'after_bulk_update')
def receive_after_bulk_update(update_context):
"listen for the 'after_bulk_update' event"
# ... (event handling logic) ...
# DEPRECATED calling style (pre-0.9, will be removed in a future release)
@event.listens_for(SomeSessionOrFactory, 'after_bulk_update')
def receive_after_bulk_update(session, query, query_context, result):
"listen for the 'after_bulk_update' event"
# ... (event handling logic) ...
Deprecated since version 0.9: The SessionEvents.after_bulk_update
event now accepts the
arguments update_context
.
Support for listener functions which accept the previous
argument signature(s) listed above as “deprecated” will be
removed in a future release.
This is called as a result of the Query.update()
method.
Parameters: | update_context¶ – an “update context” object which contains details about the update, including these attributes:
|
---|
after_commit
(session)¶Execute after a commit has occurred.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'after_commit')
def receive_after_commit(session):
"listen for the 'after_commit' event"
# ... (event handling logic) ...
Note
The after_commit()
hook is not per-flush,
that is, the Session
can emit SQL to the database
many times within the scope of a transaction.
For interception of these events, use the
before_flush()
,
after_flush()
, or
after_flush_postexec()
events.
Note
The Session
is not in an active transaction
when the after_commit()
event is invoked,
and therefore can not emit SQL. To emit SQL corresponding to
every transaction, use the before_commit()
event.
Parameters: | session¶ – The target Session . |
---|
after_flush
(session, flush_context)¶Execute after flush has completed, but before commit has been called.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'after_flush')
def receive_after_flush(session, flush_context):
"listen for the 'after_flush' event"
# ... (event handling logic) ...
Note that the session’s state is still in pre-flush, i.e. ‘new’, ‘dirty’, and ‘deleted’ lists still show pre-flush state as well as the history settings on instance attributes.
Warning
This event runs after the Session
has emitted
SQL to modify the database, but before it has altered its
internal state to reflect those changes, including that newly
inserted objects are placed into the identity map. ORM operations
emitted within this event such as loads of related items
may produce new identity map entries that will immediately
be replaced, sometimes causing confusing results. SQLAlchemy will
emit a warning for this condition as of version 1.3.9.
Parameters: |
|
---|
after_flush_postexec
(session, flush_context)¶Execute after flush has completed, and after the post-exec state occurs.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'after_flush_postexec')
def receive_after_flush_postexec(session, flush_context):
"listen for the 'after_flush_postexec' event"
# ... (event handling logic) ...
This will be when the ‘new’, ‘dirty’, and ‘deleted’ lists are in their final state. An actual commit() may or may not have occurred, depending on whether or not the flush started its own transaction or participated in a larger transaction.
Parameters: |
|
---|
after_rollback
(session)¶Execute after a real DBAPI rollback has occurred.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'after_rollback')
def receive_after_rollback(session):
"listen for the 'after_rollback' event"
# ... (event handling logic) ...
Note that this event only fires when the actual rollback against
the database occurs - it does not fire each time the
Session.rollback()
method is called, if the underlying
DBAPI transaction has already been rolled back. In many
cases, the Session
will not be in
an “active” state during this event, as the current
transaction is not valid. To acquire a Session
which is active after the outermost rollback has proceeded,
use the SessionEvents.after_soft_rollback()
event, checking the
Session.is_active
flag.
Parameters: | session¶ – The target Session . |
---|
after_soft_rollback
(session, previous_transaction)¶Execute after any rollback has occurred, including “soft” rollbacks that don’t actually emit at the DBAPI level.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'after_soft_rollback')
def receive_after_soft_rollback(session, previous_transaction):
"listen for the 'after_soft_rollback' event"
# ... (event handling logic) ...
This corresponds to both nested and outer rollbacks, i.e. the innermost rollback that calls the DBAPI’s rollback() method, as well as the enclosing rollback calls that only pop themselves from the transaction stack.
The given Session
can be used to invoke SQL and
Session.query()
operations after an outermost rollback
by first checking the Session.is_active
flag:
@event.listens_for(Session, "after_soft_rollback")
def do_something(session, previous_transaction):
if session.is_active:
session.execute("select * from some_table")
Parameters: |
|
---|
after_transaction_create
(session, transaction)¶Execute when a new SessionTransaction
is created.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'after_transaction_create')
def receive_after_transaction_create(session, transaction):
"listen for the 'after_transaction_create' event"
# ... (event handling logic) ...
This event differs from after_begin()
in that it occurs for each SessionTransaction
overall, as opposed to when transactions are begun
on individual database connections. It is also invoked
for nested transactions and subtransactions, and is always
matched by a corresponding
after_transaction_end()
event
(assuming normal operation of the Session
).
Parameters: |
|
---|
after_transaction_end
(session, transaction)¶Execute when the span of a SessionTransaction
ends.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'after_transaction_end')
def receive_after_transaction_end(session, transaction):
"listen for the 'after_transaction_end' event"
# ... (event handling logic) ...
This event differs from after_commit()
in that it corresponds to all SessionTransaction
objects in use, including those for nested transactions
and subtransactions, and is always matched by a corresponding
after_transaction_create()
event.
Parameters: |
|
---|
before_attach
(session, instance)¶Execute before an instance is attached to a session.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'before_attach')
def receive_before_attach(session, instance):
"listen for the 'before_attach' event"
# ... (event handling logic) ...
This is called before an add, delete or merge causes the object to be part of the session.
before_commit
(session)¶Execute before commit is called.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'before_commit')
def receive_before_commit(session):
"listen for the 'before_commit' event"
# ... (event handling logic) ...
Note
The before_commit()
hook is not per-flush,
that is, the Session
can emit SQL to the database
many times within the scope of a transaction.
For interception of these events, use the
before_flush()
,
after_flush()
, or
after_flush_postexec()
events.
Parameters: | session¶ – The target Session . |
---|
before_flush
(session, flush_context, instances)¶Execute before flush process has started.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'before_flush')
def receive_before_flush(session, flush_context, instances):
"listen for the 'before_flush' event"
# ... (event handling logic) ...
Parameters: |
|
---|
deleted_to_detached
(session, instance)¶Intercept the “deleted to detached” transition for a specific object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'deleted_to_detached')
def receive_deleted_to_detached(session, instance):
"listen for the 'deleted_to_detached' event"
# ... (event handling logic) ...
This event is invoked when a deleted object is evicted
from the session. The typical case when this occurs is when
the transaction for a Session
in which the object
was deleted is committed; the object moves from the deleted
state to the detached state.
It is also invoked for objects that were deleted in a flush
when the Session.expunge_all()
or Session.close()
events are called, as well as if the object is individually
expunged from its deleted state via Session.expunge()
.
New in version 1.1.
See also
deleted_to_persistent
(session, instance)¶Intercept the “deleted to persistent” transition for a specific object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'deleted_to_persistent')
def receive_deleted_to_persistent(session, instance):
"listen for the 'deleted_to_persistent' event"
# ... (event handling logic) ...
This transition occurs only when an object that’s been deleted
successfully in a flush is restored due to a call to
Session.rollback()
. The event is not called under
any other circumstances.
New in version 1.1.
See also
detached_to_persistent
(session, instance)¶Intercept the “detached to persistent” transition for a specific object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'detached_to_persistent')
def receive_detached_to_persistent(session, instance):
"listen for the 'detached_to_persistent' event"
# ... (event handling logic) ...
This event is a specialization of the
SessionEvents.after_attach()
event which is only invoked
for this specific transition. It is invoked typically during the
Session.add()
call, as well as during the
Session.delete()
call if the object was not previously
associated with the
Session
(note that an object marked as “deleted” remains
in the “persistent” state until the flush proceeds).
Note
If the object becomes persistent as part of a call to
Session.delete()
, the object is not yet marked as
deleted when this event is called. To detect deleted objects,
check the deleted
flag sent to the
SessionEvents.persistent_to_detached()
to event after the
flush proceeds, or check the Session.deleted
collection
within the SessionEvents.before_flush()
event if deleted
objects need to be intercepted before the flush.
Parameters: |
---|
New in version 1.1.
See also
loaded_as_persistent
(session, instance)¶Intercept the “loaded as persistent” transition for a specific object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'loaded_as_persistent')
def receive_loaded_as_persistent(session, instance):
"listen for the 'loaded_as_persistent' event"
# ... (event handling logic) ...
This event is invoked within the ORM loading process, and is invoked
very similarly to the InstanceEvents.load()
event. However,
the event here is linkable to a Session
class or instance,
rather than to a mapper or class hierarchy, and integrates
with the other session lifecycle events smoothly. The object
is guaranteed to be present in the session’s identity map when
this event is called.
Parameters: |
---|
New in version 1.1.
See also
pending_to_persistent
(session, instance)¶Intercept the “pending to persistent”” transition for a specific object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'pending_to_persistent')
def receive_pending_to_persistent(session, instance):
"listen for the 'pending_to_persistent' event"
# ... (event handling logic) ...
This event is invoked within the flush process, and is
similar to scanning the Session.new
collection within
the SessionEvents.after_flush()
event. However, in this
case the object has already been moved to the persistent state
when the event is called.
Parameters: |
---|
New in version 1.1.
See also
pending_to_transient
(session, instance)¶Intercept the “pending to transient” transition for a specific object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'pending_to_transient')
def receive_pending_to_transient(session, instance):
"listen for the 'pending_to_transient' event"
# ... (event handling logic) ...
This less common transition occurs when an pending object that has
not been flushed is evicted from the session; this can occur
when the Session.rollback()
method rolls back the transaction,
or when the Session.expunge()
method is used.
Parameters: |
---|
New in version 1.1.
See also
persistent_to_deleted
(session, instance)¶Intercept the “persistent to deleted” transition for a specific object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'persistent_to_deleted')
def receive_persistent_to_deleted(session, instance):
"listen for the 'persistent_to_deleted' event"
# ... (event handling logic) ...
This event is invoked when a persistent object’s identity
is deleted from the database within a flush, however the object
still remains associated with the Session
until the
transaction completes.
If the transaction is rolled back, the object moves again
to the persistent state, and the
SessionEvents.deleted_to_persistent()
event is called.
If the transaction is committed, the object becomes detached,
which will emit the SessionEvents.deleted_to_detached()
event.
Note that while the Session.delete()
method is the primary
public interface to mark an object as deleted, many objects
get deleted due to cascade rules, which are not always determined
until flush time. Therefore, there’s no way to catch
every object that will be deleted until the flush has proceeded.
the SessionEvents.persistent_to_deleted()
event is therefore
invoked at the end of a flush.
New in version 1.1.
See also
persistent_to_detached
(session, instance)¶Intercept the “persistent to detached” transition for a specific object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'persistent_to_detached')
def receive_persistent_to_detached(session, instance):
"listen for the 'persistent_to_detached' event"
# ... (event handling logic) ...
This event is invoked when a persistent object is evicted from the session. There are many conditions that cause this to happen, including:
Session.expunge()
or Session.close()
Session.rollback()
method, when the object
was part of an INSERT statement for that session’s transactionParameters: |
---|
New in version 1.1.
See also
persistent_to_transient
(session, instance)¶Intercept the “persistent to transient” transition for a specific object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'persistent_to_transient')
def receive_persistent_to_transient(session, instance):
"listen for the 'persistent_to_transient' event"
# ... (event handling logic) ...
This less common transition occurs when an pending object that has
has been flushed is evicted from the session; this can occur
when the Session.rollback()
method rolls back the transaction.
Parameters: |
---|
New in version 1.1.
See also
transient_to_pending
(session, instance)¶Intercept the “transient to pending” transition for a specific object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeSessionOrFactory, 'transient_to_pending')
def receive_transient_to_pending(session, instance):
"listen for the 'transient_to_pending' event"
# ... (event handling logic) ...
This event is a specialization of the
SessionEvents.after_attach()
event which is only invoked
for this specific transition. It is invoked typically during the
Session.add()
call.
Parameters: |
---|
New in version 1.1.
See also
sqlalchemy.orm.events.
QueryEvents
¶Bases: sqlalchemy.event.base.Events
Represent events within the construction of a Query
object.
The events here are intended to be used with an as-yet-unreleased
inspection system for Query
. Some very basic operations
are possible now, however the inspection system is intended to allow
complex query manipulations to be automated.
New in version 1.0.0.
before_compile
(query)¶Receive the Query
object before it is composed into a
core Select
object.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeQuery, 'before_compile')
def receive_before_compile(query):
"listen for the 'before_compile' event"
# ... (event handling logic) ...
This event is intended to allow changes to the query given:
@event.listens_for(Query, "before_compile", retval=True)
def no_deleted(query):
for desc in query.column_descriptions:
if desc['type'] is User:
entity = desc['entity']
query = query.filter(entity.deleted == False)
return query
The event should normally be listened with the retval=True
parameter set, so that the modified query may be returned.
The QueryEvents.before_compile()
event by default
will disallow “baked” queries from caching a query, if the event
hook returns a new Query
object. This affects both direct
use of the baked query extension as well as its operation within
lazy loaders and eager loaders for relationships. In order to
re-establish the query being cached, apply the event adding the
bake_ok
flag:
@event.listens_for(
Query, "before_compile", retval=True, bake_ok=True)
def my_event(query):
for desc in query.column_descriptions:
if desc['type'] is User:
entity = desc['entity']
query = query.filter(entity.deleted == False)
return query
When bake_ok
is set to True, the event hook will only be invoked
once, and not called for subsequent invocations of a particular query
that is being cached.
New in version 1.3.11: - added the “bake_ok” flag to the
QueryEvents.before_compile()
event and disallowed caching via
the “baked” extension from occurring for event handlers that
return a new Query
object if this flag is not set.
before_compile_delete
(query, delete_context)¶Allow modifications to the Query
object within
Query.delete()
.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeQuery, 'before_compile_delete')
def receive_before_compile_delete(query, delete_context):
"listen for the 'before_compile_delete' event"
# ... (event handling logic) ...
Like the QueryEvents.before_compile()
event, this event
should be configured with retval=True
, and the modified
Query
object returned, as in
@event.listens_for(Query, "before_compile_delete", retval=True)
def no_deleted(query, delete_context):
for desc in query.column_descriptions:
if desc['type'] is User:
entity = desc['entity']
query = query.filter(entity.deleted == False)
return query
Parameters: |
---|
New in version 1.2.17.
before_compile_update
(query, update_context)¶Allow modifications to the Query
object within
Query.update()
.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeQuery, 'before_compile_update')
def receive_before_compile_update(query, update_context):
"listen for the 'before_compile_update' event"
# ... (event handling logic) ...
Like the QueryEvents.before_compile()
event, if the event
is to be used to alter the Query
object, it should
be configured with retval=True
, and the modified
Query
object returned, as in
@event.listens_for(Query, "before_compile_update", retval=True)
def no_deleted(query, update_context):
for desc in query.column_descriptions:
if desc['type'] is User:
entity = desc['entity']
query = query.filter(entity.deleted == False)
update_context.values['timestamp'] = datetime.utcnow()
return query
The .values
dictionary of the “update context” object can also
be modified in place as illustrated above.
Parameters: |
|
---|
New in version 1.2.17.
Defines SQLAlchemy’s system of class instrumentation.
This module is usually not directly visible to user applications, but defines a large part of the ORM’s interactivity.
instrumentation.py deals with registration of end-user classes for state tracking. It interacts closely with state.py and attributes.py which establish per-instance and per-class-attribute instrumentation, respectively.
The class instrumentation system can be customized on a per-class
or global basis using the sqlalchemy.ext.instrumentation
module, which provides the means to build and specify
alternate instrumentation forms.
sqlalchemy.orm.events.
InstrumentationEvents
¶Bases: sqlalchemy.event.base.Events
Events related to class instrumentation events.
The listeners here support being established against any new style class, that is any object that is a subclass of ‘type’. Events will then be fired off for events against that class. If the “propagate=True” flag is passed to event.listen(), the event will fire off for subclasses of that class as well.
The Python type
builtin is also accepted as a target,
which when used has the effect of events being emitted
for all classes.
Note the “propagate” flag here is defaulted to True
,
unlike the other class level events where it defaults
to False
. This means that new subclasses will also
be the subject of these events, when a listener
is established on a superclass.
attribute_instrument
(cls, key, inst)¶Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeBaseClass, 'attribute_instrument')
def receive_attribute_instrument(cls, key, inst):
"listen for the 'attribute_instrument' event"
# ... (event handling logic) ...
Called when an attribute is instrumented.
class_instrument
(cls)¶Called after the given class is instrumented.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeBaseClass, 'class_instrument')
def receive_class_instrument(cls):
"listen for the 'class_instrument' event"
# ... (event handling logic) ...
To get at the ClassManager
, use
manager_of_class()
.
class_uninstrument
(cls)¶Called before the given class is uninstrumented.
Example argument forms:
from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeBaseClass, 'class_uninstrument')
def receive_class_uninstrument(cls):
"listen for the 'class_uninstrument' event"
# ... (event handling logic) ...
To get at the ClassManager
, use
manager_of_class()
.