异常时Sqlalchemy回滚

2024-10-04 03:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在core.event 'handle_error' (catch 'keyboardInterrupt')中回滚一个事务,但是这个事件中的参数是ExceptionContext,怎么做?在


Tags: coreevent参数事件error事务handlecatch
1条回答
网友
1楼 · 发布于 2024-10-04 03:24:15

我在使用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()

为了使事情更易于使用,将其作为上下文管理器很有用:

^{pr2}$

然后:

with get_session() as session:
    # do something with the session

如果在块中引发异常,则上下文管理器将回滚事务。在


*有一个空的except:它可以捕捉所有的东西。这通常不是您想要的,但是在这里总是会重新引发异常,所以没关系。

相关问题 更多 >