Release: 1.1.0b1 | Release Date: not released

SQLAlchemy 1.1 Documentation

Connection Pooling

A connection pool is a standard technique used to maintain long running connections in memory for efficient re-use, as well as to provide management for the total number of connections an application might use simultaneously.

Particularly for server-side web applications, a connection pool is the standard way to maintain a “pool” of active database connections in memory which are reused across requests.

SQLAlchemy includes several connection pool implementations which integrate with the Engine. They can also be used directly for applications that want to add pooling to an otherwise plain DBAPI approach.

Connection Pool Configuration

The Engine returned by the create_engine() function in most cases has a QueuePool integrated, pre-configured with reasonable pooling defaults. If you’re reading this section only to learn how to enable pooling - congratulations! You’re already done.

The most common QueuePool tuning parameters can be passed directly to create_engine() as keyword arguments: pool_size, max_overflow, pool_recycle and pool_timeout. For example:

engine = create_engine('postgresql://me@localhost/mydb',
                       pool_size=20, max_overflow=0)

In the case of SQLite, the SingletonThreadPool or NullPool are selected by the dialect to provide greater compatibility with SQLite’s threading and locking model, as well as to provide a reasonable default behavior to SQLite “memory” databases, which maintain their entire dataset within the scope of a single connection.

All SQLAlchemy pool implementations have in common that none of them “pre create” connections - all implementations wait until first use before creating a connection. At that point, if no additional concurrent checkout requests for more connections are made, no additional connections are created. This is why it’s perfectly fine for create_engine() to default to using a QueuePool of size five without regard to whether or not the application really needs five connections queued up - the pool would only grow to that size if the application actually used five connections concurrently, in which case the usage of a small pool is an entirely appropriate default behavior.

Switching Pool Implementations

The usual way to use a different kind of pool with create_engine() is to use the poolclass argument. This argument accepts a class imported from the sqlalchemy.pool module, and handles the details of building the pool for you. Common options include specifying QueuePool with SQLite:

from sqlalchemy.pool import QueuePool
engine = create_engine('sqlite:///file.db', poolclass=QueuePool)

Disabling pooling using NullPool:

from sqlalchemy.pool import NullPool
engine = create_engine(
          'postgresql+psycopg2://scott:tiger@localhost/test',
          poolclass=NullPool)

Using a Custom Connection Function

All Pool classes accept an argument creator which is a callable that creates a new connection. create_engine() accepts this function to pass onto the pool via an argument of the same name:

import sqlalchemy.pool as pool
import psycopg2

def getconn():
    c = psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
    # do things with 'c' to set up
    return c

engine = create_engine('postgresql+psycopg2://', creator=getconn)

For most “initialize on connection” routines, it’s more convenient to use the PoolEvents event hooks, so that the usual URL argument to create_engine() is still usable. creator is there as a last resort for when a DBAPI has some form of connect that is not at all supported by SQLAlchemy.

Constructing a Pool

To use a Pool by itself, the creator function is the only argument that’s required and is passed first, followed by any additional options:

import sqlalchemy.pool as pool
import psycopg2

def getconn():
    c = psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
    return c

mypool = pool.QueuePool(getconn, max_overflow=10, pool_size=5)

DBAPI connections can then be procured from the pool using the Pool.connect() function. The return value of this method is a DBAPI connection that’s contained within a transparent proxy:

# get a connection
conn = mypool.connect()

# use it
cursor = conn.cursor()
cursor.execute("select foo")

The purpose of the transparent proxy is to intercept the close() call, such that instead of the DBAPI connection being closed, it is returned to the pool:

# "close" the connection.  Returns
# it to the pool.
conn.close()

The proxy also returns its contained DBAPI connection to the pool when it is garbage collected, though it’s not deterministic in Python that this occurs immediately (though it is typical with cPython).

