Skip to main content
 首页 » 编程设计

python之Sqlalchemy之异常时回滚

2025年05月04日15duanxz

我需要在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 

如果在 block 内引发异常,事务将由上下文管理器回滚。


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