版本: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)

In addition to accepting the Pool class and Pool instances, PoolEvents also accepts Engine objects and the Engine class as targets, which will be resolved to the .pool attribute of the given engine or the Pool class:

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

# will associate with engine.pool
event.listen(engine, 'checkout', my_on_checkout)
checkin tt> 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 – the _ConnectionRecord managing the DBAPI connection.
checkout(dbapi_connection, connection_record, connection_proxy)

在从池中检索连接时调用。

示例参数表单:

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 – the _ConnectionRecord managing the DBAPI connection.
  • 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() - a similar event which occurs upon creation of a new 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

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

示例参数表单:

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 – the _ConnectionRecord managing the DBAPI connection.
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)

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

示例参数表单:

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) ...

The rationale for PoolEvents.first_connect() is to determine information about a particular series of database connections based on the settings used for all connections. 由于特定的Pool是指单个“创建者”函数(根据Engine引用所使用的URL和连接选项),因此通常可以进行观察关于单个连接可以安全地认为对所有后续连接有效,如数据库版本,服务器和客户端编码设置,排序规则设置等等。

参数:
  • dbapi_connection - 一个DBAPI连接。
  • connection_record – the _ConnectionRecord managing the DBAPI connection.
无效 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 – the _ConnectionRecord managing the DBAPI connection.
  • 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 – the _ConnectionRecord managing the DBAPI connection.

0.8版本中的新功能

soft_invalidate(dbapi_connection, connection_record, exception)

当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

Available events for Connectable, which includes Connection and Engine.

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

事件监听器可以与任何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.

也可以使用retval=True标志建立before_execute()before_cursor_execute()事件,从而允许修改语句和参数被发送到数据库。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实例上不可用新添加的侦听器将对在父类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 > context,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 – Multiple parameter sets, a list of dictionaries.
  • params – Single parameter set, a single dictionary.
  • resultResultProxy generated by the execution.
before_cursor_execute conn游标语句参数 t5 > context,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 – Multiple parameter sets, a list of dictionaries.
  • params – Single parameter set, a single dictionary.

也可以看看:

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(conn, xid)

截取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 tt> connxidis_prepared ¶ T6>

拦截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, cursor, statement, parameters, context, exception)

拦截原始的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 conn分支

拦截创建新的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. But note there can in fact be multiple PoolEvents.checkout() events within the lifespan of a single Connection object, if that Connection is invalidated and re-established. 在生成Connection的“分支”的情况下,也可以为同一个已经检出的DBAPI连接生成多个Connection对象。

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

版本0.9.0中新增。

也可以看看

Disconnect Handling - Pessimistic - illustrates how to use ConnectionEvents.engine_connect() to transparently ensure pooled connections are connected to the database.

PoolEvents.checkout() the lower-level pool checkout event for an individual DBAPI connection

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的语句调用过程中发出的所有异常,包括编码错误和其他语句验证错误。事件被调用的其他领域包括事务开始和结束,结果行取回,光标创建。

Note that handle_error() may support new kinds of exceptions and new calling scenarios at any time. 使用此事件的代码必须期望在次要版本中存在新的调用模式。

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”的细节提示。

参数: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 tt> 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

Intercept when the Connection.execution_options() method is called.

示例参数表单:

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之前已经对这些新的选项起作用。

Note that this method is not called when a new Connection is produced which is inheriting execution options from its parent Engine; to intercept this condition, use the ConnectionEvents.engine_connect() event.

参数:

版本0.9.0中新增。

set_engine_execution_options(engine, opts)

在调用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) ...

The Engine.execution_options() method produces a shallow copy of the Engine which stores the new options. 新的Engine在这里传递。这个方法的一个特殊的应用是给给定的Engine添加一个ConnectionEvents.engine_connect()事件处理程序,它将执行一些per- Connection任务具体到这些执行选项。

参数:

版本0.9.0中新增。

也可以看看

ConnectionEvents.set_connection_execution_options() - event which is called when Connection.execution_options() is called.

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(cursor, statement, context)

接收一个游标来调用没有参数的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.

当一个Column与它的Table关联时,还提供附件事件来定制行为,例如当一个ForeignKeyConstraintTable等相关联

使用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(target, connection, **kw)

在发出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() also accepts a modifier for this event:

参数: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(target, connection, **kw)

在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(target, parent)

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() also accepts a modifier for this event:

参数: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