版本:1.1.0b2 |发布日期:2016年7月1日

SQLAlchemy 1.1文档

核心活动

本节介绍SQLAlchemy Core中提供的事件接口。有关事件监听API的介绍,请参阅EventsORM事件在ORM Events中描述。

class sqlalchemy.event.base。 Events

定义特定目标类型的事件监听功能。

连接池事件

class sqlalchemy.events。 PoolEvents

基础:sqlalchemy.event.base.Events

Pool的可用事件。

这里的方法定义了事件的名称以及传递给侦听器函数的成员的名称。

例如。:

from sqlalchemy import event

def my_on_checkout(dbapi_conn, connection_rec, connection_proxy):
    "handle an on checkout event"

event.listen(Pool, 'checkout', my_on_checkout)

除了接受Pool类和Pool实例外,PoolEvents还接受Engine对象和Engine类作为目标,将解析为给定引擎或Pool类的.pool属性:

engine = create_engine("postgresql://scott:tiger@localhost/test")

# will associate with engine.pool
event.listen(engine, 'checkout', my_on_checkout)
checkin dbapi_connectionconnection_record

连接返回到池时调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngineOrPool, 'checkin')
def receive_checkin(dbapi_connection, connection_record):
    "listen for the 'checkin' event"

    # ... (event handling logic) ...

请注意,连接可能已关闭,如果连接已失效,则可能为无。checkin will not be called for detached connections. (他们不回到游泳池。)

参数:
  • dbapi_connection - 一个DBAPI连接。
  • connection_record - 管理DBAPI连接的_ConnectionRecord
结帐 tt> dbapi_connectionconnection_recordconnection_proxy ¶ T6>

从池中检索连接时调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngineOrPool, 'checkout')
def receive_checkout(dbapi_connection, connection_record, connection_proxy):
    "listen for the 'checkout' event"

    # ... (event handling logic) ...
参数:
  • dbapi_connection - 一个DBAPI连接。
  • connection_record - 管理DBAPI连接的_ConnectionRecord
  • connection_proxy – the _ConnectionFairy object which will proxy the public interface of the DBAPI connection for the lifespan of the checkout.

如果引发DisconnectionError,则当前连接将被丢弃并重新获取连接。处理所有结帐侦听器将中止并使用新连接重新启动。

也可以看看

ConnectionEvents.engine_connect() - 创建新的Connection时发生的类似事件。

close dbapi_connectionconnection_record

当DBAPI连接关闭时调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngineOrPool, 'close')
def receive_close(dbapi_connection, connection_record):
    "listen for the 'close' event"

    # ... (event handling logic) ...

事件在收盘前发出。

连接关闭可能失败;通常这是因为连接已经关闭。如果关闭操作失败,连接将被丢弃。

close()事件对应于仍与该池关联的连接。要为分离连接拦截关闭事件,请使用close_detached()

版本1.1中的新功能

close_detached T0> ( T1> dbapi_connection T2> ) T3> ¶ T4>

当分离的DBAPI连接关闭时调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngineOrPool, 'close_detached')
def receive_close_detached(dbapi_connection):
    "listen for the 'close_detached' event"

    # ... (event handling logic) ...

事件在收盘前发出。

连接关闭可能失败;通常这是因为连接已经关闭。如果关闭操作失败,连接将被丢弃。

版本1.1中的新功能

connect tt> dbapi_connectionconnection_record

首先为给定的Pool创建一个特定的DBAPI连接。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngineOrPool, 'connect')
def receive_connect(dbapi_connection, connection_record):
    "listen for the 'connect' event"

    # ... (event handling logic) ...

此事件允许捕获直接使用DBAPI模块级别.connect()方法生成新的DBAPI连接的点。

参数:
  • dbapi_connection - 一个DBAPI连接。
  • connection_record - 管理DBAPI连接的_ConnectionRecord
detach dbapi_connectionconnection_record

当DBAPI连接从池中“分离”时调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngineOrPool, 'detach')
def receive_detach(dbapi_connection, connection_record):
    "listen for the 'detach' event"

    # ... (event handling logic) ...

此事件在分离发生后发出。该连接不再与给定的连接记录相关联。

版本1.1中的新功能

first_connect(dbapi_connection, connection_record)

第一次从特定的Pool中检出DBAPI连接时,只调用一次。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngineOrPool, 'first_connect')
def receive_first_connect(dbapi_connection, connection_record):
    "listen for the 'first_connect' event"

    # ... (event handling logic) ...