The close() step also performs the important step of calling the rollback() method of the DBAPI connection. This is so that any existing transaction on the connection is removed, not only ensuring that no existing state remains on next usage, but also so that table and row locks are released as well as that any isolated data snapshots are removed. This behavior can be disabled using the reset_on_return option of Pool.

A particular pre-created Pool can be shared with one or more engines by passing it to the pool argument of create_engine():

e = create_engine('postgresql://', pool=mypool)

Pool Events

Connection pools support an event interface that allows hooks to execute upon first connect, upon each new connection, and upon checkout and checkin of connections. See PoolEvents for details.

Dealing with Disconnects

The connection pool has the ability to refresh individual connections as well as its entire set of connections, setting the previously pooled connections as “invalid”. A common use case is allow the connection pool to gracefully recover when the database server has been restarted, and all previously established connections are no longer functional. There are two approaches to this.

Disconnect Handling - Optimistic

The most common approach is to let SQLAlchemy handle disconnects as they occur, at which point the pool is refreshed. This assumes the Pool is used in conjunction with a Engine. The Engine has logic which can detect disconnection events and refresh the pool automatically.

When the Connection attempts to use a DBAPI connection, and an exception is raised that corresponds to a “disconnect” event, the connection is invalidated. The Connection then calls the Pool.recreate() method, effectively invalidating all connections not currently checked out so that they are replaced with new ones upon next checkout:

from sqlalchemy import create_engine, exc
e = create_engine(...)
c = e.connect()

try:
    # suppose the database has been restarted.
    c.execute("SELECT * FROM table")
    c.close()
except exc.DBAPIError, e:
    # an exception is raised, Connection is invalidated.
    if e.connection_invalidated:
        print "Connection was invalidated!"

# after the invalidate event, a new connection
# starts with a new Pool
c = e.connect()
c.execute("SELECT * FROM table")

The above example illustrates that no special intervention is needed, the pool continues normally after a disconnection event is detected. However, an exception is raised. In a typical web application using an ORM Session, the above condition would correspond to a single request failing with a 500 error, then the web application continuing normally beyond that. Hence the approach is “optimistic” in that frequent database restarts are not anticipated.

Setting Pool Recycle

An additional setting that can augment the “optimistic” approach is to set the pool recycle parameter. This parameter prevents the pool from using a particular connection that has passed a certain age, and is appropriate for database backends such as MySQL that automatically close connections that have been stale after a particular period of time:

from sqlalchemy import create_engine
e = create_engine("mysql://scott:tiger@localhost/test", pool_recycle=3600)

Above, any DBAPI connection that has been open for more than one hour will be invalidated and replaced, upon next checkout. Note that the invalidation only occurs during checkout - not on any connections that are held in a checked out state. pool_recycle is a function of the Pool itself, independent of whether or not an Engine is in use.

Disconnect Handling - Pessimistic

At the expense of some extra SQL emitted for each connection checked out from the pool, a “ping” operation established by a checkout event handler can detect an invalid connection before it is used. In modern SQLAlchemy, the best way to do this is to make use of the ConnectionEvents.engine_connect() event, assuming the use of a Engine and not just a raw Pool object:

from sqlalchemy import exc
from sqlalchemy import event
from sqlalchemy import select

some_engine = create_engine(...)

@event.listens_for(some_engine, "engine_connect")
def ping_connection(connection, branch):
    if branch:
        # "branch" refers to a sub-connection of a connection,
        # we don't want to bother pinging on these.
        return

    try:
        # run a SELECT 1.   use a core select() so that
        # the SELECT of a scalar value without a table is
        # appropriately formatted for the backend
        connection.scalar(select([1]))
    except exc.DBAPIError as err:
        # catch SQLAlchemy's DBAPIError, which is a wrapper
        # for the DBAPI's exception.  It includes a .connection_invalidated
        # attribute which specifies if this connection is a "disconnect"
        # condition, which is based on inspection of the original exception
        # by the dialect in use.
        if err.connection_invalidated:
            # run the same SELECT again - the connection will re-validate
            # itself and establish a new connection.  The disconnect detection
            # here also causes the whole connection pool to be invalidated
            # so that all stale connections are discarded.
            connection.scalar(select([1]))
        else:
            raise

