Flask-SQLAlchemy "Mysql Server Has Gone"

January 20, 2013

I have a Flask server deployment which are access by only a few users in an infrequent manner, and I frequently bump into “MySQL server has gone away” when no one used it for a few days.

Initially I though it was a uwsgi problem (applying –lazy and –lazy-apps param to uwsgi), but sadly it didn’t work.

Then I suspect it could be a SQLAlchemy problem or Flask-SQLAlchemy problem, which leads me to this article.

Flask-SQLAlchemy seems to use scoped session, so that is covered.

I found someone reported the same problem, where the patch seems to be applied on the package I downloaded (0.16).

Sadly, the patch is not applied to the version I had downloaded (the setup.py version number is not updated to 0.8); and the driver I happend to use is “mysql+mysqldb”.

or I could set the settings manually through the Flask variable SQLALCHEMY_POOL_RECYCLE

I have not confirmed this solution works yet, have to observer for a few days ;)

Update 2012-02-26: Error “Can’t reconnect until invalid transaction is rolled back” popup once in a while (“MySQL server has gone away” is observed as well), where refreshing the page doesn’t make the problem go away (need restart).

Based on this, besides SQLALCHEMY_POOL_RECYCLE, the next culprit seems to be session is closed/remove before end of request (this is tricky).

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.