PoolEvents.first_connect()的基本原理是根据用于所有连接的设置确定有关特定系列数据库连接的信息。由于特定的Pool是指单个“creator”函数(根据Engine引用所使用的URL和连接选项),因此通常可以进行观察关于单个连接可以安全地假定为对所有后续连接有效,例如数据库版本,服务器和客户端编码设置,排序规则设置以及其他许多连接。

参数:
  • dbapi_connection - 一个DBAPI连接。
  • connection_record - 管理DBAPI连接的_ConnectionRecord
无效 tt> dbapi_connectionconnection_record异常 ¶ T6>

当DBAPI连接“失效”时调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngineOrPool, 'invalidate')
def receive_invalidate(dbapi_connection, connection_record, exception):
    "listen for the 'invalidate' event"

    # ... (event handling logic) ...

每次调用_ConnectionRecord.invalidate()方法时,都会调用此事件,无论是API使用还是通过“自动失效”,都没有soft标志。

事件发生在最终尝试在连接上调用.close()之前发生。

参数:
  • dbapi_connection - 一个DBAPI连接。
  • connection_record - 管理DBAPI连接的_ConnectionRecord
  • exception – the exception object corresponding to the reason for this invalidation, if any. 可能是None

版本0.9.2新增:增加了对连接失效侦听的支持。

也可以看看

More on Invalidation

reset dbapi_connectionconnection_record

在集中连接发生“重置”操作之前调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngineOrPool, 'reset')
def receive_reset(dbapi_connection, connection_record):
    "listen for the 'reset' event"

    # ... (event handling logic) ...

此事件表示何时在将DBAPI连接返回到池之前调用rollback()方法。使用reset_on_return池参数可以控制“reset”的行为,包括禁用。

The PoolEvents.reset() event is usually followed by the PoolEvents.checkin() event is called, except in those cases where the connection is discarded immediately after reset.

参数:
  • dbapi_connection - 一个DBAPI连接。
  • connection_record - 管理DBAPI连接的_ConnectionRecord

0.8版本中的新功能

soft_invalidate tt> dbapi_connectionconnection_record异常 ¶ T6>

当DBAPI连接将被“软失效”时调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngineOrPool, 'soft_invalidate')
def receive_soft_invalidate(dbapi_connection, connection_record, exception):
    "listen for the 'soft_invalidate' event"

    # ... (event handling logic) ...

每次使用soft标志调用_ConnectionRecord.invalidate()方法时都会调用此事件。

软失效指的是跟踪此连接的连接记录在检入当前连接后强制重新连接。它不会在它被调用的地方主动关闭dbapi_connection。

版本1.0.3中的新功能

SQL执行和连接事件

class sqlalchemy.events。 ConnectionEvents

基础:sqlalchemy.event.base.Events

Connectable的可用事件,其中包括ConnectionEngine

这里的方法定义了事件的名称以及传递给侦听器函数的成员的名称。

事件监听器可以与任何Connectable类或实例相关联,例如Engine,例如:

from sqlalchemy import event, create_engine

def before_cursor_execute(conn, cursor, statement, parameters, context,
                                                executemany):
    log.info("Received statement: %s", statement)

engine = create_engine('postgresql://scott:tiger@localhost/test')
event.listen(engine, "before_cursor_execute", before_cursor_execute)

或使用特定的Connection

with engine.begin() as conn:
    @event.listens_for(conn, 'before_cursor_execute')
    def before_cursor_execute(conn, cursor, statement, parameters,
                                    context, executemany):
        log.info("Received statement: %s", statement)

When the methods are called with a statement parameter, such as in after_cursor_execute(), before_cursor_execute() and dbapi_error(), the statement is the exact SQL string that was prepared for transmission to the DBAPI cursor in the connection’s Dialect.

before_execute()before_cursor_execute()事件也可以使用retval=True标志建立,它允许修改语句和参数为被发送到数据库。The before_cursor_execute() event is particularly useful here to add ad-hoc string transformations, such as comments, to all executions:

from sqlalchemy.engine import Engine
from sqlalchemy import event

@event.listens_for(Engine, "before_cursor_execute", retval=True)
def comment_sql_calls(conn, cursor, statement, parameters,
                                    context, executemany):
    statement = statement + " -- some comment"
    return statement, parameters

注意

