SQLAlchemy 1.1文档
核心活动¶
本节介绍SQLAlchemy Core中提供的事件接口。有关事件监听API的介绍,请参阅Events。ORM事件在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_connection,connection_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_connection,connection_record,connection_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_connection,connection_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_connection,connection_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_connection,connection_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_connection,connection_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新增:增加了对连接失效侦听的支持。
也可以看看
reset
( dbapi_connection,connection_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 thePoolEvents.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_connection,connection_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
的可用事件,其中包括Connection
和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()
anddbapi_error()
, the statement is the exact SQL string that was prepared for transmission to the DBAPIcursor
in the connection’sDialect
.before_execute()
和before_cursor_execute()
事件也可以使用retval=True
标志建立,它允许修改语句和参数为被发送到数据库。Thebefore_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 ofEngine
,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()
andbefore_cursor_execute()
events only. 如果为True,则用户定义的事件函数必须具有返回值,该值是用于替换给定语句和参数的参数元组。请参阅这些方法以获取特定返回参数的说明。Changed in version 0.8:
ConnectionEvents
can now be associated with anyConnectable
includingConnection
, in addition to the existing support forEngine
.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()
orexecutemany()
method of the DBAPIcursor
. 在某些情况下可能是None
。 - context¶ –
ExecutionContext
object in use. 可能是None
。 - executemany¶ – boolean, if
True
, this is anexecutemany()
call, ifFalse
, this is anexecute()
call.
- conn ¶ -
-
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 toConnection.execute()
. - multiparams ¶ - 多个参数集,一个字典列表。
- params ¶ - 单个参数集,单个字典。
- result¶ –
ResultProxy
generated by the execution.
- conn ¶ -
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
标志来选择性地建立。在这种情况下,statement
和parameters
参数应作为二元组返回:@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()
orexecutemany()
method of the DBAPIcursor
. 在某些情况下可能是None
。 - context¶ –
ExecutionContext
object in use. 可能是None
。 - executemany¶ – boolean, if
True
, this is anexecutemany()
call, ifFalse
, this is anexecute()
call.
也可以看看:
- conn ¶ -
before_execute
( conn,clauseelement,multiparams,params 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
标志来选择性地建立。在这种情况下,应该将clauseelement
,multiparams
和params
参数作为三元组返回:@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 toConnection.execute()
. - multiparams ¶ - 多个参数集,一个字典列表。
- params ¶ - 单个参数集,单个字典。
也可以看看:
- conn ¶ -
开始 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) ...
参数: - conn ¶ -
Connection
对象 - xid ¶ - 两阶段XID标识符
- conn ¶ -
提交 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) ...
参数: - conn ¶ -
Connection
对象 - xid ¶ - 两阶段XID标识符
- is_prepared¶ – boolean, indicates if
TwoPhaseTransaction.prepare()
was called.
- conn ¶ -
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()
orexecutemany()
method of the DBAPIcursor
. 在某些情况下可能是None
。 - context¶ –
ExecutionContext
object in use. 可能是None
。 - exception¶ – The unwrapped exception emitted directly from the DBAPI. 此处的类特定于正在使用的DBAPI模块。
从版本0.9.7开始弃用: - 由
ConnectionEvents.handle_error()
- conn ¶ -
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 theConnection
object, not the DBAPI connection thatPoolEvents.checkout()
deals with, although this DBAPI connection is available here via theConnection.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 aConnection
is also made when theConnection.execution_options()
method is called.- conn ¶ -
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
的处理程序可能保留在此链中;最后一个nonNone
返回值是继续传递给下一个处理程序的那个。当引发或返回自定义异常时,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 anEngine
fails during the initial call toEngine.connect()
, as well as when aConnection
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
( conn,xid )拦截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) ...
参数: - conn ¶ -
Connection
对象 - xid ¶ - 两阶段XID标识符
- conn ¶ -
-
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) ...
参数: - conn ¶ -
Connection
对象 - name¶ – specified name used for the savepoint.
- 上下文 ¶ -
ExecutionContext
正在使用中。可能是None
。
- conn ¶ -
回滚 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 thereset_on_return
flag is set to its default value of'rollback'
. 要拦截此回滚,请使用PoolEvents.reset()
挂钩。参数: conn ¶ - Connection
对象也可以看看
-
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) ...
参数: - conn¶ –
Connection
object - name¶ – specified name used for the savepoint.
- 上下文 ¶ -
ExecutionContext
正在使用中。可能是None
。
- conn¶ –
-
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) ...
参数: - conn ¶ -
Connection
对象 - xid ¶ - 两阶段XID标识符
- is_prepared¶ – boolean, indicates if
TwoPhaseTransaction.prepare()
was called.
- conn ¶ -
-
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.
- conn ¶ -
set_connection_execution_options
( conn,opts )在调用
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()
事件。参数: - conn¶ – The newly copied
Connection
object - opts¶ – dictionary of options that were passed to the
Connection.execution_options()
method.
版本0.9.0中的新功能
- conn¶ – The newly copied
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) ...
Engine.execution_options()
方法产生存储新选项的Engine
的浅表副本。新的Engine
在这里传递。此方法的一个特殊应用是向给定的Engine
添加一个ConnectionEvents.engine_connect()
事件处理程序,它将执行一些per-Connection
任务特定于这些执行选项。参数: - conn ¶ - 新复制的
Engine
对象 - opts¶ – dictionary of options that were passed to the
Connection.execution_options()
method.
版本0.9.0中的新功能
- conn ¶ - 新复制的
- class
sqlalchemy.events。
DialectEvents
¶ 基础:
sqlalchemy.event.base.Events
事件接口用于执行替换功能。
这些事件允许直接检测和替换与DBAPI交互的关键方言功能。
注意
DialectEvents
hooks should be considered semi-public and experimental. 这些钩子并不是一般用途,只适用于那些需要将DBAPI机制复杂的重新声明注入现有方言的情况。对于通用语句拦截事件,请使用ConnectionEvents
接口。也可以看看
ConnectionEvents.before_cursor_execute()
ConnectionEvents.before_execute()
版本0.9.4中的新功能
do_connect
( dialect,conn_rec,cargs,cparams 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 otherSchemaEventTarget
subclasses, includingMetaData
,Table
,Column
.MetaData
andTable
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 itsTable
, when aForeignKeyConstraint
is associated with aTable
, 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
( target,connection,** 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) ...
参数:
-
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) ...
参数:
-
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) ...
参数: 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
( target,connection,** 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) ...
参数:
before_drop
( target,connection,** 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) ...
参数:
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) ...
参数: 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
特定参数info
,key
和quote
也可以添加到字典中,并将传递给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
。