DB-API 2.0 Pool

Stellt hier eure Projekte vor.
Internetseiten, Skripte, und alles andere bzgl. Python.
Beiträge: 22
Registriert: Sonntag 10. Dezember 2006, 20:17

DB-API 2.0 Pool

Beitragvon uphill » Dienstag 10. April 2007, 18:17

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


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

    def __getattr__(self, attr):
        return getattr(self._con, attr)
    def __del__(self):

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
        ##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:
                ret = self._driver.connect(**self._params)
                self._connections[ret] =  False
                logger.debug("Added new connection %X to pool" % id(ret))
                logger.exception('Failed to connect')
        ##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))
        for (con, free) in self._connections.items():
            if con == conref:
                self._connections[con] = True

Wer ist online?

Mitglieder in diesem Forum: 0 Mitglieder