ConnectionEvents can be established on any combination of Engine, Connection, as well as instances of each of those classes. 所有四个范围内的事件将针对给定的Connection实例触发。但是,出于性能方面的原因,Connection对象在实例化时确定其父Engine是否已建立事件侦听器。事件监听器添加到Engine类或者Engine 实例之后实例化一个依赖的Connection实例通常在Connection实例上不可用not新添加的侦听器将对在Engine类或实例上建立的那些事件侦听器之后创建的Connection实例生效。

参数:retval=False – Applies to the before_execute() and before_cursor_execute() events only. 如果为True,则用户定义的事件函数必须具有返回值,该值是用于替换给定语句和参数的参数元组。请参阅这些方法以获取特定返回参数的说明。

Changed in version 0.8: ConnectionEvents can now be associated with any Connectable including Connection, in addition to the existing support for Engine.

after_cursor_execute conn游标语句参数 t5 >,上下文executemany

在执行后拦截低级游标execute()事件。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'after_cursor_execute')
def receive_after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
    "listen for the 'after_cursor_execute' event"

    # ... (event handling logic) ...

# named argument style (new in 0.9)
@event.listens_for(SomeEngine, 'after_cursor_execute', named=True)
def receive_after_cursor_execute(**kw):
    "listen for the 'after_cursor_execute' event"
    conn = kw['conn']
    cursor = kw['cursor']

    # ... (event handling logic) ...
参数:
  • conn - Connection对象
  • 游标 - DBAPI游标对象。如果语句是SELECT,将会产生挂起的结果,但是这些不应该被使用,因为它们将被ResultProxy需要。
  • statement – string SQL statement, as passed to the DBAPI
  • parameters – Dictionary, tuple, or list of parameters being passed to the execute() or executemany() method of the DBAPI cursor. 在某些情况下可能是None
  • contextExecutionContext object in use. 可能是None
  • executemany – boolean, if True, this is an executemany() call, if False, this is an execute() call.
after_execute(conn, clauseelement, multiparams, params, result)

执行后拦截高级别的execute()事件。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'after_execute')
def receive_after_execute(conn, clauseelement, multiparams, params, result):
    "listen for the 'after_execute' event"

    # ... (event handling logic) ...

# named argument style (new in 0.9)
@event.listens_for(SomeEngine, 'after_execute', named=True)
def receive_after_execute(**kw):
    "listen for the 'after_execute' event"
    conn = kw['conn']
    clauseelement = kw['clauseelement']

    # ... (event handling logic) ...
参数:
  • conn - Connection对象
  • clauseelement – SQL expression construct, Compiled instance, or string statement passed to Connection.execute().
  • multiparams - 多个参数集,一个字典列表。
  • params - 单个参数集,单个字典。
  • resultResultProxy generated by the execution.
before_cursor_execute conn游标语句参数 t5 >,上下文executemany

在执行前拦截低级别游标execute()事件,接收要针对游标调用的字符串SQL语句和DBAPI特定的参数列表。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'before_cursor_execute')
def receive_before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
    "listen for the 'before_cursor_execute' event"

    # ... (event handling logic) ...

# named argument style (new in 0.9)
@event.listens_for(SomeEngine, 'before_cursor_execute', named=True)
def receive_before_cursor_execute(**kw):
    "listen for the 'before_cursor_execute' event"
    conn = kw['conn']
    cursor = kw['cursor']

    # ... (event handling logic) ...

此事件对于日志记录以及对SQL字符串的后期修改都是不错的选择。除了那些特定于目标后端的参数之外,它不太理想。

该事件可以通过retval=True标志来选择性地建立。在这种情况下,statementparameters参数应作为二元组返回:

@event.listens_for(Engine, "before_cursor_execute", retval=True)
def before_cursor_execute(conn, cursor, statement,
                parameters, context, executemany):
    # do something with statement, parameters
    return statement, parameters

请参阅ConnectionEvents中的示例。

参数:
  • conn - Connection对象
  • 游标 - DBAPI游标对象
  • 语句 - 将字符串SQL语句传递给DBAPI
  • parameters – Dictionary, tuple, or list of parameters being passed to the execute() or executemany() method of the DBAPI cursor. 在某些情况下可能是None
  • contextExecutionContext object in use. 可能是None
  • executemany – boolean, if True, this is an executemany() call, if False, this is an execute() call.

也可以看看:

before_execute()

after_cursor_execute()

before_execute connclauseelementmultiparamsparams t5 > ) T6> ¶ T7>

拦截高级别的execute()事件,在渲染到SQL之前接收未编译的SQL构造和其他对象。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'before_execute')
def receive_before_execute(conn, clauseelement, multiparams, params):
    "listen for the 'before_execute' event"

    # ... (event handling logic) ...