The above recipe has the advantage that we are making use of SQLAlchemy’s facilities for detecting those DBAPI exceptions that are known to indicate a “disconnect” situation, as well as the Engine object’s ability to correctly invalidate the current connection pool when this condition occurs and allowing the current Connection to re-validate onto a new DBAPI connection.

For the much less common case of where a Pool is being used without an Engine, an older approach may be used as below:

from sqlalchemy import exc
from sqlalchemy import event
from sqlalchemy.pool import Pool

@event.listens_for(Pool, "checkout")
def ping_connection(dbapi_connection, connection_record, connection_proxy):
    cursor = dbapi_connection.cursor()
    try:
        cursor.execute("SELECT 1")
    except:
        # raise DisconnectionError - pool will try
        # connecting again up to three times before raising.
        raise exc.DisconnectionError()
    cursor.close()

Above, the Pool object specifically catches DisconnectionError and attempts to create a new DBAPI connection, up to three times, before giving up and then raising InvalidRequestError, failing the connection. The disadvantage of the above approach is that we don’t have any easy way of determining if the exception raised is in fact a “disconnect” situation, since there is no Engine or Dialect in play, and also the above error would occur individually for all stale connections still in the pool.

More on Invalidation

The Pool provides “connection invalidation” services which allow both explicit invalidation of a connection as well as automatic invalidation in response to conditions that are determined to render a connection unusable.

“Invalidation” means that a particular DBAPI connection is removed from the pool and discarded. The .close() method is called on this connection if it is not clear that the connection itself might not be closed, however if this method fails, the exception is logged but the operation still proceeds.

When using a Engine, the Connection.invalidate() method is the usual entrypoint to explicit invalidation. Other conditions by which a DBAPI connection might be invalidated include:

  • a DBAPI exception such as OperationalError, raised when a method like connection.execute() is called, is detected as indicating a so-called “disconnect” condition. As the Python DBAPI provides no standard system for determining the nature of an exception, all SQLAlchemy dialects include a system called is_disconnect() which will examine the contents of an exception object, including the string message and any potential error codes included with it, in order to determine if this exception indicates that the connection is no longer usable. If this is the case, the _ConnectionFairy.invalidate() method is called and the DBAPI connection is then discarded.
  • When the connection is returned to the pool, and calling the connection.rollback() or connection.commit() methods, as dictated by the pool’s “reset on return” behavior, throws an exception. A final attempt at calling .close() on the connection will be made, and it is then discarded.
  • When a listener implementing PoolEvents.checkout() raises the DisconnectionError exception, indicating that the connection won’t be usable and a new connection attempt needs to be made.

All invalidations which occur will invoke the PoolEvents.invalidate() event.

Using Connection Pools with Multiprocessing

It’s critical that when using a connection pool, and by extension when using an Engine created via create_engine(), that the pooled connections are not shared to a forked process. TCP connections are represented as file descriptors, which usually work across process boundaries, meaning this will cause concurrent access to the file descriptor on behalf of two or more entirely independent Python interpreter states.

There are two approaches to dealing with this.

The first is, either create a new Engine within the child process, or upon an existing Engine, call Engine.dispose() before the child process uses any connections. This will remove all existing connections from the pool so that it makes all new ones. Below is a simple version using multiprocessing.Process, but this idea should be adapted to the style of forking in use:

eng = create_engine("...")

def run_in_process():
  eng.dispose()

  with eng.connect() as conn:
      conn.execute("...")

p = Process(target=run_in_process)

The next approach is to instrument the Pool itself with events so that connections are automatically invalidated in the subprocess. This is a little more magical but probably more foolproof:

