hab hier ein einfaches modul für connectionpooling, unittests fehlen noch aber funkt schon ganz gut

lg
Julian
Code: Alles auswählen
"""
Simple connection Pooling for DB-API 2.0 conform drivers
"""
import threading
import logging
logger = logging.getLogger(__name__)
class _ConnectionProxy(object):
"""
Class which manager the autorelease of connections
"""
def __init__(self, con, distroy_hook):
self._con = con
self._distroy_hook = distroy_hook
#self.__dict__.update(con.__dict__)
def __getattr__(self, attr):
return getattr(self._con, attr)
def __del__(self):
self._distroy_hook(self._con)
class DbApi2Pool(object):
"""
Implements verry simple DB2 api pooling, but threading safe(hopefully :))
the connections are safed in a dict, where the key is the connection and the
value is True if the connection is free and false if the connection is used
@todo: max and min connection handling
"""
def __init__(self, params, driver):
"""
@param params: the kwparams for the connection
@type params: dict
@param driver: mostly a module object which have a connect function,
kwparams pass to it.
@type param: a object with a connect method
"""
self._params = params
self._driver = driver
self._connections = {}
self._connections_lock = threading.Lock()
def get(self):
"""
@return: a connection out of the pool or a fresh one
@rtype: a weakref proxy
"""
ret = None
self._connections_lock.acquire()
##is a connection free
for (con, free) in self._connections.items():
if free:
logger.debug("Locking connection %X from pool" % id(con))
ret = con
self._connections[con] = False
##if not create a new one
if ret == None:
try:
ret = self._driver.connect(**self._params)
self._connections[ret] = False
logger.debug("Added new connection %X to pool" % id(ret))
except:
logger.exception('Failed to connect')
self._connections_lock.release()
##create a weekref so if the weakref is released we release the connection object
return _ConnectionProxy(ret, self._release_hook)
def _release_hook(self, conref):
logger.debug("Releasing connection %X back to pool" % id(conref))
self._connections_lock.acquire()
for (con, free) in self._connections.items():
if con == conref:
self._connections[con] = True
self._connections_lock.release()