Flask Sqlalchemy Sessions Out Of Sync
I have a Flask REST API, running with a gunicorn/nginx stack. There is global SQLAlchemy session set up once for each thread that the API runs on. I set up an endpoint /test/ for
Solution 1:
Please use flask-sqlalchemy if you're using flask, it takes care of the lifecycle of the session for you.
If you insist on doing it yourself, the correct pattern is to create a session for each request instead of having a global session. You should be doing
Session = scoped_session(session_factory, scopefunc=flask._app_ctx_stack.__ident_func__)
return Session
instead of
Session = scoped_session(session_factory)
return Session()
And do
session = Session()
every time you need a session. By virtue of the scoped_session
and the scopefunc
, this will return you a different session in each request, but the same session in the same request.
Solution 2:
Figured it out. What I did was to add a setup and teardown to the request in my app's __init__.py:
@app.before_request
def startup_session():
db.session = db.connectSQLAlchemy()
@app.teardown_request
def shutdown_session(exception=None):
db.session.close()
still using the global session object in my db module:
db.py:
....
session = None
....
The scoped_session
handles the different threads, I think...
Please advise if this is a terrible way to do this for some reason. =c)
Post a Comment for "Flask Sqlalchemy Sessions Out Of Sync"