from sqlalchemy import event
from sqlalchemy import exc
import os

eng = create_engine("...")

@event.listens_for(engine, "connect")
def connect(dbapi_connection, connection_record):
    connection_record.info['pid'] = os.getpid()

@event.listens_for(engine, "checkout")
def checkout(dbapi_connection, connection_record, connection_proxy):
    pid = os.getpid()
    if connection_record.info['pid'] != pid:
        connection_record.connection = connection_proxy.connection = None
        raise exc.DisconnectionError(
                "Connection record belongs to pid %s, "
                "attempting to check out in pid %s" %
                (connection_record.info['pid'], pid)
        )

Above, we use an approach similar to that described in Disconnect Handling - Pessimistic to treat a DBAPI connection that originated in a different parent process as an “invalid” connection, coercing the pool to recycle the connection record to make a new connection.

API Documentation - Available Pool Implementations

class sqlalchemy.pool.Pool(creator, recycle=-1, echo=None, use_threadlocal=False, logging_name=None, reset_on_return=True, listeners=None, events=None, _dispatch=None, _dialect=None)

Bases: sqlalchemy.log.Identified

Abstract base class for connection pools.

__init__(creator, recycle=-1, echo=None, use_threadlocal=False, logging_name=None, reset_on_return=True, listeners=None, events=None, _dispatch=None, _dialect=None)

Construct a Pool.

매개 변수:
  • creator – a callable function that returns a DB-API connection object. The function will be called with parameters.
  • recycle – If set to non -1, number of seconds between connection recycling, which means upon checkout, if this timeout is surpassed the connection will be closed and replaced with a newly opened connection. Defaults to -1.
  • logging_name – String identifier which will be used within the “name” field of logging records generated within the “sqlalchemy.pool” logger. Defaults to a hexstring of the object’s id.
  • echo – If True, connections being pulled and retrieved from the pool will be logged to the standard output, as well as pool sizing information. Echoing can also be achieved by enabling logging for the “sqlalchemy.pool” namespace. Defaults to False.
  • use_threadlocal

    If set to True, repeated calls to connect() within the same application thread will be guaranteed to return the same connection object, if one has already been retrieved from the pool and has not been returned yet. Offers a slight performance advantage at the cost of individual transactions by default. The Pool.unique_connection() method is provided to return a consistenty unique connection to bypass this behavior when the flag is set.

    경고

    The Pool.use_threadlocal flag does not affect the behavior of Engine.connect(). Engine.connect() makes use of the Pool.unique_connection() method which does not use thread local context. To produce a Connection which refers to the Pool.connect() method, use Engine.contextual_connect().

    Note that other SQLAlchemy connectivity systems such as Engine.execute() as well as the orm Session make use of Engine.contextual_connect() internally, so these functions are compatible with the Pool.use_threadlocal setting.

    더 보기

    Using the Threadlocal Execution Strategy - contains detail on the “threadlocal” engine strategy, which provides a more comprehensive approach to “threadlocal” connectivity for the specific use case of using Engine and Connection objects directly.

  • reset_on_return

    Determine steps to take on connections as they are returned to the pool. reset_on_return can have any of these values:

    • "rollback" - call rollback() on the connection, to release locks and transaction resources. This is the default value. The vast majority of use cases should leave this value set.
    • True - same as ‘rollback’, this is here for backwards compatibility.
    • "commit" - call commit() on the connection, to release locks and transaction resources. A commit here may be desirable for databases that cache query plans if a commit is emitted, such as Microsoft SQL Server. However, this value is more dangerous than ‘rollback’ because any data changes present on the transaction are committed unconditionally.
    • None - don’t do anything on the connection. This setting should only be made on a database that has no transaction support at all, namely MySQL MyISAM. By not doing anything, performance can be improved. This setting should never be selected for a database that supports transactions, as it will lead to deadlocks and stale state.
    • "none" - same as None

      버전 0.9.10에 추가.

    • False - same as None, this is here for backwards compatibility.

    버전 0.7.6으로 변경: Pool.reset_on_return accepts "rollback" and "commit" arguments.

  • events – a list of 2-tuples, each of the form (callable, target) which will be passed to event.listen() upon construction. Provided here so that event listeners can be assigned via create_engine() before dialect-level listeners are applied.
  • listeners – Deprecated. A list of PoolListener-like objects or dictionaries of callables that receive events when DB-API connections are created, checked out and checked in to the pool. This has been superseded by listen().
