Events

SQLAlchemyには、SQLAlchemy CoreとORMの内部にさまざまなフックを公開するイベントAPIが含まれています。

Event Registration

イベントへのサブスクライブは、単一のAPIポイント、 listen() 関数、または listen_for() デコレータを通して行われます。これらの関数は、target、インターセプトされるイベントを識別する文字列識別子、およびユーザ定義のlisten関数を受け取ります。これら2つの関数への追加の位置引数とキーワード引数は、特定のタイプのイベントによってサポートされる場合があります。これらのイベントは、指定されたイベント関数の代替インタフェースを指定したり、指定されたターゲットに基づいて2番目のイベントターゲットに関する命令を提供したりします。

イベントの名前と対応するリスナー関数の引数シグネチャは、ドキュメントに記述されているマーカークラスにバインドされて存在するクラスバインド指定メソッドから派生します。たとえば、 PoolEvents.connect `のドキュメントは、イベント名が ``connect`() であり、ユーザー定義のリスナー関数が2つの位置引数を受け取る必要があることを示しています:

from sqlalchemy.event import listen
from sqlalchemy.pool import Pool

def my_on_connect(dbapi_con, connection_record):
    print("New DBAPI connection:", dbapi_con)

listen(Pool, "connect", my_on_connect)

listens_for() デコレータでリッスンするには、次のようにします:

from sqlalchemy.event import listens_for
from sqlalchemy.pool import Pool

@listens_for(Pool, "connect")
def my_on_connect(dbapi_con, connection_record):
    print("New DBAPI connection:", dbapi_con)

Named Argument Styles

listener関数で受け付けられる引数のスタイルにはいくつかの種類があります。 PoolEvents.connect() を例にとると、この関数は dbapi_connection 引数と connection_record 引数を受け取るものとして記述されています。これらの引数を名前で受け取ることもできます。そのためには、 **keyword 引数を受け付けるlistener関数を作成し、 listen `か: func:().listen_for` のどちらかに named=True を渡します:

from sqlalchemy.event import listens_for
from sqlalchemy.pool import Pool

@listens_for(Pool, "connect", named=True)
def my_on_connect(**kw):
    print("New DBAPI connection:", kw["dbapi_connection"])

名前付き引数の受け渡しを使用する場合、関数の引数指定にリストされた名前がディクショナリ内のキーとして使用されます。

名前付きスタイルは、関数のシグネチャに関係なく、すべての引数を名前で渡します。したがって、名前が一致する限り、特定の引数も任意の順序でリストすることができます:

from sqlalchemy.event import listens_for
from sqlalchemy.pool import Pool

@listens_for(Pool, "connect", named=True)
def my_on_connect(dbapi_connection, **kw):
    print("New DBAPI connection:", dbapi_connection)
    print("Connection record:", kw["connection_record"])

上の例では、 **kw があることで、 listen_for() に対して、引数は位置ではなく名前で関数に渡されるべきであることを伝えています。

Targets

listen() 関数はターゲットに関して非常に柔軟です。一般的には、クラス、それらのクラスのインスタンス、および適切なターゲットを派生させることができる関連クラスまたはオブジェクトを受け入れます。例えば、前述の "connect" イベントは Engine クラスとオブジェクト、および Pool クラスとオブジェクトを受け入れます:

from sqlalchemy.event import listen
from sqlalchemy.pool import Pool, QueuePool
from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
import psycopg2

def connect():
    return psycopg2.connect(user="ed", host="127.0.0.1", dbname="test")

my_pool = QueuePool(connect)
my_engine = create_engine("postgresql+psycopg2://ed@localhost/test")

# associate listener with all instances of Pool
listen(Pool, "connect", my_on_connect)

# associate listener with all instances of Pool
# via the Engine class
listen(Engine, "connect", my_on_connect)

# associate listener with my_pool
listen(my_pool, "connect", my_on_connect)

# associate listener with my_engine.pool
listen(my_engine, "connect", my_on_connect)

Modifiers

listen() に修飾子を渡すことができるリスナもあります。これらの修飾子は、リスナに対して別の呼び出しシグネチャを提供することがあります。ORMイベントのように、一部のイベントリスナは、後続の処理を変更する戻り値を持つことができます。デフォルトでは、nolistenerは戻り値を必要としますが、 retval=True を渡すことで、この値をサポートできます:

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)

Events and Multiprocessing

SQLAlchemyのイベント・フックはPythonの関数とオブジェクトを使って実装されているため、イベントはPythonの関数呼び出しを介して伝搬します。Pythonのマルチプロセッシングは、親プロセスが子プロセスをフォークするなど、OSのマルチプロセッシングと同じ考え方に従っているので、同じモデルを使ってSQLAlchemyイベント・システムの振る舞いを記述することができます。

親プロセスに登録されたイベントフックは、フックが登録された後にその親から分岐した新しい子プロセスに存在します。これは、子プロセスは、生成時に親からの既存のすべてのPython構造のコピーで開始されるためです。親プロセスのPython構造に加えられた変更は子プロセスに伝播されないため、フックが登録される前にすでに存在していた子プロセスは、これらの新しいイベントフックを受け取りません。

イベント自体の場合、これらはPython関数呼び出しであり、プロセス間で伝播する機能はありません。SQLAlchemyのイベントシステムは、プロセス間通信を実装していません。Pythonプロセス間通信を使用するイベントフックを実装することは可能ですが、これはユーザが実装する必要があります。

Event Reference

