Sqlalchemy - rollback when exception

谁说我不能喝 提交于 2021-02-07 06:56:20

问题


I need to rollback a transaction in core.event 'handle_error' (catch 'KeyboardInterrupt'), but the parameter in this event is ExceptionContext, how do this?


回答1:


I usually have this kind of pattern when working with 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()

To make things easier to use, it is useful to have this as a context manager:

@contextmanager
def get_session():
    session = get_the_session_one_way_or_another()

    try:
        yield session
    except:
        session.rollback()
        raise
    else:
        session.commit()

And then:

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

If an exception is raised within the block, the transaction will be rolled back by the context manager.


*There is an empty except: which catches literally everything. That is usually not what you want, but here the exception is always re-raised, so it's fine.



来源:https://stackoverflow.com/questions/52232979/sqlalchemy-rollback-when-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!