mirror of
https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git
synced 2025-08-14 00:25:46 +02:00
Проверка 09.02.2025
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
# orm/events.py
|
||||
# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
|
||||
# Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
|
||||
# <see AUTHORS file>
|
||||
#
|
||||
# This module is part of SQLAlchemy and is released under
|
||||
@@ -207,10 +207,12 @@ class InstanceEvents(event.Events[ClassManager[Any]]):
|
||||
|
||||
from sqlalchemy import event
|
||||
|
||||
|
||||
def my_load_listener(target, context):
|
||||
print("on load!")
|
||||
|
||||
event.listen(SomeClass, 'load', my_load_listener)
|
||||
|
||||
event.listen(SomeClass, "load", my_load_listener)
|
||||
|
||||
Available targets include:
|
||||
|
||||
@@ -466,8 +468,7 @@ class InstanceEvents(event.Events[ClassManager[Any]]):
|
||||
the existing loading context is maintained for the object after the
|
||||
event is called::
|
||||
|
||||
@event.listens_for(
|
||||
SomeClass, "load", restore_load_context=True)
|
||||
@event.listens_for(SomeClass, "load", restore_load_context=True)
|
||||
def on_load(instance, context):
|
||||
instance.some_unloaded_attribute
|
||||
|
||||
@@ -502,7 +503,7 @@ class InstanceEvents(event.Events[ClassManager[Any]]):
|
||||
|
||||
:meth:`.SessionEvents.loaded_as_persistent`
|
||||
|
||||
"""
|
||||
""" # noqa: E501
|
||||
|
||||
def refresh(
|
||||
self, target: _O, context: QueryContext, attrs: Optional[Iterable[str]]
|
||||
@@ -749,6 +750,7 @@ class MapperEvents(event.Events[mapperlib.Mapper[Any]]):
|
||||
|
||||
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
|
||||
@@ -756,10 +758,10 @@ class MapperEvents(event.Events[mapperlib.Mapper[Any]]):
|
||||
text("select my_special_function(%d)" % target.special_number)
|
||||
).scalar()
|
||||
|
||||
|
||||
# associate the listener function with SomeClass,
|
||||
# to execute during the "before_insert" hook
|
||||
event.listen(
|
||||
SomeClass, 'before_insert', my_before_insert_listener)
|
||||
event.listen(SomeClass, "before_insert", my_before_insert_listener)
|
||||
|
||||
Available targets include:
|
||||
|
||||
@@ -925,9 +927,10 @@ class MapperEvents(event.Events[mapperlib.Mapper[Any]]):
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
@event.listens_for(Base, "instrument_class", propagate=True)
|
||||
def on_new_class(mapper, cls_):
|
||||
" ... "
|
||||
"..."
|
||||
|
||||
:param mapper: the :class:`_orm.Mapper` which is the target
|
||||
of this event.
|
||||
@@ -983,7 +986,7 @@ class MapperEvents(event.Events[mapperlib.Mapper[Any]]):
|
||||
symbol which indicates to the :func:`.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,
|
||||
more mappers are skipped, the "new mappers" flag will remain set,
|
||||
meaning the :func:`.configure_mappers` function will continue to be
|
||||
called when mappers are used, to continue to try to configure all
|
||||
available mappers.
|
||||
@@ -992,7 +995,7 @@ class MapperEvents(event.Events[mapperlib.Mapper[Any]]):
|
||||
:meth:`.MapperEvents.before_configured`,
|
||||
:meth:`.MapperEvents.after_configured`, and
|
||||
:meth:`.MapperEvents.mapper_configured`, the
|
||||
:meth;`.MapperEvents.before_mapper_configured` event provides for a
|
||||
:meth:`.MapperEvents.before_mapper_configured` event provides for a
|
||||
meaningful return value when it is registered with the ``retval=True``
|
||||
parameter.
|
||||
|
||||
@@ -1006,13 +1009,16 @@ class MapperEvents(event.Events[mapperlib.Mapper[Any]]):
|
||||
|
||||
DontConfigureBase = declarative_base()
|
||||
|
||||
|
||||
@event.listens_for(
|
||||
DontConfigureBase,
|
||||
"before_mapper_configured", retval=True, propagate=True)
|
||||
"before_mapper_configured",
|
||||
retval=True,
|
||||
propagate=True,
|
||||
)
|
||||
def dont_configure(mapper, cls):
|
||||
return EXT_SKIP
|
||||
|
||||
|
||||
.. seealso::
|
||||
|
||||
:meth:`.MapperEvents.before_configured`
|
||||
@@ -1094,9 +1100,9 @@ class MapperEvents(event.Events[mapperlib.Mapper[Any]]):
|
||||
|
||||
from sqlalchemy.orm import Mapper
|
||||
|
||||
|
||||
@event.listens_for(Mapper, "before_configured")
|
||||
def go():
|
||||
...
|
||||
def go(): ...
|
||||
|
||||
Contrast this event to :meth:`.MapperEvents.after_configured`,
|
||||
which is invoked after the series of mappers has been configured,
|
||||
@@ -1114,10 +1120,9 @@ class MapperEvents(event.Events[mapperlib.Mapper[Any]]):
|
||||
|
||||
from sqlalchemy.orm import mapper
|
||||
|
||||
@event.listens_for(mapper, "before_configured", once=True)
|
||||
def go():
|
||||
...
|
||||
|
||||
@event.listens_for(mapper, "before_configured", once=True)
|
||||
def go(): ...
|
||||
|
||||
.. seealso::
|
||||
|
||||
@@ -1154,9 +1159,9 @@ class MapperEvents(event.Events[mapperlib.Mapper[Any]]):
|
||||
|
||||
from sqlalchemy.orm import Mapper
|
||||
|
||||
|
||||
@event.listens_for(Mapper, "after_configured")
|
||||
def go():
|
||||
# ...
|
||||
def go(): ...
|
||||
|
||||
Theoretically this event is called once per
|
||||
application, but is actually called any time new mappers
|
||||
@@ -1168,9 +1173,9 @@ class MapperEvents(event.Events[mapperlib.Mapper[Any]]):
|
||||
|
||||
from sqlalchemy.orm import mapper
|
||||
|
||||
|
||||
@event.listens_for(mapper, "after_configured", once=True)
|
||||
def go():
|
||||
# ...
|
||||
def go(): ...
|
||||
|
||||
.. seealso::
|
||||
|
||||
@@ -1557,9 +1562,11 @@ class SessionEvents(event.Events[Session]):
|
||||
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)
|
||||
@@ -1779,7 +1786,7 @@ class SessionEvents(event.Events[Session]):
|
||||
@event.listens_for(session, "after_transaction_create")
|
||||
def after_transaction_create(session, transaction):
|
||||
if transaction.parent is None:
|
||||
# work with top-level transaction
|
||||
... # work with top-level transaction
|
||||
|
||||
To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the
|
||||
:attr:`.SessionTransaction.nested` attribute::
|
||||
@@ -1787,8 +1794,7 @@ class SessionEvents(event.Events[Session]):
|
||||
@event.listens_for(session, "after_transaction_create")
|
||||
def after_transaction_create(session, transaction):
|
||||
if transaction.nested:
|
||||
# work with SAVEPOINT transaction
|
||||
|
||||
... # work with SAVEPOINT transaction
|
||||
|
||||
.. seealso::
|
||||
|
||||
@@ -1820,7 +1826,7 @@ class SessionEvents(event.Events[Session]):
|
||||
@event.listens_for(session, "after_transaction_create")
|
||||
def after_transaction_end(session, transaction):
|
||||
if transaction.parent is None:
|
||||
# work with top-level transaction
|
||||
... # work with top-level transaction
|
||||
|
||||
To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the
|
||||
:attr:`.SessionTransaction.nested` attribute::
|
||||
@@ -1828,8 +1834,7 @@ class SessionEvents(event.Events[Session]):
|
||||
@event.listens_for(session, "after_transaction_create")
|
||||
def after_transaction_end(session, transaction):
|
||||
if transaction.nested:
|
||||
# work with SAVEPOINT transaction
|
||||
|
||||
... # work with SAVEPOINT transaction
|
||||
|
||||
.. seealso::
|
||||
|
||||
@@ -1939,7 +1944,7 @@ class SessionEvents(event.Events[Session]):
|
||||
@event.listens_for(Session, "after_soft_rollback")
|
||||
def do_something(session, previous_transaction):
|
||||
if session.is_active:
|
||||
session.execute("select * from some_table")
|
||||
session.execute(text("select * from some_table"))
|
||||
|
||||
:param session: The target :class:`.Session`.
|
||||
:param previous_transaction: The :class:`.SessionTransaction`
|
||||
@@ -2455,11 +2460,11 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]):
|
||||
|
||||
from sqlalchemy import event
|
||||
|
||||
@event.listens_for(MyClass.collection, 'append', propagate=True)
|
||||
|
||||
@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,
|
||||
@@ -2468,11 +2473,12 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]):
|
||||
def validate_phone(target, value, oldvalue, initiator):
|
||||
"Strip non-numeric characters from a phone number"
|
||||
|
||||
return re.sub(r'\D', '', value)
|
||||
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)
|
||||
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.
|
||||
@@ -2482,7 +2488,7 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]):
|
||||
as when using mapper inheritance patterns::
|
||||
|
||||
|
||||
@event.listens_for(MySuperClass.attr, 'set', propagate=True)
|
||||
@event.listens_for(MySuperClass.attr, "set", propagate=True)
|
||||
def receive_set(target, value, initiator):
|
||||
print("value set: %s" % target)
|
||||
|
||||
@@ -2715,10 +2721,12 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]):
|
||||
|
||||
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
|
||||
@@ -2866,16 +2874,18 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]):
|
||||
|
||||
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)
|
||||
MyClass.some_attribute, "init_scalar", retval=True, propagate=True
|
||||
)
|
||||
def _init_some_attribute(target, dict_, value):
|
||||
dict_['some_attribute'] = SOME_CONSTANT
|
||||
dict_["some_attribute"] = SOME_CONSTANT
|
||||
return SOME_CONSTANT
|
||||
|
||||
Above, we initialize the attribute ``MyClass.some_attribute`` to the
|
||||
@@ -2911,9 +2921,10 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]):
|
||||
|
||||
SOME_CONSTANT = 3.1415926
|
||||
|
||||
|
||||
@event.listens_for(
|
||||
MyClass.some_attribute, "init_scalar",
|
||||
retval=True, propagate=True)
|
||||
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
|
||||
@@ -2950,7 +2961,7 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]):
|
||||
:ref:`examples_instrumentation` - see the
|
||||
``active_column_defaults.py`` example.
|
||||
|
||||
"""
|
||||
""" # noqa: E501
|
||||
|
||||
def init_collection(
|
||||
self,
|
||||
@@ -3088,8 +3099,8 @@ class QueryEvents(event.Events[Query[Any]]):
|
||||
@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']
|
||||
if desc["type"] is User:
|
||||
entity = desc["entity"]
|
||||
query = query.filter(entity.deleted == False)
|
||||
return query
|
||||
|
||||
@@ -3105,12 +3116,11 @@ class QueryEvents(event.Events[Query[Any]]):
|
||||
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)
|
||||
@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']
|
||||
if desc["type"] is User:
|
||||
entity = desc["entity"]
|
||||
query = query.filter(entity.deleted == False)
|
||||
return query
|
||||
|
||||
@@ -3131,7 +3141,7 @@ class QueryEvents(event.Events[Query[Any]]):
|
||||
|
||||
:ref:`baked_with_before_compile`
|
||||
|
||||
"""
|
||||
""" # noqa: E501
|
||||
|
||||
def before_compile_update(
|
||||
self, query: Query[Any], update_context: BulkUpdate
|
||||
@@ -3151,11 +3161,13 @@ class QueryEvents(event.Events[Query[Any]]):
|
||||
@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']
|
||||
if desc["type"] is User:
|
||||
entity = desc["entity"]
|
||||
query = query.filter(entity.deleted == False)
|
||||
|
||||
update_context.values['timestamp'] = datetime.utcnow()
|
||||
update_context.values["timestamp"] = datetime.datetime.now(
|
||||
datetime.UTC
|
||||
)
|
||||
return query
|
||||
|
||||
The ``.values`` dictionary of the "update context" object can also
|
||||
@@ -3183,7 +3195,7 @@ class QueryEvents(event.Events[Query[Any]]):
|
||||
:meth:`.QueryEvents.before_compile_delete`
|
||||
|
||||
|
||||
"""
|
||||
""" # noqa: E501
|
||||
|
||||
def before_compile_delete(
|
||||
self, query: Query[Any], delete_context: BulkDelete
|
||||
@@ -3202,8 +3214,8 @@ class QueryEvents(event.Events[Query[Any]]):
|
||||
@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']
|
||||
if desc["type"] is User:
|
||||
entity = desc["entity"]
|
||||
query = query.filter(entity.deleted == False)
|
||||
return query
|
||||
|
||||
|
Reference in New Issue
Block a user