How to make Flask-SQLAlchemy automatically rollback the session if an exception is raised?

dukebody picture dukebody · Oct 22, 2015 · Viewed 16.7k times · Source

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).

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

Something similar to Django's transaction request wrapping.

Answer

reptilicus picture reptilicus · Oct 22, 2015

you can do something like this:

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

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.