What is this problem about:
Recently, This Mysql error message has appeared always in the morning. It means that there are no MySQL connections anymore. By MySQL default, idling database connections will be closed after 8 hours. So SqlAlchemy reports the error.
Solution:
engine = create_engine(db_path, pool_size = 100, pool_recycle=3600)
Add the pool_recycle variable to the connection. It makes SqlAlchemy engine reconnect every 3600 seconds.
Update:
It doesn't work in the project based on Tornado and SQLAlchemy. There are many people having the same problem in the Stack Overflow. Thanks to @Lepture, he gives a solution. We can set a PeriodicCallback to ping mysql every pool recycle time, so that mysql can not go away.
I use this database.py created by Lepture to integrate Tornado and SQLAlchemy. Referring to his article Fix MySQL has gone away, I modify the part of code as blow.
from tornado.ioloop import PeriodicCallback
if pool_recycle:
# ping db, so that mysql won't goaway
PeriodicCallback(self._ping_db, kwargs['pool_recycle'] * 1000).start()
def _ping_db(self):
self.session.execute('show variables')