# named argument style (new in 0.9)
@event.listens_for(SomeEngine, 'before_execute', named=True)
def receive_before_execute(**kw):
    "listen for the 'before_execute' event"
    conn = kw['conn']
    clauseelement = kw['clauseelement']

    # ... (event handling logic) ...

此事件适用于调试SQL编译问题以及对发送到数据库的参数的早期操作,因为参数列表在这里将采用一致的格式。

该事件可以通过retval=True标志来选择性地建立。在这种情况下,应该将clauseelementmultiparamsparams参数作为三元组返回:

@event.listens_for(Engine, "before_execute", retval=True)
def before_execute(conn, conn, clauseelement, multiparams, params):
    # do something with clauseelement, multiparams, params
    return clauseelement, multiparams, params
参数:
  • conn - Connection对象
  • clauseelement – SQL expression construct, Compiled instance, or string statement passed to Connection.execute().
  • multiparams - 多个参数集,一个字典列表。
  • params - 单个参数集,单个字典。

也可以看看:

before_cursor_execute()

开始 T0> ( T1> 康恩 T2> ) T3> ¶ T4>

拦截begin()事件。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'begin')
def receive_begin(conn):
    "listen for the 'begin' event"

    # ... (event handling logic) ...
参数: conn - Connection对象
begin_twophase connxid

拦截begin_twophase()事件。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'begin_twophase')
def receive_begin_twophase(conn, xid):
    "listen for the 'begin_twophase' event"

    # ... (event handling logic) ...
参数:
提交 T0> ( T1> 康恩 T2> ) T3> ¶ T4>

拦截commit()事件,由Transaction启动。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'commit')
def receive_commit(conn):
    "listen for the 'commit' event"

    # ... (event handling logic) ...

请注意,如果reset_on_return标志设置为'commit'值,则Pool也可以在签入时自动提交DBAPI连接。 。要拦截此提交,请使用PoolEvents.reset()挂钩。

参数: conn - Connection对象
commit_twophase(conn, xid, is_prepared)

拦截commit_twophase()事件。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'commit_twophase')
def receive_commit_twophase(conn, xid, is_prepared):
    "listen for the 'commit_twophase' event"

    # ... (event handling logic) ...
参数:
dbapi_error conn游标语句参数 t5 >,上下文异常

拦截原始DBAPI错误。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'dbapi_error')
def receive_dbapi_error(conn, cursor, statement, parameters, context, exception):
    "listen for the 'dbapi_error' event"

    # ... (event handling logic) ...

# named argument style (new in 0.9)
@event.listens_for(SomeEngine, 'dbapi_error', named=True)
def receive_dbapi_error(**kw):
    "listen for the 'dbapi_error' event"
    conn = kw['conn']
    cursor = kw['cursor']

    # ... (event handling logic) ...

This event is called with the DBAPI exception instance received from the DBAPI itself, before SQLAlchemy wraps the exception with it’s own exception wrappers, and before any other operations are performed on the DBAPI cursor; the existing transaction remains in effect as well as any state on the cursor.

这里的用例是将低级异常处理注入到Engine中,通常用于记录和调试目的。

警告

代码应该修改任何状态或抛出任何异常,因为这会干扰SQLAlchemy的清理和错误处理例程。对于异常修改,请参阅新的ConnectionEvents.handle_error()事件。

在该钩子之后,SQLAlchemy可以尝试对连接/游标执行任意数量的操作,包括关闭游标,在无连接执行的情况下回滚事务,以及在检测到“断开连接”的情况下处置整个连接池。然后将该异常包装在SQLAlchemy DBAPI异常包装器中并重新引发。

参数:
  • conn - Connection对象
  • 游标 - DBAPI游标对象
  • statement – string SQL statement, as passed to the DBAPI
  • parameters – Dictionary, tuple, or list of parameters being passed to the execute() or executemany() method of the DBAPI cursor. 在某些情况下可能是None
  • contextExecutionContext object in use. 可能是None
  • exception – The unwrapped exception emitted directly from the DBAPI. 此处的类特定于正在使用的DBAPI模块。

从版本0.9.7开始弃用: - 由ConnectionEvents.handle_error()

engine_connect T0> ( T1> 康恩 T2>,分支 T3> ) T4> ¶ T5>

拦截创建新的Connection

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'engine_connect')
def receive_engine_connect(conn, branch):
    "listen for the 'engine_connect' event"

    # ... (event handling logic) ...

