Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 299
dukebody Avatar asked Oct 22 '15 15:10

dukebody


People also ask

What is rollback in SQLAlchemy?

If an exception is raised within the block, the transaction will be rolled back by the context manager. *Thereisanemptyexcept:whichcatchesliterallyeverything. That is usually not what you want, but here the exception is always re-raised, so it's fine.

What is Autocommit SQLAlchemy?

In particular, it now features “autobegin” operation, which means the point at which a transaction begins may be controlled, without using the legacy “autocommit” mode. The Session tracks the state of a single “virtual” transaction at a time, using an object called SessionTransaction .

What is SQLAlchemy Session flush?

session. flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.

What does Session refresh do SQLAlchemy?

You can use session. refresh() to immediately get an up-to-date version of the object, even if the session already queried the object earlier.


1 Answers

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.

like image 89
reptilicus Avatar answered Sep 20 '22 07:09

reptilicus