mirror of
https://github.com/psycopg/psycopg2.git
synced 2025-08-05 21:00:08 +03:00
Merge 4e6ab07b30
into 90ee1ebba5
This commit is contained in:
commit
154fe12af2
21
lib/pool.py
21
lib/pool.py
|
@ -32,6 +32,20 @@ class PoolError(psycopg2.Error):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ConnectionContext(object):
|
||||||
|
|
||||||
|
def __init__(self, pool):
|
||||||
|
self.pool = pool
|
||||||
|
self._conn = None
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
self._conn = self.pool.getconn()
|
||||||
|
return self._conn
|
||||||
|
|
||||||
|
def __exit__(self, exc_type, exc_value, traceback):
|
||||||
|
self.pool.putconn(self._conn)
|
||||||
|
|
||||||
|
|
||||||
class AbstractConnectionPool(object):
|
class AbstractConnectionPool(object):
|
||||||
"""Generic key-based pooling code."""
|
"""Generic key-based pooling code."""
|
||||||
|
|
||||||
|
@ -57,6 +71,9 @@ class AbstractConnectionPool(object):
|
||||||
for i in range(self.minconn):
|
for i in range(self.minconn):
|
||||||
self._connect()
|
self._connect()
|
||||||
|
|
||||||
|
def __call__(self):
|
||||||
|
return ConnectionContext(self)
|
||||||
|
|
||||||
def _connect(self, key=None):
|
def _connect(self, key=None):
|
||||||
"""Create a new connection and assign it to 'key' if not None."""
|
"""Create a new connection and assign it to 'key' if not None."""
|
||||||
conn = psycopg2.connect(*self._args, **self._kwargs)
|
conn = psycopg2.connect(*self._args, **self._kwargs)
|
||||||
|
@ -76,7 +93,7 @@ class AbstractConnectionPool(object):
|
||||||
"""Get a free connection and assign it to 'key' if not None."""
|
"""Get a free connection and assign it to 'key' if not None."""
|
||||||
if self.closed: raise PoolError("connection pool is closed")
|
if self.closed: raise PoolError("connection pool is closed")
|
||||||
if key is None: key = self._getkey()
|
if key is None: key = self._getkey()
|
||||||
|
|
||||||
if key in self._used:
|
if key in self._used:
|
||||||
return self._used[key]
|
return self._used[key]
|
||||||
|
|
||||||
|
@ -88,7 +105,7 @@ class AbstractConnectionPool(object):
|
||||||
if len(self._used) == self.maxconn:
|
if len(self._used) == self.maxconn:
|
||||||
raise PoolError("connection pool exhausted")
|
raise PoolError("connection pool exhausted")
|
||||||
return self._connect(key)
|
return self._connect(key)
|
||||||
|
|
||||||
def _putconn(self, conn, key=None, close=False):
|
def _putconn(self, conn, key=None, close=False):
|
||||||
"""Put away a connection."""
|
"""Put away a connection."""
|
||||||
if self.closed: raise PoolError("connection pool is closed")
|
if self.closed: raise PoolError("connection pool is closed")
|
||||||
|
|
Loading…
Reference in New Issue
Block a user