这个事件通常被称为调用Engine.connect()方法的直接结果。

它不同于PoolEvents.connect()方法,它指向DBAPI级别的数据库的实际连接; DBAPI连接可能会被集中并重用于许多操作。相反,此事件仅涉及围绕此类DBAPI连接生成较高级别的Connection包装。

It also differs from the PoolEvents.checkout() event in that it is specific to the Connection object, not the DBAPI connection that PoolEvents.checkout() deals with, although this DBAPI connection is available here via the Connection.connection attribute. 但是请注意,如果Connection对象失效,那么在单个Connection对象的生命周期内实际上可能存在多个PoolEvents.checkout()重新建立。在生成Connection的“分支”的情况下,也可以为同一个已经检出的DBAPI连接生成多个Connection对象。

参数:
  • conn - Connection对象。
  • branch – if True, this is a “branch” of an existing Connection. 在执行语句的过程中会生成一个分支以调用补充语句,通常为了INSERT语句的目的预先执行一个默认值的SELECT。

版本0.9.0中的新功能

也可以看看

Disconnect Handling - Pessimistic - 说明如何使用ConnectionEvents.engine_connect()透明地确保池连接连接到数据库。

PoolEvents.checkout()单个DBAPI连接的低级池检出事件

ConnectionEvents.set_connection_execution_options() - a copy of a Connection is also made when the Connection.execution_options() method is called.

engine_disposed T0> ( T1> 发动机 T2> ) T3> ¶ T4>

在调用Engine.dispose()方法时拦截。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'engine_disposed')
def receive_engine_disposed(engine):
    "listen for the 'engine_disposed' event"

    # ... (event handling logic) ...

Engine.dispose()方法指示引擎“处置”其连接池(例如,Pool),并用新的替换它。处理旧池会导致现有的检入连接关闭。新池在首次使用之前不会建立任何新连接。

此事件可用于指示与Engine相关的资源也应该清理干净,同时请记住Engine仍可用于新请求,在这种情况下,重新获取连接资源。

版本1.0.5中的新功能

了handle_error T0> ( T1> exception_context T2> ) T3> ¶ T4>

拦截由Connection处理的所有异常。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'handle_error')
def receive_handle_error(exception_context):
    "listen for the 'handle_error' event"

    # ... (event handling logic) ...

这包括DBAPI以及SQLAlchemy的语句调用过程中发出的所有异常,包括编码错误和其他语句验证错误。事件被调用的其他区域包括事务开始和结束,结果行读取,光标创建。

请注意,handle_error()可以随时支持新类型的异常和新的调用方案使用此事件的代码必须期望在次要版本中存在新的调用模式。

To support the wide variety of members that correspond to an exception, as well as to allow extensibility of the event without backwards incompatibility, the sole argument received is an instance of ExceptionContext. 该对象包含表示有关异常详细信息的数据成员。

这个钩子支持的用例包括:

  • 用于记录和调试目的的只读,低级异常处理
  • 异常重写

挂钩被调用,而失败操作的光标(如果有的话)仍然打开并可访问。可以在该游标上调用特殊的清理操作;在此钩子被调用后,SQLAlchemy将尝试关闭这个游标。如果连接处于“自动提交”模式,则该事务在该钩子的范围内也保持打开状态;每个语句事务的回滚也会在钩子被调用后发生。

用户定义的事件处理程序有两个用于将SQLAlchemy构造的异常替换为用户定义的异常的选项。它可以直接引发这个新的异常,在这种情况下,所有进一步的事件侦听器都会被绕过,并在发生适当的清理后引发异常:

@event.listens_for(Engine, "handle_error")
def handle_exception(context):
    if isinstance(context.original_exception,
        psycopg2.OperationalError) and \
        "failed" in str(context.original_exception):
        raise MySpecialException("failed operation")

警告

Because the ConnectionEvents.handle_error() event specifically provides for exceptions to be re-thrown as the ultimate exception raised by the failed statement, stack traces will be misleading if the user-defined event handler itself fails and throws an unexpected exception; the stack trace may not illustrate the actual code line that failed! 建议在此仔细编码,并在发生意外异常时使用日志记录和/或内联调试。

或者,通过使用retval=True修饰符配置处理程序并从函数返回新的异常实例,可以使用“链式”事件处理风格。在这种情况下,事件处理将继续到下一个处理程序。“链接”异常可以使用ExceptionContext.chained_exception