SQLAlchemy CoreとSQLAlchemy ORMには、さまざまなイベントフックが用意されています:

  • コアイベント - これらは Core Events で説明されており、接続プールライフサイクル、SQL文の実行、トランザクションライフサイクル、およびスキーマの作成とティアダウンに固有のイベントフックが含まれています。

  • ORMイベント - これらは ORM Events で説明されており、クラスと属性のインストルメンテーションに固有のイベントフック、オブジェクト初期化フック、属性on-changeフック、セッション状態、フラッシュ、コミットフック、マッパー初期化、オブジェクト/結果生成、インスタンス毎の永続化フックが含まれます。

API Reference

Object Name Description

contains(target, identifier, fn)

Return True if the given target/ident/fn is set up to listen.

listen(target, identifier, fn, *args, **kw)

Register a listener function for the given target.

listens_for(target, identifier, *args, **kw)

Decorate a function as a listener for the given target + identifier.

remove(target, identifier, fn)

Remove an event listener.

function sqlalchemy.event.listen(target: Any, identifier: str, fn: Callable[[...], Any], *args: Any, **kw: Any) None

Register a listener function for the given target.

The listen() function is part of the primary interface for the SQLAlchemy event system, documented at Events.

e.g.:

from sqlalchemy import event
from sqlalchemy.schema import UniqueConstraint

def unique_constraint_name(const, table):
    const.name = "uq_%s_%s" % (
        table.name,
        list(const.columns)[0].name
    )
event.listen(
        UniqueConstraint,
        "after_parent_attach",
        unique_constraint_name)
Parameters:
  • insert (bool) – The default behavior for event handlers is to append the decorated user defined function to an internal list of registered event listeners upon discovery. If a user registers a function with insert=True, SQLAlchemy will insert (prepend) the function to the internal list upon discovery. This feature is not typically used or recommended by the SQLAlchemy maintainers, but is provided to ensure certain user defined functions can run before others, such as when Changing the sql_mode in MySQL.

  • named (bool) – When using named argument passing, the names listed in the function argument specification will be used as keys in the dictionary. See Named Argument Styles.

  • once (bool) – Private/Internal API usage. Deprecated. This parameter would provide that an event function would run only once per given target. It does not however imply automatic de-registration of the listener function; associating an arbitrarily high number of listeners without explicitly removing them will cause memory to grow unbounded even if once=True is specified.

  • propagate (bool) – The propagate kwarg is available when working with ORM instrumentation and mapping events. See MapperEvents and MapperEvents.before_mapper_configured() for examples.

  • retval (bool) –

    This flag applies only to specific event listeners, each of which includes documentation explaining when it should be used. By default, no listener ever requires a return value. However, some listeners do support special behaviors for return values, and include in their documentation that the retval=True flag is necessary for a return value to be processed.

    Event listener suites that make use of listen.retval include ConnectionEvents and AttributeEvents.

Note

The listen() function cannot be called at the same time that the target event is being run. This has implications for thread safety, and also means an event cannot be added from inside the listener function for itself. The list of events to be run are present inside of a mutable collection that can’t be changed during iteration.

Event registration and removal is not intended to be a “high velocity” operation; it is a configurational operation. For systems that need to quickly associate and deassociate with events at high scale, use a mutable structure that is handled from inside of a single listener.

function sqlalchemy.event.listens_for(target: Any, identifier: str, *args: Any, **kw: Any) Callable[[Callable[[...], Any]], Callable[[...], Any]]

Decorate a function as a listener for the given target + identifier.

The listens_for() decorator is part of the primary interface for the SQLAlchemy event system, documented at Events.

This function generally shares the same kwargs as listen().

e.g.:

from sqlalchemy import event
from sqlalchemy.schema import UniqueConstraint

@event.listens_for(UniqueConstraint, "after_parent_attach")
def unique_constraint_name(const, table):
    const.name = "uq_%s_%s" % (
        table.name,
        list(const.columns)[0].name
    )

A given function can also be invoked for only the first invocation of the event using the once argument:

@event.listens_for(Mapper, "before_configure", once=True)
def on_config():
    do_config()

Warning

The once argument does not imply automatic de-registration of the listener function after it has been invoked a first time; a listener entry will remain associated with the target object. Associating an arbitrarily high number of listeners without explicitly removing them will cause memory to grow unbounded even if once=True is specified.

See also

listen() - general description of event listening

function sqlalchemy.event.remove(target: Any, identifier: str, fn: Callable[[...], Any]) None

Remove an event listener.

The arguments here should match exactly those which were sent to listen(); all the event registration which proceeded as a result of this call will be reverted by calling remove() with the same arguments.

e.g.:

# if a function was registered like this...
@event.listens_for(SomeMappedClass, "before_insert", propagate=True)
def my_listener_function(*arg):
    pass

# ... it's removed like this
event.remove(SomeMappedClass, "before_insert", my_listener_function)

Above, the listener function associated with SomeMappedClass was also propagated to subclasses of SomeMappedClass; the remove() function will revert all of these operations.

Note

The remove() function cannot be called at the same time that the target event is being run. This has implications for thread safety, and also means an event cannot be removed from inside the listener function for itself. The list of events to be run are present inside of a mutable collection that can’t be changed during iteration.

Event registration and removal is not intended to be a “high velocity” operation; it is a configurational operation. For systems that need to quickly associate and deassociate with events at high scale, use a mutable structure that is handled from inside of a single listener.

See also

listen()

function sqlalchemy.event.contains(target: Any, identifier: str, fn: Callable[[...], Any]) bool

Return True if the given target/ident/fn is set up to listen.