ctds.pool

class ctds.pool.ConnectionPool(dbapi2, params, idlettl=None, maxsize=None, block=False)

A basic connection pool for DB-API 2.0-compliant database drivers.

Example usage:

config = {
    'server': 'my-host',
    'database': 'MyDefaultDatabase',
    'user': 'my-username',
    'password': 'my-password',
    'appname': 'my-app-name',
    'timeout': 5
}
pool = ConnectionPool(pydbmod, config)

conn = pool.acquire()
try:
    cursor = conn.cursor()
    try:
        cursor.execute('SELECT @@VERSION')
    finally:
        cursor.close()
finally:
    pool.release(conn)

New in version 1.2.

Note

Idle connection collection only occurs during calls to acquire() and does not happen automatically in the background.

Parameters
  • dbapi2 – The DB-API 2 module used to create connections. This module must implement the PEP 0249 specification.

  • params (dict) – Connection parameters to pass directly to the PEP 0249#connect method when creating a new connection.

  • idlettl (float) – The maximum time, in seconds, a connection can sit idle before it is discarded. If not specified, connections are retained indefinitely.

  • maxsize (int) – The maximum number of connections to keep in the pool.

  • block (bool) – Block until a connection is released back to the pool? This is only applicable when a maxsize value is specified. If False, a new connection will be created as needed, but the number of connections retained in the pool will never exceed maxsize.

acquire()

Get a new connection from the pool. This will return an existing connection, if one is available in the pool, or create a new connection.

Warning

If the pool was created with maxsize and block=True, this method may block until a connection is available in the pool.

connection()

Acquire a connection in a managed context for use with the Python with keyword.

with pool.connection() as connection:
    # do stuff with connection
finalize()

Release all connections contained in the pool.

Note

This should be called to cleanly shutdown the pool, i.e. on process exit.

release(connection)

Return a connection back to the pool.

Prior to release, ctds.Connection.rollback() is called to rollback any pending transaction.

Note

This must be called once for every successful call to acquire().

Parameters

connection – The connection object returned by acquire().