@event.listens_for(Engine, "handle_error", retval=True)
def handle_exception(context):
    if context.chained_exception is not None and \
        "special" in context.chained_exception.message:
        return MySpecialException("failed",
            cause=context.chained_exception)

返回None的处理程序可能保留在此链中;最后一个non None返回值是继续传递给下一个处理程序的那个。

当引发或返回自定义异常时,SQLAlchemy会按原样引发此新异常,但不会由任何SQLAlchemy对象包装。如果该异常不是sqlalchemy.exc.StatementError的子类,则某些功能可能不可用;目前这包括ORM的功能,即在autoflush进程中添加关于“autoflush”的异常提示。

参数:context – an ExceptionContext object. 有关所有可用成员的详情,请参阅此课程。

版本0.9.7新增:添加了ConnectionEvents.handle_error()钩子。

Changed in version 1.0.0: The handle_error() event is now invoked when an Engine fails during the initial call to Engine.connect(), as well as when a Connection object encounters an error during a reconnect operation.

版本1.0.0更改:当方言使用skip_user_error_events执行选项时,handle_error()事件不会被触发。这被用于打算在特定操作中捕获SQLAlchemy特定异常的方言,例如当MySQL方言检测到has_table()方言方法中不存在的表时。在1.0.0之前,实现handle_error()的代码需要确保在这些场景中抛出的异常不加修改地重新引发。

prepare_twophase connxid

拦截prepare_twophase()事件。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'prepare_twophase')
def receive_prepare_twophase(conn, xid):
    "listen for the 'prepare_twophase' event"

    # ... (event handling logic) ...
参数:
release_savepoint(conn, name, context)

拦截release_savepoint()事件。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'release_savepoint')
def receive_release_savepoint(conn, name, context):
    "listen for the 'release_savepoint' event"

    # ... (event handling logic) ...
参数:
回滚 T0> ( T1> 康恩 T2> ) T3> ¶ T4>

拦截回滚()事件,由Transaction启动。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'rollback')
def receive_rollback(conn):
    "listen for the 'rollback' event"

    # ... (event handling logic) ...

Note that the Pool also “auto-rolls back” a DBAPI connection upon checkin, if the reset_on_return flag is set to its default value of 'rollback'. 要拦截此回滚,请使用PoolEvents.reset()挂钩。

参数: conn - Connection对象

也可以看看

PoolEvents.reset()

rollback_savepoint(conn, name, context)

拦截rollback_savepoint()事件。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'rollback_savepoint')
def receive_rollback_savepoint(conn, name, context):
    "listen for the 'rollback_savepoint' event"

    # ... (event handling logic) ...
参数:
rollback_twophase(conn, xid, is_prepared)

拦截rollback_twophase()事件。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'rollback_twophase')
def receive_rollback_twophase(conn, xid, is_prepared):
    "listen for the 'rollback_twophase' event"

    # ... (event handling logic) ...
参数:
savepoint(conn, name)

截取保存点()事件。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'savepoint')
def receive_savepoint(conn, name):
    "listen for the 'savepoint' event"

    # ... (event handling logic) ...
参数:
  • conn - Connection对象
  • name – specified name used for the savepoint.
set_connection_execution_options connopts

在调用Connection.execution_options()方法时拦截。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'set_connection_execution_options')
def receive_set_connection_execution_options(conn, opts):
    "listen for the 'set_connection_execution_options' event"

    # ... (event handling logic) ...

在新的Connection生成后,使用新更新的执行选项集合,但在Dialect对这些新选项执行操作之前调用此方法。

注意,当一个新的Connection产生了继承其父节点Engine的执行选项时,这个方法不会被调用。要拦截此情况,请使用ConnectionEvents.engine_connect()事件。

参数:

版本0.9.0中的新功能

set_engine_execution_options engineopts

在调用Engine.execution_options()方法时拦截。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'set_engine_execution_options')
def receive_set_engine_execution_options(engine, opts):
    "listen for the 'set_engine_execution_options' event"

    # ... (event handling logic) ...

Engine.execution_options()方法产生存储新选项的Engine的浅表副本。新的Engine在这里传递。此方法的一个特殊应用是向给定的Engine添加一个ConnectionEvents.engine_connect()事件处理程序,它将执行一些per- Connection任务特定于这些执行选项。

参数:

版本0.9.0中的新功能

class sqlalchemy.events。 DialectEvents

基础:sqlalchemy.event.base.Events

事件接口用于执行替换功能。

