如果引发异常,如何使 Flask-SQLAlchemy 自动回滚会话? [英] How to make Flask-SQLAlchemy automatically rollback the session if an exception is raised?

查看:37
本文介绍了如果引发异常,如何使 Flask-SQLAlchemy 自动回滚会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个使用 Flask-SQLAlchemy 构建的应用程序,以便在视图引发异常的情况下回滚对数据库所做的所有更改,该异常在视图代码之外冒泡(即未捕获到内部).

I'd like to setup an app built with Flask-SQLAlchemy to rollback all changes done to the database if the view raises an exception that bubbles outside the view code (i.e. not catched inside).

即使某些对象在子事务中自动或直接通过 session.commit() 刷新到数据库,我也希望它能够工作.

I'd like it to work even if some objects are flushed to the database in subtransactions, either automatically or directly via session.commit().

类似于Django的事务请求包装.

推荐答案

你可以这样做:

@app.teardown_request
def teardown_request(exception):
    if exception:
        db.session.rollback()
    db.session.remove()

查看此处了解teardown_request信息.如果您处于调试模式,您可能需要设置 PRESERVE_CONTEXT_ON_EXCEPTION 配置变量.

Have a look here for teardown_request info. You might need to set the PRESERVE_CONTEXT_ON_EXCEPTION config variable if you are in debug mode.

这篇关于如果引发异常,如何使 Flask-SQLAlchemy 自动回滚会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