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.
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.
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 .
session. flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With