这些事件允许直接检测和替换与DBAPI交互的关键方言功能。

注意

DialectEvents hooks should be considered semi-public and experimental. 这些钩子并不是一般用途,只适用于那些需要将DBAPI机制复杂的重新声明注入现有方言的情况。对于通用语句拦截事件,请使用ConnectionEvents接口。

版本0.9.4中的新功能

do_connect dialectconn_reccargscparams t5 > ) T6> ¶ T7>

在建立连接之前接收连接参数。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'do_connect')
def receive_do_connect(dialect, conn_rec, cargs, cparams):
    "listen for the 'do_connect' event"

    # ... (event handling logic) ...

# named argument style (new in 0.9)
@event.listens_for(SomeEngine, 'do_connect', named=True)
def receive_do_connect(**kw):
    "listen for the 'do_connect' event"
    dialect = kw['dialect']
    conn_rec = kw['conn_rec']

    # ... (event handling logic) ...

返回一个DBAPI连接以阻止进一步调用事件;返回的连接将被使用。

或者,该事件可以操纵货物和/或cparams集合; cargs将始终是一个Python列表,可以在原地进行变异,并且可以编写一个Python字典。返回None以允许控制传递给下一个事件处理程序,并最终允许方言正常连接,给定更新的参数。

版本1.0.3中的新功能

do_execute(cursor, statement, parameters, context)

接收一个游标以调用execute()。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'do_execute')
def receive_do_execute(cursor, statement, parameters, context):
    "listen for the 'do_execute' event"

    # ... (event handling logic) ...

# named argument style (new in 0.9)
@event.listens_for(SomeEngine, 'do_execute', named=True)
def receive_do_execute(**kw):
    "listen for the 'do_execute' event"
    cursor = kw['cursor']
    statement = kw['statement']

    # ... (event handling logic) ...

返回值True以暂停调用的更多事件,并指示游标执行已经发生在事件处理程序中。

do_execute_no_params 游标语句上下文 ¶ T6>

接收一个没有调用参数的游标来执行execute()。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'do_execute_no_params')
def receive_do_execute_no_params(cursor, statement, context):
    "listen for the 'do_execute_no_params' event"

    # ... (event handling logic) ...

返回值True以暂停调用的更多事件,并指示游标执行已经发生在事件处理程序中。

do_executemany(cursor, statement, parameters, context)

接收一个游标来调用executemany()。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeEngine, 'do_executemany')
def receive_do_executemany(cursor, statement, parameters, context):
    "listen for the 'do_executemany' event"

    # ... (event handling logic) ...

# named argument style (new in 0.9)
@event.listens_for(SomeEngine, 'do_executemany', named=True)
def receive_do_executemany(**kw):
    "listen for the 'do_executemany' event"
    cursor = kw['cursor']
    statement = kw['statement']

    # ... (event handling logic) ...

返回值True以暂停调用的更多事件,并指示游标执行已经发生在事件处理程序中。

模式事件

class sqlalchemy.events。 DDLEvents

基础:sqlalchemy.event.base.Events

Define event listeners for schema objects, that is, SchemaItem and other SchemaEventTarget subclasses, including MetaData, Table, Column.

MetaData and Table support events specifically regarding when CREATE and DROP DDL is emitted to the database.

Attachment events are also provided to customize behavior whenever a child schema element is associated with a parent, such as, when a Column is associated with its Table, when a ForeignKeyConstraint is associated with a Table, etc.

使用after_create事件的示例:

from sqlalchemy import event
from sqlalchemy import Table, Column, Metadata, Integer

m = MetaData()
some_table = Table('some_table', m, Column('data', Integer))

def after_create(target, connection, **kw):
    connection.execute("ALTER TABLE %s SET name=foo_%s" %
                            (target.name, target.name))

event.listen(some_table, "after_create", after_create)

DDL事件与DDL子句构造的DDL类和DDLElement层次结构紧密集成,这些构造本身适合作为侦听器可调用元素:

from sqlalchemy import DDL
event.listen(
    some_table,
    "after_create",
    DDL("ALTER TABLE %(table)s SET name=foo_%(table)s")
)

这里的方法定义了事件的名称以及传递给侦听器函数的成员的名称。

也可以看看:

after_create targetconnection** kw T5> ¶ T6>

在发出CREATE语句后调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeSchemaClassOrObject, 'after_create')
def receive_after_create(target, connection, **kw):
    "listen for the 'after_create' event"

    # ... (event handling logic) ...
