[Twisted-Python] Creating a new selectable (for Pg async interface)
Matthias Urlichs
smurf at noris.de
Mon Dec 16 00:33:24 EST 2002
Hi,
Gerhard Häring:
> Perhaps you have a tip on how to improve my connection pool? Here's some
> rough code I produced a few minutes ago:
>
Take the connection out of the pool while it's in use.
Use a Deferred to return the connection.
Something along these lines:
class ConnectionPool:
def __init__(size=5):
self.waiting=[]
self.connections=[]
for i in range(size):
conn = PoolConnection()
conn.is_free=1
self.connections.append(conn)
def findConn(self):
d=Deferred()
try:
conn = self.connections.pop()
except IndexError:
self.waiting.append(d)
else:
conn.is_free=0
d.callback(conn)
return d
def freeConn(self,conn):
if conn.is_free:
return
try:
d = self.waiting.pop()
except IndexError:
conn.is_free=1
self.connections.push(conn)
else:
d.callback(conn)
For bonus points, subclass your db connection to self-add itself back to
the pool when it's no longer in use:
class PoolConnection(YourDatabaseConnection):
def __init__(self,pool,*args,**kwargs):
YourDatabaseConnection.__init__(self,*args,**kwargs)
self.__pool=weakref.ref(__pool)
def __del__(self):
pool=self.__pool()
try:
pool.freeConn(self)
except:
pass
--
Matthias Urlichs | noris network AG | http://smurf.noris.de/
--
The teacher comes when the soul calls--and thank goodness, for the ego
is never fully ready.
-- Clarissa Pinkola Estes, "Women Who Run With the Wolves"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://twistedmatrix.com/pipermail/twisted-python/attachments/20021216/463c67f2/attachment.pgp
More information about the Twisted-Python
mailing list