connect()

Return a DBAPI connection from the pool.

The connection is instrumented such that when its close() method is called, the connection will be returned to the pool.

dispose()

Dispose of this pool.

This method leaves the possibility of checked-out connections remaining open, as it only affects connections that are idle in the pool.

See also the Pool.recreate() method.

recreate()

Return a new Pool, of the same class as this one and configured with identical creation arguments.

This method is used in conjunction with dispose() to close out an entire Pool and create a new one in its place.

unique_connection()

Produce a DBAPI connection that is not referenced by any thread-local context.

This method is equivalent to Pool.connect() when the Pool.use_threadlocal flag is not set to True. When Pool.use_threadlocal is True, the Pool.unique_connection() method provides a means of bypassing the threadlocal context.

class sqlalchemy.pool.QueuePool(creator, pool_size=5, max_overflow=10, timeout=30, **kw)

Bases: sqlalchemy.pool.Pool

A Pool that imposes a limit on the number of open connections.

QueuePool is the default pooling implementation used for all Engine objects, unless the SQLite dialect is in use.

__init__(creator, pool_size=5, max_overflow=10, timeout=30, **kw)

Construct a QueuePool.

매개 변수:
  • creator – a callable function that returns a DB-API connection object, same as that of Pool.creator.
  • pool_size – The size of the pool to be maintained, defaults to 5. This is the largest number of connections that will be kept persistently in the pool. Note that the pool begins with no connections; once this number of connections is requested, that number of connections will remain. pool_size can be set to 0 to indicate no size limit; to disable pooling, use a NullPool instead.
  • max_overflow – The maximum overflow size of the pool. When the number of checked-out connections reaches the size set in pool_size, additional connections will be returned up to this limit. When those additional connections are returned to the pool, they are disconnected and discarded. It follows then that the total number of simultaneous connections the pool will allow is pool_size + max_overflow, and the total number of “sleeping” connections the pool will allow is pool_size. max_overflow can be set to -1 to indicate no overflow limit; no limit will be placed on the total number of concurrent connections. Defaults to 10.
  • timeout – The number of seconds to wait before giving up on returning a connection. Defaults to 30.
  • **kw – Other keyword arguments including Pool.recycle, Pool.echo, Pool.reset_on_return and others are passed to the Pool constructor.
connect()
inherited from the connect() method of Pool

Return a DBAPI connection from the pool.

The connection is instrumented such that when its close() method is called, the connection will be returned to the pool.

unique_connection()
inherited from the unique_connection() method of Pool

Produce a DBAPI connection that is not referenced by any thread-local context.

This method is equivalent to Pool.connect() when the Pool.use_threadlocal flag is not set to True. When Pool.use_threadlocal is True, the Pool.unique_connection() method provides a means of bypassing the threadlocal context.

class sqlalchemy.pool.SingletonThreadPool(creator, pool_size=5, **kw)

Bases: sqlalchemy.pool.Pool

A Pool that maintains one connection per thread.

Maintains one connection per each thread, never moving a connection to a thread other than the one which it was created in.

경고

the SingletonThreadPool will call .close() on arbitrary connections that exist beyond the size setting of pool_size, e.g. if more unique thread identities than what pool_size states are used. This cleanup is non-deterministic and not sensitive to whether or not the connections linked to those thread identities are currently in use.

