Try to add
app.teardown_request(Exception=None)
Decorator, which is executed at the end of each request. I am currently experiencing a similar problem, and it seems that today I really resolved its use.
@app.teardown_request def teardown_request(exception=None): Session.remove() if exception and Session.is_active: print(exception) Session.rollback()
I do not use Flask-SQLAlchemy Raw SQLAlchemy , so you may have differences.
In documents
Break callbacks are special callbacks at which they are executed at another point. Strictly speaking, they are independent of the processing of actual requests, since they are related to the life cycle of the RequestContext object. When the request context is exposed, the teardown_request () functions are called.
In my case, I open a new scoped_session for each query, requiring me to delete it at the end of each query ( Flask-SQLAlchemy may not be needed). In addition, the teardown_request function is thrown by Exception if it occurred during the context. In this case, if an exception occurred (it is possible that the transaction was not deleted or a rollback was not required), we check whether there was an exception and a rollback.
If this does not work for my own testing, the next thing I was going to do is session.commit() at each break, just to make sure everything is cleared
UPDATE: a message also appears stating that MySQL disconnects connections after 8 hours, which will damage the session.
set pool_recycle=3600 in the configuration of your engine or in the setting <MySQL timeout. This is combined with the correct viewing of the session (closing sessions).
source share