Search code examples
pythonmysqldjangopython-3.xpymysql

Django + PyMySQL throws "MySQL server has gone away" after a couple of hours


I have a module in my Django 1.6 app (Python3) that runs like a daemon but it's throwing this error after a couple of hours running:

OperationalError: (2006, "MySQL server has gone away (BrokenPipeError(32, 'Broken pipe'))")

It seems that exist a flag in MySQL connection that autoreconnect called MYSQL_OPT_RECONNECT, should I set it? Where? I’m using PyMySQL connector (by running pymysql.install_as_MySQLdb() in the main __init__.py).


Solution

  • We have to catch the error when it is thrown, and call django.db.connection.close() to reconnect.

    from django.db import connection
    from django.db.utils import OperationalError
    ...
    try:
        function_that_uses_database_connection()
    except OperationalError:
        connection.close()
        function_that_uses_database_connection()
    

    I did not found a way to make it automatic, though, but it did the job.