How to get Flask-SQLAlchemy to automatically roll back a session if an exception occurs?

I would like to configure an application built using Flask-SQLAlchemy to undo all changes made to the database if the view throws an exception that goes beyond the view code (i.e. not hooked inside).

I would like it to work even if some objects were dumped into the database in subtransactions, either automatically or directly through session.commit() .

Something like a Django transaction wrapper .

+7
python flask flask-sqlalchemy transactions
source share
1 answer

you can do something like this:

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

Look here for teardown_request info. You may need to set the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable if you are in debug mode.

+12
source share

All Articles