我需要在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()
为了使事情更容易使用,将它作为上下文管理器是有用的:
@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
如果在块中引发异常,则事务将由上下文管理器回滚。
*有一个空的except:
,它可以捕获所有东西。这通常不是你想要的,但这里异常总是重新提出,所以没关系。