SQLAlchemy-发生异常时回滚

Sma*_*ron 1 python sqlalchemy

我需要回滚中的事务core.event 'handle_error' (catch 'KeyboardInterrupt'),但是此事件中的参数是ExceptionContext,该怎么做?

zvo*_*one 5

在使用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:,几乎可以抓住所有东西。通常这不是您想要的,但是在这里总是会引发异常,所以很好。

  • @zvone 这就是为什么,我认为更好的方法是在 `try` 块本身而不是在 else 块中包含 `session.commit()`。 (5认同)
  • 如果我们在不重新引发异常时在“session.commit()”中遇到异常怎么办? (3认同)