SingletonThreadPool may be improved in a future release, however in its current status it is generally used only for test scenarios using a SQLite :memory: database and is not recommended for production use.

Options are the same as those of Pool, as well as:

매개 변수:pool_size – The number of threads in which to maintain connections at once. Defaults to five.

SingletonThreadPool is used by the SQLite dialect automatically when a memory-based database is used. See SQLite.

__init__(creator, pool_size=5, **kw)
class sqlalchemy.pool.AssertionPool(*args, **kw)

Bases: sqlalchemy.pool.Pool

A Pool that allows at most one checked out connection at any given time.

This will raise an exception if more than one connection is checked out at a time. Useful for debugging code that is using more connections than desired.

버전 0.7으로 변경: AssertionPool also logs a traceback of where the original connection was checked out, and reports this in the assertion error raised.

class sqlalchemy.pool.NullPool(creator, recycle=-1, echo=None, use_threadlocal=False, logging_name=None, reset_on_return=True, listeners=None, events=None, _dispatch=None, _dialect=None)

Bases: sqlalchemy.pool.Pool

A Pool which does not pool connections.

Instead it literally opens and closes the underlying DB-API connection per each connection open/close.

Reconnect-related functions such as recycle and connection invalidation are not supported by this Pool implementation, since no connections are held persistently.

버전 0.7으로 변경: NullPool is used by the SQlite dialect automatically when a file-based database is used. See SQLite.

class sqlalchemy.pool.StaticPool(creator, recycle=-1, echo=None, use_threadlocal=False, logging_name=None, reset_on_return=True, listeners=None, events=None, _dispatch=None, _dialect=None)

Bases: sqlalchemy.pool.Pool

A Pool of exactly one connection, used for all requests.

Reconnect-related functions such as recycle and connection invalidation (which is also used to support auto-reconnect) are not currently supported by this Pool implementation but may be implemented in a future release.

class sqlalchemy.pool._ConnectionFairy(dbapi_connection, connection_record, echo)

Proxies a DBAPI connection and provides return-on-dereference support.

This is an internal object used by the Pool implementation to provide context management to a DBAPI connection delivered by that Pool.

The name “fairy” is inspired by the fact that the _ConnectionFairy object’s lifespan is transitory, as it lasts only for the length of a specific DBAPI connection being checked out from the pool, and additionally that as a transparent proxy, it is mostly invisible.

더 보기

_ConnectionRecord

_connection_record = None

A reference to the _ConnectionRecord object associated with the DBAPI connection.

This is currently an internal accessor which is subject to change.

connection = None

A reference to the actual DBAPI connection being tracked.

cursor(*args, **kwargs)

Return a new DBAPI cursor for the underlying connection.

This method is a proxy for the connection.cursor() DBAPI method.

detach()

Separate this connection from its Pool.

This means that the connection will no longer be returned to the pool when closed, and will instead be literally closed. The containing ConnectionRecord is separated from the DB-API connection, and will create a new connection when next used.

Note that any overall connection limiting constraints imposed by a Pool implementation may be violated after a detach, as the detached connection is removed from the pool’s knowledge and control.

info

Info dictionary associated with the underlying DBAPI connection referred to by this ConnectionFairy, allowing user-defined data to be associated with the connection.

The data here will follow along with the DBAPI connection including after it is returned to the connection pool and used again in subsequent instances of _ConnectionFairy. It is shared with the _ConnectionRecord.info and Connection.info accessors.

invalidate(e=None, soft=False)

Mark this connection as invalidated.

This method can be called directly, and is also called as a result of the Connection.invalidate() method. When invoked, the DBAPI connection is immediately closed and discarded from further use by the pool. The invalidation mechanism proceeds via the _ConnectionRecord.invalidate() internal method.

매개 변수:
  • e – an exception object indicating a reason for the invalidation.
  • soft

    if True, the connection isn’t closed; instead, this connection will be recycled on next checkout.

    버전 1.0.3에 추가.

