我需要回滚中的事务core.event 'handle_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()
Run Code Online (Sandbox Code Playgroud)
为了使事情更易于使用,将其作为上下文管理器很有用:
@contextmanager
def get_session():
session = get_the_session_one_way_or_another()
try:
yield session
except:
session.rollback()
raise
else:
session.commit()
Run Code Online (Sandbox Code Playgroud)
然后:
with get_session() as session:
# do something with the session
Run Code Online (Sandbox Code Playgroud)
如果在该块内引发异常,则上下文管理器将回滚该事务。
*有一个空洞except:
,几乎可以抓住所有东西。通常这不是您想要的,但是在这里总是会引发异常,所以很好。