Python Sqlalchemy-异常时回滚
我需要在Python Sqlalchemy-异常时回滚,python,sqlalchemy,Python,Sqlalchemy,我需要在core.event'handle\u error'(catch'KeyboardInterrupt')中回滚事务,但此事件中的参数是ExceptionContext,如何执行此操作?在使用sqlalchemy时,我通常有这种模式: session = get_the_session_one_way_or_another() try: # do something with the session except: # * see commen
core.event'handle\u error'(catch'KeyboardInterrupt')
中回滚事务,但此事件中的参数是ExceptionContext
,如何执行此操作?在使用sqlalchemy时,我通常有这种模式:
session = get_the_session_one_way_or_another()
try:
# do something with the session
except: # * see comment below
session.rollback()
raise
else:
session.commit()
为了使事情更易于使用,将其用作上下文管理器非常有用:
@contextmanager
def get_session():
session = get_the_session_one_way_or_another()
try:
yield session
except:
session.rollback()
raise
else:
session.commit()
然后:
with get_session() as session:
# do something with the session
如果在块内引发异常,则上下文管理器将回滚事务
*除了:之外,还有一个空的
,它可以捕获所有内容。这通常不是您想要的,但是这里总是会重新引发异常,所以这很好。感谢您的响应,但我需要在handler\u error core.event中处理异常signal@SmartElectron好的,但我很好奇,你能解释一下为什么需要这种方法吗?如果我们在session.commit()中遇到异常怎么办
当我们不重新引发异常时?@Pranjal在session.commit()中的异常未被捕获,因为它在try
块之外,所以不需要重新引发它。@zvone这就是为什么,我认为更好的方法是包含session.commit()
在中尝试
块本身,而不是在else块中。