Skip to content

Instantly share code, notes, and snippets.

@robyoung
Last active January 31, 2022 06:35
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robyoung/68e2121c045f117bea78 to your computer and use it in GitHub Desktop.
Save robyoung/68e2121c045f117bea78 to your computer and use it in GitHub Desktop.
Flask-SQLAlchemy set per request isolation level
def isolation_level(level):
"""Return a Flask view decorator to set SQLAlchemy isolation level
Usage::
@main.route("/thingy/<id>", methods=["POST"])
@isolation_level("SERIALIZABLE")
def update_a_thing(id):
...
"""
def decorator(view):
def view_wrapper(*args, **kwargs):
db.session.connection(execution_options={'isolation_level': level})
return view(*args, **kwargs)
return view_wrapper
return decorator
@sombek
Copy link

sombek commented Dec 18, 2019

Is this thing would be any helpful?
I don't have any idea if this is going to work
but isn't going to make it easier? instead of adding this decorator before all routes?

This code is not tested, not sure if this even works

@app.after_request
def after_request():
     db.session.connection(execution_options={'isolation_level': level})

@k-time
Copy link

k-time commented Jan 31, 2022

I don't think this actually works in Flask-SQLAlchemy, I get the warning

SAWarning: Connection is already established for the given bind; execution_options ignored

because Flask-SQLAlchemy doesn't allow you to change the isolation level after the connection is established.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment