I use a CherryPy webserver (Python 2.7) with a local MySQL database. In short, after some days, I get the following error when performing a new SQL query:
MySQL server has gone away
Although I can find some sources to this problem, they are not related to CherryPy actually. Restarting CherryPy resolves the problem. I guess, CherryPy looses the connection and is not able to reconnect?.
Thus, my question is:
- How can I check the database connection and if it is not alive, reconnect then? or
- simply, how to avoid the error mentioned above?.
In the following, I show some simplified code version that I am using:
def dbconnect(thread_index):
"""
Creates a database connection for each thread that CherryPy creates
:param thread_index:
"""
cherrypy.thread_data.db = MySQLdb.connect("localhost", "user",
"password", "databasename")
class website(object):
@cherrypy.expose
def index(self):
c = cherrypy.thread_data.db.cursor()
c.execute("Select * from ATable")
(output,) = c.fetchone()
# generate some html output ...
cherrypy.engine.subscribe('start_thread', dbconnect)
website = website()
cherrypy.quickstart(website)
Now If I visit the index page after some days where nothing happened on the server, the index method throws the MySQL server has gone away error.
Hopefully, this question might be interesting for all who use CherryPy and get the SQL error one day. Thank you very much :-)