Avoiding "MySQL server has gone away" on infrequently used Python / Flask server with SQLAlchemy

Viewed 34208

How can Flask / SQLAlchemy be configured to create a new database connection if one is not present?

I have an infrequently visited Python / Flask server which uses SQLAlchemy. It gets visited every couple of days, and on the first visit it often throws a "MySQL server has gone away" error. Subsequent page views are fine, but it looks unprofessional to have this initial error.

I'd like to know the correct way to handle this - advice like "make a really long time out", which would be about 4 days long in this case, doesn't seem correct. How can I test for the lack of a database connection and create one if needed?

7 Answers

The pessimistic approach as described by @wim

pool_pre_ping=True

can now be done for Flask-SQLAlchemy using a config var -->

SQLALCHEMY_POOL_PRE_PING = True

When I encountered this error I was storing a LONGBLOB / LargeBinary image ~1MB in size. I had to adjust the max_allowed_packet config setting in MySQL.

I used mysqld --max-allowed-packet=16M

If you use Pool, you should set recyle less than wait_timeout of DB wait_timeout is 60. So I set 40 to recyle

from sqlalchemy.pool import Pool
pool.QueuePool(self.get_connection, max_overflow=0,pool_size=40,recycle=50)
Related