Jeffrey Gelens

Twisted ConnectionPool Revisited

Last year I posted a fix to re-establish database connections in the pool when connections are lost. This hack worked great for me and a couple of other people around the internet.

The enhanced version by powdahound:

from twisted.enterprise import adbapi
from twisted.python import log
import MySQLdb

class ReconnectingConnectionPool(adbapi.ConnectionPool):
    """Reconnecting adbapi connection pool for MySQL.

    This class improves on the solution posted at
    by checking exceptions by error code and only disconnecting the current
    connection instead of all of them.

    Also see:

    def _runInteraction(self, interaction, *args, **kw):
            return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)
        except MySQLdb.OperationalError, e:
            if e[0] not in (2006, 2013):
            log.msg("RCP: got error %s, retrying operation" %(e))
            conn = self.connections.get(self.threadID())
            # try the interaction again
            return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)