<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> Connection Pooling — SQLAlchemy 0.8 Documentation </title> <!-- begin iterate through SQLA + sphinx environment css_files --> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/docs.css" type="text/css" /> <link rel="stylesheet" href="../_static/changelog.css" type="text/css" /> <link rel="stylesheet" href="../_static/sphinx_paramlinks.css" type="text/css" /> <!-- end iterate through SQLA + sphinx environment css_files --> <!-- begin layout.mako headers --> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '0.8.7', COLLAPSE_MODINDEX: false, FILE_SUFFIX: '.html' }; </script> <!-- begin iterate through sphinx environment script_files --> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <!-- end iterate through sphinx environment script_files --> <script type="text/javascript" src="../_static/detectmobile.js"></script> <script type="text/javascript" src="../_static/init.js"></script> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="top" title="SQLAlchemy 0.8 Documentation" href="../index.html" /> <link rel="up" title="SQLAlchemy Core" href="index.html" /> <link rel="next" title="Events" href="event.html" /> <link rel="prev" title="Working with Engines and Connections" href="connections.html" /> <!-- end layout.mako headers --> </head> <body> <div id="docs-container"> <div id="docs-top-navigation-container" class="body-background"> <div id="docs-header"> <div id="docs-version-header"> Release: <span class="version-num">0.8.7</span> | Release Date: July 22, 2014 </div> <h1>SQLAlchemy 0.8 Documentation</h1> </div> </div> <div id="docs-body-container"> <div id="fixed-sidebar" class="withsidebar"> <div id="docs-sidebar-popout"> <h3><a href="../index.html">SQLAlchemy 0.8 Documentation</a></h3> <p id="sidebar-paginate"> <a href="index.html" title="SQLAlchemy Core">Up</a> | <a href="connections.html" title="Working with Engines and Connections">Prev</a> | <a href="event.html" title="Events">Next</a> </p> <p id="sidebar-topnav"> <a href="../index.html">Contents</a> | <a href="../genindex.html">Index</a> </p> <div id="sidebar-search"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" size="12" /> <input type="submit" value="Search" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div id="docs-sidebar"> <h3><a href="#"> Connection Pooling </a></h3> <ul> <li><a class="reference internal" href="#">Connection Pooling</a><ul> <li><a class="reference internal" href="#connection-pool-configuration">Connection Pool Configuration</a></li> <li><a class="reference internal" href="#switching-pool-implementations">Switching Pool Implementations</a></li> <li><a class="reference internal" href="#using-a-custom-connection-function">Using a Custom Connection Function</a></li> <li><a class="reference internal" href="#constructing-a-pool">Constructing a Pool</a></li> <li><a class="reference internal" href="#pool-events">Pool Events</a></li> <li><a class="reference internal" href="#dealing-with-disconnects">Dealing with Disconnects</a><ul> <li><a class="reference internal" href="#disconnect-handling-optimistic">Disconnect Handling - Optimistic</a><ul> <li><a class="reference internal" href="#setting-pool-recycle">Setting Pool Recycle</a></li> </ul> </li> <li><a class="reference internal" href="#disconnect-handling-pessimistic">Disconnect Handling - Pessimistic</a></li> </ul> </li> <li><a class="reference internal" href="#api-documentation-available-pool-implementations">API Documentation - Available Pool Implementations</a></li> <li><a class="reference internal" href="#pooling-plain-db-api-connections">Pooling Plain DB-API Connections</a></li> </ul> </li> </ul> </div> </div> <div id="docs-body" class="withsidebar" > <div class="section" id="module-sqlalchemy.pool"> <span id="connection-pooling"></span><span id="pooling-toplevel"></span><h1>Connection Pooling<a class="headerlink" href="#module-sqlalchemy.pool" title="Permalink to this headline">¶</a></h1> <p>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.</p> <p>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.</p> <p>SQLAlchemy includes several connection pool implementations which integrate with the <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a>. They can also be used directly for applications that want to add pooling to an otherwise plain DBAPI approach.</p> <div class="section" id="connection-pool-configuration"> <h2>Connection Pool Configuration<a class="headerlink" href="#connection-pool-configuration" title="Permalink to this headline">¶</a></h2> <p>The <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> returned by the <a class="reference internal" href="engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><tt class="xref py py-func docutils literal"><span class="pre">create_engine()</span></tt></a> function in most cases has a <a class="reference internal" href="#sqlalchemy.pool.QueuePool" title="sqlalchemy.pool.QueuePool"><tt class="xref py py-class docutils literal"><span class="pre">QueuePool</span></tt></a> 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.</p> <p>The most common <a class="reference internal" href="#sqlalchemy.pool.QueuePool" title="sqlalchemy.pool.QueuePool"><tt class="xref py py-class docutils literal"><span class="pre">QueuePool</span></tt></a> tuning parameters can be passed directly to <a class="reference internal" href="engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><tt class="xref py py-func docutils literal"><span class="pre">create_engine()</span></tt></a> as keyword arguments: <tt class="docutils literal"><span class="pre">pool_size</span></tt>, <tt class="docutils literal"><span class="pre">max_overflow</span></tt>, <tt class="docutils literal"><span class="pre">pool_recycle</span></tt> and <tt class="docutils literal"><span class="pre">pool_timeout</span></tt>. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://me@localhost/mydb'</span><span class="p">,</span> <span class="n">pool_size</span><span class="o">=</span><span class="mi">20</span><span class="p">,</span> <span class="n">max_overflow</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span></pre></div> </div> <p>In the case of SQLite, the <a class="reference internal" href="#sqlalchemy.pool.SingletonThreadPool" title="sqlalchemy.pool.SingletonThreadPool"><tt class="xref py py-class docutils literal"><span class="pre">SingletonThreadPool</span></tt></a> or <a class="reference internal" href="#sqlalchemy.pool.NullPool" title="sqlalchemy.pool.NullPool"><tt class="xref py py-class docutils literal"><span class="pre">NullPool</span></tt></a> 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.</p> <p>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 <a class="reference internal" href="engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><tt class="xref py py-func docutils literal"><span class="pre">create_engine()</span></tt></a> to default to using a <a class="reference internal" href="#sqlalchemy.pool.QueuePool" title="sqlalchemy.pool.QueuePool"><tt class="xref py py-class docutils literal"><span class="pre">QueuePool</span></tt></a> 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.</p> </div> <div class="section" id="switching-pool-implementations"> <h2>Switching Pool Implementations<a class="headerlink" href="#switching-pool-implementations" title="Permalink to this headline">¶</a></h2> <p>The usual way to use a different kind of pool with <a class="reference internal" href="engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><tt class="xref py py-func docutils literal"><span class="pre">create_engine()</span></tt></a> is to use the <tt class="docutils literal"><span class="pre">poolclass</span></tt> argument. This argument accepts a class imported from the <tt class="docutils literal"><span class="pre">sqlalchemy.pool</span></tt> module, and handles the details of building the pool for you. Common options include specifying <a class="reference internal" href="#sqlalchemy.pool.QueuePool" title="sqlalchemy.pool.QueuePool"><tt class="xref py py-class docutils literal"><span class="pre">QueuePool</span></tt></a> with SQLite:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.pool</span> <span class="kn">import</span> <span class="n">QueuePool</span> <span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'sqlite:///file.db'</span><span class="p">,</span> <span class="n">poolclass</span><span class="o">=</span><span class="n">QueuePool</span><span class="p">)</span></pre></div> </div> <p>Disabling pooling using <a class="reference internal" href="#sqlalchemy.pool.NullPool" title="sqlalchemy.pool.NullPool"><tt class="xref py py-class docutils literal"><span class="pre">NullPool</span></tt></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.pool</span> <span class="kn">import</span> <span class="n">NullPool</span> <span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span> <span class="s">'postgresql+psycopg2://scott:tiger@localhost/test'</span><span class="p">,</span> <span class="n">poolclass</span><span class="o">=</span><span class="n">NullPool</span><span class="p">)</span></pre></div> </div> </div> <div class="section" id="using-a-custom-connection-function"> <h2>Using a Custom Connection Function<a class="headerlink" href="#using-a-custom-connection-function" title="Permalink to this headline">¶</a></h2> <p>All <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a> classes accept an argument <tt class="docutils literal"><span class="pre">creator</span></tt> which is a callable that creates a new connection. <a class="reference internal" href="engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><tt class="xref py py-func docutils literal"><span class="pre">create_engine()</span></tt></a> accepts this function to pass onto the pool via an argument of the same name:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">sqlalchemy.pool</span> <span class="kn">as</span> <span class="nn">pool</span> <span class="kn">import</span> <span class="nn">psycopg2</span> <span class="k">def</span> <span class="nf">getconn</span><span class="p">():</span> <span class="n">c</span> <span class="o">=</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s">'ed'</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="s">'127.0.0.1'</span><span class="p">,</span> <span class="n">dbname</span><span class="o">=</span><span class="s">'test'</span><span class="p">)</span> <span class="c"># do things with 'c' to set up</span> <span class="k">return</span> <span class="n">c</span> <span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql+psycopg2://'</span><span class="p">,</span> <span class="n">creator</span><span class="o">=</span><span class="n">getconn</span><span class="p">)</span></pre></div> </div> <p>For most “initialize on connection” routines, it’s more convenient to use the <a class="reference internal" href="events.html#sqlalchemy.events.PoolEvents" title="sqlalchemy.events.PoolEvents"><tt class="xref py py-class docutils literal"><span class="pre">PoolEvents</span></tt></a> event hooks, so that the usual URL argument to <a class="reference internal" href="engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><tt class="xref py py-func docutils literal"><span class="pre">create_engine()</span></tt></a> is still usable. <tt class="docutils literal"><span class="pre">creator</span></tt> is there as a last resort for when a DBAPI has some form of <tt class="docutils literal"><span class="pre">connect</span></tt> that is not at all supported by SQLAlchemy.</p> </div> <div class="section" id="constructing-a-pool"> <h2>Constructing a Pool<a class="headerlink" href="#constructing-a-pool" title="Permalink to this headline">¶</a></h2> <p>To use a <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a> by itself, the <tt class="docutils literal"><span class="pre">creator</span></tt> function is the only argument that’s required and is passed first, followed by any additional options:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">sqlalchemy.pool</span> <span class="kn">as</span> <span class="nn">pool</span> <span class="kn">import</span> <span class="nn">psycopg2</span> <span class="k">def</span> <span class="nf">getconn</span><span class="p">():</span> <span class="n">c</span> <span class="o">=</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s">'ed'</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="s">'127.0.0.1'</span><span class="p">,</span> <span class="n">dbname</span><span class="o">=</span><span class="s">'test'</span><span class="p">)</span> <span class="k">return</span> <span class="n">c</span> <span class="n">mypool</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">QueuePool</span><span class="p">(</span><span class="n">getconn</span><span class="p">,</span> <span class="n">max_overflow</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span> <span class="n">pool_size</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span></pre></div> </div> <p>DBAPI connections can then be procured from the pool using the <a class="reference internal" href="#sqlalchemy.pool.Pool.connect" title="sqlalchemy.pool.Pool.connect"><tt class="xref py py-meth docutils literal"><span class="pre">Pool.connect()</span></tt></a> function. The return value of this method is a DBAPI connection that’s contained within a transparent proxy:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># get a connection</span> <span class="n">conn</span> <span class="o">=</span> <span class="n">mypool</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span> <span class="c"># use it</span> <span class="n">cursor</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span> <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"select foo"</span><span class="p">)</span></pre></div> </div> <p>The purpose of the transparent proxy is to intercept the <tt class="docutils literal"><span class="pre">close()</span></tt> call, such that instead of the DBAPI connection being closed, it is returned to the pool:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># "close" the connection. Returns</span> <span class="c"># it to the pool.</span> <span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></pre></div> </div> <p>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).</p> <p>The <tt class="docutils literal"><span class="pre">close()</span></tt> step also performs the important step of calling the <tt class="docutils literal"><span class="pre">rollback()</span></tt> 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 <tt class="docutils literal"><span class="pre">reset_on_return</span></tt> option of <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a>.</p> <p>A particular pre-created <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a> can be shared with one or more engines by passing it to the <tt class="docutils literal"><span class="pre">pool</span></tt> argument of <a class="reference internal" href="engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><tt class="xref py py-func docutils literal"><span class="pre">create_engine()</span></tt></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">e</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">'postgresql://'</span><span class="p">,</span> <span class="n">pool</span><span class="o">=</span><span class="n">mypool</span><span class="p">)</span></pre></div> </div> </div> <div class="section" id="pool-events"> <h2>Pool Events<a class="headerlink" href="#pool-events" title="Permalink to this headline">¶</a></h2> <p>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 <a class="reference internal" href="events.html#sqlalchemy.events.PoolEvents" title="sqlalchemy.events.PoolEvents"><tt class="xref py py-class docutils literal"><span class="pre">PoolEvents</span></tt></a> for details.</p> </div> <div class="section" id="dealing-with-disconnects"> <h2>Dealing with Disconnects<a class="headerlink" href="#dealing-with-disconnects" title="Permalink to this headline">¶</a></h2> <p>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.</p> <div class="section" id="disconnect-handling-optimistic"> <h3>Disconnect Handling - Optimistic<a class="headerlink" href="#disconnect-handling-optimistic" title="Permalink to this headline">¶</a></h3> <p>The most common approach is to let SQLAlchemy handle disconnects as they occur, at which point the pool is refreshed. This assumes the <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a> is used in conjunction with a <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a>. The <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> has logic which can detect disconnection events and refresh the pool automatically.</p> <p>When the <a class="reference internal" href="connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> attempts to use a DBAPI connection, and an exception is raised that corresponds to a “disconnect” event, the connection is invalidated. The <a class="reference internal" href="connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> then calls the <a class="reference internal" href="#sqlalchemy.pool.Pool.recreate" title="sqlalchemy.pool.Pool.recreate"><tt class="xref py py-meth docutils literal"><span class="pre">Pool.recreate()</span></tt></a> method, effectively invalidating all connections not currently checked out so that they are replaced with new ones upon next checkout:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">create_engine</span><span class="p">,</span> <span class="n">exc</span> <span class="n">e</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="o">...</span><span class="p">)</span> <span class="n">c</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span> <span class="k">try</span><span class="p">:</span> <span class="c"># suppose the database has been restarted.</span> <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"SELECT * FROM table"</span><span class="p">)</span> <span class="n">c</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="k">except</span> <span class="n">exc</span><span class="o">.</span><span class="n">DBAPIError</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span> <span class="c"># an exception is raised, Connection is invalidated.</span> <span class="k">if</span> <span class="n">e</span><span class="o">.</span><span class="n">connection_invalidated</span><span class="p">:</span> <span class="k">print</span> <span class="s">"Connection was invalidated!"</span> <span class="c"># after the invalidate event, a new connection</span> <span class="c"># starts with a new Pool</span> <span class="n">c</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span> <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"SELECT * FROM table"</span><span class="p">)</span></pre></div> </div> <p>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.</p> <div class="section" id="setting-pool-recycle"> <h4>Setting Pool Recycle<a class="headerlink" href="#setting-pool-recycle" title="Permalink to this headline">¶</a></h4> <p>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:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">create_engine</span> <span class="n">e</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">"mysql://scott:tiger@localhost/test"</span><span class="p">,</span> <span class="n">pool_recycle</span><span class="o">=</span><span class="mi">3600</span><span class="p">)</span></pre></div> </div> <p>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 <strong>only</strong> occurs during checkout - not on any connections that are held in a checked out state. <tt class="docutils literal"><span class="pre">pool_recycle</span></tt> is a function of the <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a> itself, independent of whether or not an <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> is in use.</p> </div> </div> <div class="section" id="disconnect-handling-pessimistic"> <h3>Disconnect Handling - Pessimistic<a class="headerlink" href="#disconnect-handling-pessimistic" title="Permalink to this headline">¶</a></h3> <p>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:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">exc</span> <span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">event</span> <span class="kn">from</span> <span class="nn">sqlalchemy.pool</span> <span class="kn">import</span> <span class="n">Pool</span> <span class="nd">@event.listens_for</span><span class="p">(</span><span class="n">Pool</span><span class="p">,</span> <span class="s">"checkout"</span><span class="p">)</span> <span class="k">def</span> <span class="nf">ping_connection</span><span class="p">(</span><span class="n">dbapi_connection</span><span class="p">,</span> <span class="n">connection_record</span><span class="p">,</span> <span class="n">connection_proxy</span><span class="p">):</span> <span class="n">cursor</span> <span class="o">=</span> <span class="n">dbapi_connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span> <span class="k">try</span><span class="p">:</span> <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"SELECT 1"</span><span class="p">)</span> <span class="k">except</span><span class="p">:</span> <span class="c"># optional - dispose the whole pool</span> <span class="c"># instead of invalidating one at a time</span> <span class="c"># connection_proxy._pool.dispose()</span> <span class="c"># raise DisconnectionError - pool will try</span> <span class="c"># connecting again up to three times before raising.</span> <span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">DisconnectionError</span><span class="p">()</span> <span class="n">cursor</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></pre></div> </div> <p>Above, the <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a> object specifically catches <a class="reference internal" href="exceptions.html#sqlalchemy.exc.DisconnectionError" title="sqlalchemy.exc.DisconnectionError"><tt class="xref py py-class docutils literal"><span class="pre">DisconnectionError</span></tt></a> and attempts to create a new DBAPI connection, up to three times, before giving up and then raising <a class="reference internal" href="exceptions.html#sqlalchemy.exc.InvalidRequestError" title="sqlalchemy.exc.InvalidRequestError"><tt class="xref py py-class docutils literal"><span class="pre">InvalidRequestError</span></tt></a>, failing the connection. This recipe will ensure that a new <a class="reference internal" href="connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> will succeed even if connections in the pool have gone stale, provided that the database server is actually running. The expense is that of an additional execution performed per checkout. When using the ORM <a class="reference internal" href="../orm/session.html#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a>, there is one connection checkout per transaction, so the expense is fairly low. The ping approach above also works with straight connection pool usage, that is, even if no <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> were involved.</p> <p>The event handler can be tested using a script like the following, restarting the database server at the point at which the script pauses for input:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">create_engine</span> <span class="n">e</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">"mysql://scott:tiger@localhost/test"</span><span class="p">,</span> <span class="n">echo_pool</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">c1</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span> <span class="n">c2</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span> <span class="n">c3</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span> <span class="n">c1</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="n">c2</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="n">c3</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="c"># pool size is now three.</span> <span class="k">print</span> <span class="s">"Restart the server"</span> <span class="nb">raw_input</span><span class="p">()</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span> <span class="n">c</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span> <span class="k">print</span> <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"select 1"</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span> <span class="n">c</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></pre></div> </div> </div> </div> <div class="section" id="api-documentation-available-pool-implementations"> <h2>API Documentation - Available Pool Implementations<a class="headerlink" href="#api-documentation-available-pool-implementations" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="sqlalchemy.pool.Pool"> <em class="property">class </em><tt class="descclassname">sqlalchemy.pool.</tt><tt class="descname">Pool</tt><big>(</big><em>creator</em>, <em>recycle=-1</em>, <em>echo=None</em>, <em>use_threadlocal=False</em>, <em>logging_name=None</em>, <em>reset_on_return=True</em>, <em>listeners=None</em>, <em>events=None</em>, <em>_dispatch=None</em>, <em>_dialect=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.pool.Pool" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.log.Identified</span></tt></p> <p>Abstract base class for connection pools.</p> <dl class="method"> <dt id="sqlalchemy.pool.Pool.__init__"> <tt class="descname">__init__</tt><big>(</big><em>creator</em>, <em>recycle=-1</em>, <em>echo=None</em>, <em>use_threadlocal=False</em>, <em>logging_name=None</em>, <em>reset_on_return=True</em>, <em>listeners=None</em>, <em>events=None</em>, <em>_dispatch=None</em>, <em>_dialect=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.pool.Pool.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Construct a Pool.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.pool.Pool.params.creator"></span><strong>creator</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.Pool.params.creator">¶</a> – a callable function that returns a DB-API connection object. The function will be called with parameters.</li> <li><span class="target" id="sqlalchemy.pool.Pool.params.recycle"></span><strong>recycle</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.Pool.params.recycle">¶</a> – 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.</li> <li><span class="target" id="sqlalchemy.pool.Pool.params.logging_name"></span><strong>logging_name</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.Pool.params.logging_name">¶</a> – 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.</li> <li><span class="target" id="sqlalchemy.pool.Pool.params.echo"></span><strong>echo</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.Pool.params.echo">¶</a> – 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.</li> <li><span class="target" id="sqlalchemy.pool.Pool.params.use_threadlocal"></span><strong>use_threadlocal</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.Pool.params.use_threadlocal">¶</a> – <p>If set to True, repeated calls to <a class="reference internal" href="#sqlalchemy.pool.Pool.connect" title="sqlalchemy.pool.Pool.connect"><tt class="xref py py-meth docutils literal"><span class="pre">connect()</span></tt></a> 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 <a class="reference internal" href="#sqlalchemy.pool.Pool.unique_connection" title="sqlalchemy.pool.Pool.unique_connection"><tt class="xref py py-meth docutils literal"><span class="pre">Pool.unique_connection()</span></tt></a> method is provided to return a consistenty unique connection to bypass this behavior when the flag is set.</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p>The <a class="reference internal" href="#sqlalchemy.pool.Pool.params.use_threadlocal" title="sqlalchemy.pool.Pool"><tt class="xref py py-paramref docutils literal"><span class="pre">Pool.use_threadlocal</span></tt></a> flag <strong>does not affect the behavior</strong> of <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine.connect" title="sqlalchemy.engine.Engine.connect"><tt class="xref py py-meth docutils literal"><span class="pre">Engine.connect()</span></tt></a>. <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine.connect" title="sqlalchemy.engine.Engine.connect"><tt class="xref py py-meth docutils literal"><span class="pre">Engine.connect()</span></tt></a> makes use of the <a class="reference internal" href="#sqlalchemy.pool.Pool.unique_connection" title="sqlalchemy.pool.Pool.unique_connection"><tt class="xref py py-meth docutils literal"><span class="pre">Pool.unique_connection()</span></tt></a> method which <strong>does not use thread local context</strong>. To produce a <a class="reference internal" href="connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> which refers to the <a class="reference internal" href="#sqlalchemy.pool.Pool.connect" title="sqlalchemy.pool.Pool.connect"><tt class="xref py py-meth docutils literal"><span class="pre">Pool.connect()</span></tt></a> method, use <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine.contextual_connect" title="sqlalchemy.engine.Engine.contextual_connect"><tt class="xref py py-meth docutils literal"><span class="pre">Engine.contextual_connect()</span></tt></a>.</p> <p class="last">Note that other SQLAlchemy connectivity systems such as <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine.execute" title="sqlalchemy.engine.Engine.execute"><tt class="xref py py-meth docutils literal"><span class="pre">Engine.execute()</span></tt></a> as well as the orm <a class="reference internal" href="../orm/session.html#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><tt class="xref py py-class docutils literal"><span class="pre">Session</span></tt></a> make use of <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine.contextual_connect" title="sqlalchemy.engine.Engine.contextual_connect"><tt class="xref py py-meth docutils literal"><span class="pre">Engine.contextual_connect()</span></tt></a> internally, so these functions are compatible with the <a class="reference internal" href="#sqlalchemy.pool.Pool.params.use_threadlocal" title="sqlalchemy.pool.Pool"><tt class="xref py py-paramref docutils literal"><span class="pre">Pool.use_threadlocal</span></tt></a> setting.</p> </div> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="connections.html#threadlocal-strategy"><em>Using the Threadlocal Execution Strategy</em></a> - contains detail on the “threadlocal” engine strategy, which provides a more comprehensive approach to “threadlocal” connectivity for the specific use case of using <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> and <a class="reference internal" href="connections.html#sqlalchemy.engine.Connection" title="sqlalchemy.engine.Connection"><tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt></a> objects directly.</p> </div> </li> <li><span class="target" id="sqlalchemy.pool.Pool.params.reset_on_return"></span><strong>reset_on_return</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.Pool.params.reset_on_return">¶</a> – <p>Determine steps to take on connections as they are returned to the pool. reset_on_return can have any of these values:</p> <ul> <li><tt class="docutils literal"><span class="pre">"rollback"</span></tt> - 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.</li> <li><tt class="docutils literal"><span class="pre">True</span></tt> - same as ‘rollback’, this is here for backwards compatibility.</li> <li><tt class="docutils literal"><span class="pre">"commit"</span></tt> - 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.</li> <li><tt class="docutils literal"><span class="pre">None</span></tt> - 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 <strong>never be selected</strong> for a database that supports transactions, as it will lead to deadlocks and stale state.</li> <li><tt class="docutils literal"><span class="pre">False</span></tt> - same as None, this is here for backwards compatibility.</li> </ul> <div class="versionchanged"> <p><span>Changed in version 0.7.6: </span><a class="reference internal" href="#sqlalchemy.pool.Pool.params.reset_on_return" title="sqlalchemy.pool.Pool"><tt class="xref py py-paramref docutils literal"><span class="pre">Pool.reset_on_return</span></tt></a> accepts <tt class="docutils literal"><span class="pre">"rollback"</span></tt> and <tt class="docutils literal"><span class="pre">"commit"</span></tt> arguments.</p> </div> </li> <li><span class="target" id="sqlalchemy.pool.Pool.params.events"></span><strong>events</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.Pool.params.events">¶</a> – a list of 2-tuples, each of the form <tt class="docutils literal"><span class="pre">(callable,</span> <span class="pre">target)</span></tt> which will be passed to <a class="reference internal" href="event.html#sqlalchemy.event.listen" title="sqlalchemy.event.listen"><tt class="xref py py-func docutils literal"><span class="pre">event.listen()</span></tt></a> upon construction. Provided here so that event listeners can be assigned via <a class="reference internal" href="engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><tt class="xref py py-func docutils literal"><span class="pre">create_engine()</span></tt></a> before dialect-level listeners are applied.</li> <li><span class="target" id="sqlalchemy.pool.Pool.params.listeners"></span><strong>listeners</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.Pool.params.listeners">¶</a> – Deprecated. A list of <a class="reference internal" href="interfaces.html#sqlalchemy.interfaces.PoolListener" title="sqlalchemy.interfaces.PoolListener"><tt class="xref py py-class docutils literal"><span class="pre">PoolListener</span></tt></a>-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 <a class="reference internal" href="event.html#sqlalchemy.event.listen" title="sqlalchemy.event.listen"><tt class="xref py py-func docutils literal"><span class="pre">listen()</span></tt></a>.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="sqlalchemy.pool.Pool.connect"> <tt class="descname">connect</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.pool.Pool.connect" title="Permalink to this definition">¶</a></dt> <dd><p>Return a DBAPI connection from the pool.</p> <p>The connection is instrumented such that when its <tt class="docutils literal"><span class="pre">close()</span></tt> method is called, the connection will be returned to the pool.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.pool.Pool.dispose"> <tt class="descname">dispose</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.pool.Pool.dispose" title="Permalink to this definition">¶</a></dt> <dd><p>Dispose of this pool.</p> <p>This method leaves the possibility of checked-out connections remaining open, as it only affects connections that are idle in the pool.</p> <p>See also the <a class="reference internal" href="#sqlalchemy.pool.Pool.recreate" title="sqlalchemy.pool.Pool.recreate"><tt class="xref py py-meth docutils literal"><span class="pre">Pool.recreate()</span></tt></a> method.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.pool.Pool.recreate"> <tt class="descname">recreate</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.pool.Pool.recreate" title="Permalink to this definition">¶</a></dt> <dd><p>Return a new <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a>, of the same class as this one and configured with identical creation arguments.</p> <p>This method is used in conjunection with <a class="reference internal" href="#sqlalchemy.pool.Pool.dispose" title="sqlalchemy.pool.Pool.dispose"><tt class="xref py py-meth docutils literal"><span class="pre">dispose()</span></tt></a> to close out an entire <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a> and create a new one in its place.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.pool.Pool.unique_connection"> <tt class="descname">unique_connection</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.pool.Pool.unique_connection" title="Permalink to this definition">¶</a></dt> <dd><p>Produce a DBAPI connection that is not referenced by any thread-local context.</p> <p>This method is equivalent to <a class="reference internal" href="#sqlalchemy.pool.Pool.connect" title="sqlalchemy.pool.Pool.connect"><tt class="xref py py-meth docutils literal"><span class="pre">Pool.connect()</span></tt></a> when the <a class="reference internal" href="#sqlalchemy.pool.Pool.params.use_threadlocal" title="sqlalchemy.pool.Pool"><tt class="xref py py-paramref docutils literal"><span class="pre">Pool.use_threadlocal</span></tt></a> flag is not set to True. When <a class="reference internal" href="#sqlalchemy.pool.Pool.params.use_threadlocal" title="sqlalchemy.pool.Pool"><tt class="xref py py-paramref docutils literal"><span class="pre">Pool.use_threadlocal</span></tt></a> is True, the <a class="reference internal" href="#sqlalchemy.pool.Pool.unique_connection" title="sqlalchemy.pool.Pool.unique_connection"><tt class="xref py py-meth docutils literal"><span class="pre">Pool.unique_connection()</span></tt></a> method provides a means of bypassing the threadlocal context.</p> </dd></dl> </dd></dl> <dl class="class"> <dt id="sqlalchemy.pool.QueuePool"> <em class="property">class </em><tt class="descclassname">sqlalchemy.pool.</tt><tt class="descname">QueuePool</tt><big>(</big><em>creator</em>, <em>pool_size=5</em>, <em>max_overflow=10</em>, <em>timeout=30</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.pool.QueuePool" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.pool.Pool</span></tt></a></p> <p>A <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a> that imposes a limit on the number of open connections.</p> <p><a class="reference internal" href="#sqlalchemy.pool.QueuePool" title="sqlalchemy.pool.QueuePool"><tt class="xref py py-class docutils literal"><span class="pre">QueuePool</span></tt></a> is the default pooling implementation used for all <a class="reference internal" href="connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><tt class="xref py py-class docutils literal"><span class="pre">Engine</span></tt></a> objects, unless the SQLite dialect is in use.</p> <dl class="method"> <dt id="sqlalchemy.pool.QueuePool.__init__"> <tt class="descname">__init__</tt><big>(</big><em>creator</em>, <em>pool_size=5</em>, <em>max_overflow=10</em>, <em>timeout=30</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.pool.QueuePool.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Construct a QueuePool.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.pool.QueuePool.params.creator"></span><strong>creator</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.QueuePool.params.creator">¶</a> – a callable function that returns a DB-API connection object, same as that of <a class="reference internal" href="#sqlalchemy.pool.Pool.params.creator" title="sqlalchemy.pool.Pool"><tt class="xref py py-paramref docutils literal"><span class="pre">Pool.creator</span></tt></a>.</li> <li><span class="target" id="sqlalchemy.pool.QueuePool.params.pool_size"></span><strong>pool_size</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.QueuePool.params.pool_size">¶</a> – 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. <tt class="docutils literal"><span class="pre">pool_size</span></tt> can be set to 0 to indicate no size limit; to disable pooling, use a <a class="reference internal" href="#sqlalchemy.pool.NullPool" title="sqlalchemy.pool.NullPool"><tt class="xref py py-class docutils literal"><span class="pre">NullPool</span></tt></a> instead.</li> <li><span class="target" id="sqlalchemy.pool.QueuePool.params.max_overflow"></span><strong>max_overflow</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.QueuePool.params.max_overflow">¶</a> – 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 + <cite>max_overflow</cite>, and the total number of “sleeping” connections the pool will allow is pool_size. <cite>max_overflow</cite> 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.</li> <li><span class="target" id="sqlalchemy.pool.QueuePool.params.timeout"></span><strong>timeout</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.QueuePool.params.timeout">¶</a> – The number of seconds to wait before giving up on returning a connection. Defaults to 30.</li> <li><span class="target" id="sqlalchemy.pool.QueuePool.params.**kw"></span><strong>**kw</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.QueuePool.params.**kw">¶</a> – Other keyword arguments including <a class="reference internal" href="#sqlalchemy.pool.Pool.params.recycle" title="sqlalchemy.pool.Pool"><tt class="xref py py-paramref docutils literal"><span class="pre">Pool.recycle</span></tt></a>, <a class="reference internal" href="#sqlalchemy.pool.Pool.params.echo" title="sqlalchemy.pool.Pool"><tt class="xref py py-paramref docutils literal"><span class="pre">Pool.echo</span></tt></a>, <a class="reference internal" href="#sqlalchemy.pool.Pool.params.reset_on_return" title="sqlalchemy.pool.Pool"><tt class="xref py py-paramref docutils literal"><span class="pre">Pool.reset_on_return</span></tt></a> and others are passed to the <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a> constructor.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="sqlalchemy.pool.QueuePool.connect"> <tt class="descname">connect</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.pool.QueuePool.connect" title="Permalink to this definition">¶</a></dt> <dd><p>Return a DBAPI connection from the pool.</p> <p>The connection is instrumented such that when its <tt class="docutils literal"><span class="pre">close()</span></tt> method is called, the connection will be returned to the pool.</p> </dd></dl> <dl class="method"> <dt id="sqlalchemy.pool.QueuePool.unique_connection"> <tt class="descname">unique_connection</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.pool.QueuePool.unique_connection" title="Permalink to this definition">¶</a></dt> <dd><p>Produce a DBAPI connection that is not referenced by any thread-local context.</p> <p>This method is equivalent to <a class="reference internal" href="#sqlalchemy.pool.Pool.connect" title="sqlalchemy.pool.Pool.connect"><tt class="xref py py-meth docutils literal"><span class="pre">Pool.connect()</span></tt></a> when the <a class="reference internal" href="#sqlalchemy.pool.Pool.params.use_threadlocal" title="sqlalchemy.pool.Pool"><tt class="xref py py-paramref docutils literal"><span class="pre">Pool.use_threadlocal</span></tt></a> flag is not set to True. When <a class="reference internal" href="#sqlalchemy.pool.Pool.params.use_threadlocal" title="sqlalchemy.pool.Pool"><tt class="xref py py-paramref docutils literal"><span class="pre">Pool.use_threadlocal</span></tt></a> is True, the <a class="reference internal" href="#sqlalchemy.pool.Pool.unique_connection" title="sqlalchemy.pool.Pool.unique_connection"><tt class="xref py py-meth docutils literal"><span class="pre">Pool.unique_connection()</span></tt></a> method provides a means of bypassing the threadlocal context.</p> </dd></dl> </dd></dl> <dl class="class"> <dt id="sqlalchemy.pool.SingletonThreadPool"> <em class="property">class </em><tt class="descclassname">sqlalchemy.pool.</tt><tt class="descname">SingletonThreadPool</tt><big>(</big><em>creator</em>, <em>pool_size=5</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.pool.SingletonThreadPool" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.pool.Pool</span></tt></a></p> <p>A Pool that maintains one connection per thread.</p> <p>Maintains one connection per each thread, never moving a connection to a thread other than the one which it was created in.</p> <p>Options are the same as those of <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a>, as well as:</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><span class="target" id="sqlalchemy.pool.SingletonThreadPool.params.pool_size"></span><strong>pool_size</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.SingletonThreadPool.params.pool_size">¶</a> – The number of threads in which to maintain connections at once. Defaults to five.</td> </tr> </tbody> </table> <p><a class="reference internal" href="#sqlalchemy.pool.SingletonThreadPool" title="sqlalchemy.pool.SingletonThreadPool"><tt class="xref py py-class docutils literal"><span class="pre">SingletonThreadPool</span></tt></a> is used by the SQLite dialect automatically when a memory-based database is used. See <a class="reference internal" href="../dialects/sqlite.html"><em>SQLite</em></a>.</p> <dl class="method"> <dt id="sqlalchemy.pool.SingletonThreadPool.__init__"> <tt class="descname">__init__</tt><big>(</big><em>creator</em>, <em>pool_size=5</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.pool.SingletonThreadPool.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> <dl class="class"> <dt id="sqlalchemy.pool.AssertionPool"> <em class="property">class </em><tt class="descclassname">sqlalchemy.pool.</tt><tt class="descname">AssertionPool</tt><big>(</big><em>*args</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#sqlalchemy.pool.AssertionPool" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.pool.Pool</span></tt></a></p> <p>A <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a> that allows at most one checked out connection at any given time.</p> <p>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.</p> <div class="versionchanged"> <p><span>Changed in version 0.7: </span><a class="reference internal" href="#sqlalchemy.pool.AssertionPool" title="sqlalchemy.pool.AssertionPool"><tt class="xref py py-class docutils literal"><span class="pre">AssertionPool</span></tt></a> also logs a traceback of where the original connection was checked out, and reports this in the assertion error raised.</p> </div> </dd></dl> <dl class="class"> <dt id="sqlalchemy.pool.NullPool"> <em class="property">class </em><tt class="descclassname">sqlalchemy.pool.</tt><tt class="descname">NullPool</tt><big>(</big><em>creator</em>, <em>recycle=-1</em>, <em>echo=None</em>, <em>use_threadlocal=False</em>, <em>logging_name=None</em>, <em>reset_on_return=True</em>, <em>listeners=None</em>, <em>events=None</em>, <em>_dispatch=None</em>, <em>_dialect=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.pool.NullPool" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.pool.Pool</span></tt></a></p> <p>A Pool which does not pool connections.</p> <p>Instead it literally opens and closes the underlying DB-API connection per each connection open/close.</p> <p>Reconnect-related functions such as <tt class="docutils literal"><span class="pre">recycle</span></tt> and connection invalidation are not supported by this Pool implementation, since no connections are held persistently.</p> <div class="versionchanged"> <p><span>Changed in version 0.7: </span><a class="reference internal" href="#sqlalchemy.pool.NullPool" title="sqlalchemy.pool.NullPool"><tt class="xref py py-class docutils literal"><span class="pre">NullPool</span></tt></a> is used by the SQlite dialect automatically when a file-based database is used. See <a class="reference internal" href="../dialects/sqlite.html"><em>SQLite</em></a>.</p> </div> </dd></dl> <dl class="class"> <dt id="sqlalchemy.pool.StaticPool"> <em class="property">class </em><tt class="descclassname">sqlalchemy.pool.</tt><tt class="descname">StaticPool</tt><big>(</big><em>creator</em>, <em>recycle=-1</em>, <em>echo=None</em>, <em>use_threadlocal=False</em>, <em>logging_name=None</em>, <em>reset_on_return=True</em>, <em>listeners=None</em>, <em>events=None</em>, <em>_dispatch=None</em>, <em>_dialect=None</em><big>)</big><a class="headerlink" href="#sqlalchemy.pool.StaticPool" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">sqlalchemy.pool.Pool</span></tt></a></p> <p>A Pool of exactly one connection, used for all requests.</p> <p>Reconnect-related functions such as <tt class="docutils literal"><span class="pre">recycle</span></tt> 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.</p> </dd></dl> </div> <div class="section" id="pooling-plain-db-api-connections"> <h2>Pooling Plain DB-API Connections<a class="headerlink" href="#pooling-plain-db-api-connections" title="Permalink to this headline">¶</a></h2> <p>Any <span class="target" id="index-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a> DB-API module can be “proxied” through the connection pool transparently. Usage of the DB-API is exactly as before, except the <tt class="docutils literal"><span class="pre">connect()</span></tt> method will consult the pool. Below we illustrate this with <tt class="docutils literal"><span class="pre">psycopg2</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">sqlalchemy.pool</span> <span class="kn">as</span> <span class="nn">pool</span> <span class="kn">import</span> <span class="nn">psycopg2</span> <span class="kn">as</span> <span class="nn">psycopg</span> <span class="n">psycopg</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">manage</span><span class="p">(</span><span class="n">psycopg</span><span class="p">)</span> <span class="c"># then connect normally</span> <span class="n">connection</span> <span class="o">=</span> <span class="n">psycopg</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">database</span><span class="o">=</span><span class="s">'test'</span><span class="p">,</span> <span class="n">username</span><span class="o">=</span><span class="s">'scott'</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">'tiger'</span><span class="p">)</span></pre></div> </div> <p>This produces a <tt class="xref py py-class docutils literal"><span class="pre">_DBProxy</span></tt> object which supports the same <tt class="docutils literal"><span class="pre">connect()</span></tt> 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 <a class="reference internal" href="#sqlalchemy.pool.Pool" title="sqlalchemy.pool.Pool"><tt class="xref py py-class docutils literal"><span class="pre">Pool</span></tt></a>) that corresponds to the exact connection arguments sent to the <tt class="docutils literal"><span class="pre">connect()</span></tt> function.</p> <p>The connection proxy supports all of the methods on the original connection object, most of which are proxied via <tt class="docutils literal"><span class="pre">__getattr__()</span></tt>. The <tt class="docutils literal"><span class="pre">close()</span></tt> method will return the connection to the pool, and the <tt class="docutils literal"><span class="pre">cursor()</span></tt> 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 (<tt class="docutils literal"><span class="pre">__del__</span></tt> is not used).</p> <p>Additionally, when connections are returned to the pool, a <tt class="docutils literal"><span class="pre">rollback()</span></tt> is issued on the connection unconditionally. This is to release any locks still held by the connection that may have resulted from normal activity.</p> <p>By default, the <tt class="docutils literal"><span class="pre">connect()</span></tt> 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 <tt class="docutils literal"><span class="pre">use_threadlocal=False</span></tt> to the <tt class="docutils literal"><span class="pre">manage()</span></tt> function.</p> <dl class="function"> <dt id="sqlalchemy.pool.manage"> <tt class="descclassname">sqlalchemy.pool.</tt><tt class="descname">manage</tt><big>(</big><em>module</em>, <em>**params</em><big>)</big><a class="headerlink" href="#sqlalchemy.pool.manage" title="Permalink to this definition">¶</a></dt> <dd><p>Return a proxy for a DB-API module that automatically pools connections.</p> <p>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.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.pool.manage.params.module"></span><strong>module</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.manage.params.module">¶</a> – a DB-API 2.0 database module</li> <li><span class="target" id="sqlalchemy.pool.manage.params.poolclass"></span><strong>poolclass</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.manage.params.poolclass">¶</a> – the class used by the pool module to provide pooling. Defaults to <a class="reference internal" href="#sqlalchemy.pool.QueuePool" title="sqlalchemy.pool.QueuePool"><tt class="xref py py-class docutils literal"><span class="pre">QueuePool</span></tt></a>.</li> <li><span class="target" id="sqlalchemy.pool.manage.params.**params"></span><strong>**params</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.pool.manage.params.**params">¶</a> – will be passed through to <em>poolclass</em></li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="function"> <dt id="sqlalchemy.pool.clear_managers"> <tt class="descclassname">sqlalchemy.pool.</tt><tt class="descname">clear_managers</tt><big>(</big><big>)</big><a class="headerlink" href="#sqlalchemy.pool.clear_managers" title="Permalink to this definition">¶</a></dt> <dd><p>Remove all current DB-API 2.0 managers.</p> <p>All pools and connections are disposed.</p> </dd></dl> </div> </div> </div> </div> <div id="docs-bottom-navigation" class="docs-navigation-links"> Previous: <a href="connections.html" title="previous chapter">Working with Engines and Connections</a> Next: <a href="event.html" title="next chapter">Events</a> <div id="docs-copyright"> © <a href="../copyright.html">Copyright</a> 2007-2014, the SQLAlchemy authors and contributors. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2b1. </div> </div> </div> </body> </html>