[Twisted-Python] 2006, 'MySQL server has gone away'

Yoann Aubineau yoann.aubineau at gmail.com
Mon Oct 15 08:06:17 EDT 2007

2007/9/20, Phil Christensen <phil at bubblehouse.org>:
> On Sep 20, 2007, at 7:39 AM, Werner Thie wrote:
> > Hi all
> >
> > While using mySQL V 5.0.33 and MySQL-python-1.2.2 with twisted/
> > adbapi with the following connection params
> [snip snip snip]
> > I noticed (2006, 'MySQL server has gone away') errors, which seem
> > to be not recoverable from an adbapi standpoint.
> [snip snip snip]
> > Questions:
> > - are there any adverse effects in applying this patch and setting
> > reconnect: 1 in DB_ARGS?
> >
> > - is there a better, safer way to avoid this nasty error?
> >
> > Thxs, Werner
> I believe this is what the 'cp_reconnect' keyword argument to the
> ConnectionPool constructor does.

In case it helps:

The cp_reconnect keyword is mandatory but not sufficient for what I've
experienced. At least with MySQL server version 4.1.7, a disconnection
raises a generic OperationalError which one has to parse to know what
actually happened.

Hence the need to subclass ConnectionPool and surcharge
_runInteraction for adding the ability to retry on MySQL connection
lost. Or maybe is there a better way to do that?

---- CODE ----

import twisted.enterprise.adbapi
    from MySQLdb import OperationalError
except ImportError:
    OperationalError = None

class EnhancedConnectionPool(adbapi.ConnectionPool):
    def _runInteraction(self, *args, **kwargs):
            d = abdapi.ConnectionPool._runInteraction(self, *args, **kwargs)
        except OperationalError, e:
            errormsg = str(e).lower()
            messages = (
                "lost connection to mysql server during query",
                "server has gone away"
            for msg in messages:
                if msg in errormsg:
                    d = abdapi.ConnectionPool._runInteraction(self,
*args, **kwargs)
                    return d
        return d

---- / CODE ----

More information about the Twisted-Python mailing list