参数:
  • target – the MetaData or Table object which is the target of the event.
  • connection – the Connection where the CREATE statement or statements have been emitted.
  • ** kw - 与事件相关的附加关键字参数。该字典的内容可能因发行版而异,并且包括为元数据级事件生成的表的列表,checkfirst标志以及内部事件使用的其他元素。
after_drop(target, connection, **kw)

在DROP语句发出后调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeSchemaClassOrObject, 'after_drop')
def receive_after_drop(target, connection, **kw):
    "listen for the 'after_drop' event"

    # ... (event handling logic) ...
参数:
  • target – the MetaData or Table object which is the target of the event.
  • connection – the Connection where the DROP statement or statements have been emitted.
  • ** kw - 与事件相关的附加关键字参数。该字典的内容可能因发行版而异,并且包括为元数据级事件生成的表的列表,checkfirst标志以及内部事件使用的其他元素。
after_parent_attach(target, parent)

SchemaItem与父SchemaItem关联后调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeSchemaClassOrObject, 'after_parent_attach')
def receive_after_parent_attach(target, parent):
    "listen for the 'after_parent_attach' event"

    # ... (event handling logic) ...
参数:
  • 目标 - 目标对象
  • parent – the parent to which the target is being attached.

event.listen()也接受这个事件的修饰符:

参数:propagate=False – When True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when Table.tometadata() is used.
before_create targetconnection** kw T5> ¶ T6>

在发出CREATE语句之前调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeSchemaClassOrObject, 'before_create')
def receive_before_create(target, connection, **kw):
    "listen for the 'before_create' event"

    # ... (event handling logic) ...
参数:
  • target – the MetaData or Table object which is the target of the event.
  • connection – the Connection where the CREATE statement or statements will be emitted.
  • ** kw - 与事件相关的附加关键字参数。该字典的内容可能因发行版而异,并且包括为元数据级事件生成的表的列表,checkfirst标志以及内部事件使用的其他元素。
before_drop targetconnection** kw T5> ¶ T6>

在DROP语句发出之前调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeSchemaClassOrObject, 'before_drop')
def receive_before_drop(target, connection, **kw):
    "listen for the 'before_drop' event"

    # ... (event handling logic) ...
参数:
  • target – the MetaData or Table object which is the target of the event.
  • connection – the Connection where the DROP statement or statements will be emitted.
  • ** kw - 与事件相关的附加关键字参数。该字典的内容可能因发行版而异,并且包括为元数据级事件生成的表的列表,checkfirst标志以及内部事件使用的其他元素。
before_parent_attach targetparent

SchemaItem与父SchemaItem关联之前调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeSchemaClassOrObject, 'before_parent_attach')
def receive_before_parent_attach(target, parent):
    "listen for the 'before_parent_attach' event"

    # ... (event handling logic) ...
参数:
  • 目标 - 目标对象
  • parent – the parent to which the target is being attached.

event.listen()也接受这个事件的修饰符:

参数:propagate=False – When True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when Table.tometadata() is used.
column_reflect(inspector, table, column_info)

当反映Table时检索到的每个“列信息”单元都被调用。

示例参数表单:

from sqlalchemy import event

# standard decorator style
@event.listens_for(SomeSchemaClassOrObject, 'column_reflect')
def receive_column_reflect(inspector, table, column_info):
    "listen for the 'column_reflect' event"

    # ... (event handling logic) ...

由方言返回的列信息的字典被传递,并且可以被修改。字典是在由reflection.Inspector.get_columns()返回的列表的每个元素中返回的。

在对该字典采取任何操作之前调用该事件,并且可以修改内容。Column特定参数infokeyquote也可以添加到字典中,并将传递给Column的构造函数。

请注意,此事件仅在与整个董事会的Table类关联时才有意义,例如:

from sqlalchemy.schema import Table
from sqlalchemy import event

def listen_for_reflect(inspector, table, column_info):
    "receive a column_reflect event"
    # ...

event.listen(
        Table,
        'column_reflect',
        listen_for_reflect)

...或使用listeners参数与特定的Table实例关联:

def listen_for_reflect(inspector, table, column_info):
    "receive a column_reflect event"
    # ...

t = Table(
    'sometable',
    autoload=True,
    listeners=[
        ('column_reflect', listen_for_reflect)
    ])

这是因为由autoload=True启动的反射过程在Table的构造函数的作用域内完成。

class sqlalchemy.events。 SchemaEventTarget

作为DDLEvents事件目标的元素的基类。

这包括SchemaItem以及SchemaType