is_valid

Return True if this _ConnectionFairy still refers to an active DBAPI connection.

class sqlalchemy.pool._ConnectionRecord(pool)

Internal object which maintains an individual DBAPI connection referenced by a Pool.

The _ConnectionRecord object always exists for any particular DBAPI connection whether or not that DBAPI connection has been “checked out”. This is in contrast to the _ConnectionFairy which is only a public facade to the DBAPI connection while it is checked out.

A _ConnectionRecord may exist for a span longer than that of a single DBAPI connection. For example, if the _ConnectionRecord.invalidate() method is called, the DBAPI connection associated with this _ConnectionRecord will be discarded, but the _ConnectionRecord may be used again, in which case a new DBAPI connection is produced when the Pool next uses this record.

The _ConnectionRecord is delivered along with connection pool events, including PoolEvents.connect() and PoolEvents.checkout(), however _ConnectionRecord still remains an internal object whose API and internals may change.

더 보기

_ConnectionFairy

connection = None

A reference to the actual DBAPI connection being tracked.

May be None if this _ConnectionRecord has been marked as invalidated; a new DBAPI connection may replace it if the owning pool calls upon this _ConnectionRecord to reconnect.

info

The .info dictionary associated with the DBAPI connection.

This dictionary is shared among the _ConnectionFairy.info and Connection.info accessors.

invalidate(e=None, soft=False)

Invalidate the DBAPI connection held by this _ConnectionRecord.

This method is called for all connection invalidations, including when the _ConnectionFairy.invalidate() or Connection.invalidate() methods are called, as well as when any so-called “automatic invalidation” condition occurs.

매개 변수:
  • e – an exception object indicating a reason for the invalidation.
  • soft

    if True, the connection isn’t closed; instead, this connection will be recycled on next checkout.

    버전 1.0.3에 추가.

Pooling Plain DB-API Connections

Any PEP 249 DB-API module can be “proxied” through the connection pool transparently. Usage of the DB-API is exactly as before, except the connect() method will consult the pool. Below we illustrate this with psycopg2:

import sqlalchemy.pool as pool
import psycopg2 as psycopg

psycopg = pool.manage(psycopg)

# then connect normally
connection = psycopg.connect(database='test', username='scott',
                             password='tiger')

This produces a _DBProxy object which supports the same connect() function as the original DB-API module. Upon connection, a connection proxy object is returned, which delegates its calls to a real DB-API connection object. This connection object is stored persistently within a connection pool (an instance of Pool) that corresponds to the exact connection arguments sent to the connect() function.

The connection proxy supports all of the methods on the original connection object, most of which are proxied via __getattr__(). The close() method will return the connection to the pool, and the cursor() method will return a proxied cursor object. Both the connection proxy and the cursor proxy will also return the underlying connection to the pool after they have both been garbage collected, which is detected via weakref callbacks (__del__ is not used).

Additionally, when connections are returned to the pool, a rollback() is issued on the connection unconditionally. This is to release any locks still held by the connection that may have resulted from normal activity.

By default, the connect() method will return the same connection that is already checked out in the current thread. This allows a particular connection to be used in a given thread without needing to pass it around between functions. To disable this behavior, specify use_threadlocal=False to the manage() function.

sqlalchemy.pool.manage(module, **params)

Return a proxy for a DB-API module that automatically pools connections.

Given a DB-API 2.0 module and pool management parameters, returns a proxy for the module that will automatically pool connections, creating new connection pools for each distinct set of connection arguments sent to the decorated module’s connect() function.

매개 변수:
  • module – a DB-API 2.0 database module
  • poolclass – the class used by the pool module to provide pooling. Defaults to QueuePool.
  • **params – will be passed through to poolclass
sqlalchemy.pool.clear_managers()

Remove all current DB-API 2.0 managers.

All pools and connections are disposed.