Skip to content

Instantly share code, notes, and snippets.

@nyov
Forked from powdahound/adbapi.py
Last active August 17, 2017 05:53
Show Gist options
  • Save nyov/8582871 to your computer and use it in GitHub Desktop.
Save nyov/8582871 to your computer and use it in GitHub Desktop.
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
http://www.gelens.org/2008/09/12/reinitializing-twisted-connectionpool/
by checking exceptions by error code and only disconnecting the current
connection instead of all of them.
Also see:
http://twistedmatrix.com/pipermail/twisted-python/2009-July/020007.html
(2006: MySQL server has gone away
2013: Lost connection to MySQL server
1213: Deadlock found when trying to get lock)
"""
def _runInteraction(self, interaction, *args, **kw):
try:
return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)
except MySQLdb.OperationalError, e:
if e[0] not in (2006, 2013, 1213):
raise
log.msg("%s got error %s, retrying operation" % (self.__class__.__name__, e))
conn = self.connections.get(self.threadID())
self.disconnect(conn)
# try the interaction again
return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment