Reinitializing Twisted ConnectionPool
I ran in a situation that database connections in a Twisted connection pool are lost when the database server is being restarted. The connection pool should be reinitialized, so that the application keeps doing its job. During my search on the internet I found several people searching a solution for the same problem, so here it is:
from twisted.enterprise import adbapi
from twisted.python import log
from MySQLdb import OperationalError
class ReconnectingConnectionPool(adbapi.ConnectionPool):
def _runInteraction(self, interaction, *args, **kw):
try:
return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)
except OperationalError, e:
error_messages = ("mysql server has gone away", "lost connection to mysql server during query")
if any([x in str(e).lower() for x in error_messages]):
log.msg(" >> Resetting DB pool")
for conn in self.connections.values():
self._close(conn)
self.connections.clear()
return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)
else:
raise
Doug Farrell Shouldn't there also be a constructor to properly initialize adbapi.ConnectionPool? Something like this:
def __init__(self, dbapiName, *connargs, **connkw):
'''Call the underlying parent class to initialize it'''
adbapi.ConnectionPool.__init__(self, dbapiName, *connargs, **connkw)
Just wondering, thanks,
Doug
Paul Goins I don't think there should be, Doug. In python, if no __init__ is defined, it'll just use the __init__ of the parent class. The code should be good.
Doug Farrell Paul,
Thanks for the reply. I was under the impression that Parent Class constructors (__init__ methods) weren't called automatically. It's good to find out otherwise, this will simplify my overzealous coding in my derived classes. :)
Doug
Jeffrey Gelens There is also an updated version if this snippet: http://www.gelens.org/2009/09...