TornadoSession Asynchronous API

Use a Queries Session asynchronously within the Tornado framework.

The TornadoSession class is optimized for asynchronous concurrency. Each call to TornadoSession.callproc or TornadoSession.query grabs a free connection from the connection pool and requires that the results that are r returned as a Results object are freed via the Results.free method. Doing so will release the free the Results object data and release the lock on the connection so that other queries are able to use the connection.

Example Use

The following RequestHandler example will return a JSON document containing the query results.

import queries
from tornado import gen, web

class ExampleHandler(web.RequestHandler):

    def initialize(self):
        self.session = queries.TornadoSession()

    @gen.coroutine
    def get(self):
        result = yield self.session.query('SELECT * FROM names')
        self.finish({'data': result.items()})
        result.free()

See the Examples for more TornadoSession() examples.

Class Documentation

class queries.tornado_session.TornadoSession(uri='postgresql://localhost:5432', cursor_factory=<class 'psycopg2.extras.RealDictCursor'>, pool_idle_ttl=60, pool_max_size=25, io_loop=None)[source]

Session class for Tornado asynchronous applications. Uses tornado.gen.coroutine() to wrap API methods for use in Tornado.

Utilizes connection pooling to ensure that multiple concurrent asynchronous queries do not block each other. Heavily trafficked services will require a higher max_pool_size to allow for greater connection concurrency.

TornadoSession.query and TornadoSession.callproc must call Results.free

Parameters:
  • uri (str) – PostgreSQL connection URI
  • psycopg2.extensions.cursor – The cursor type to use
  • pool_idle_ttl (int) – How long idle pools keep connections open
  • pool_max_size (int) – The maximum size of the pool to use
backend_pid

Return the backend process ID of the PostgreSQL server that this session is connected to.

Return type:int
callproc(name, args=None)[source]

Call a stored procedure asynchronously on the server, passing in the arguments to be passed to the stored procedure, yielding the results as a Results object.

You must free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections.

Parameters:
  • name (str) – The stored procedure name
  • args (list) – An optional list of procedure arguments
Return type:

Results

Raises:

queries.DataError

Raises:

queries.DatabaseError

Raises:

queries.IntegrityError

Raises:

queries.InternalError

Raises:

queries.InterfaceError

Raises:

queries.NotSupportedError

Raises:

queries.OperationalError

Raises:

queries.ProgrammingError

close()

Explicitly close the connection and remove it from the connection pool if pooling is enabled. If the connection is already closed

Raises:psycopg2.InterfaceError
connection

Do not use this directly with Tornado applications

Returns:
encoding

Return the current client encoding value.

Return type:str
notices

Return a list of up to the last 50 server notices sent to the client.

Return type:list
pid

Return the pool ID used for connection pooling.

Return type:str
query(sql, parameters=None)[source]

Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a Results object.

You must free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections.

Parameters:
  • sql (str) – The SQL statement
  • parameters (dict) – A dictionary of query parameters
Return type:

Results

Raises:

queries.DataError

Raises:

queries.DatabaseError

Raises:

queries.IntegrityError

Raises:

queries.InternalError

Raises:

queries.InterfaceError

Raises:

queries.NotSupportedError

Raises:

queries.OperationalError

Raises:

queries.ProgrammingError

set_encoding(value='UTF8')

Set the client encoding for the session if the value specified is different than the current client encoding.

Parameters:value (str) – The encoding value to use
validate()[source]

Validate the session can connect or has open connections to PostgreSQL. As of 1.10.3

Deprecated since version 1.10.3: As of 1.10.3, this method only warns about Deprecation

Return type:bool
class queries.tornado_session.Results(cursor, cleanup, fd)[source]

A TornadoSession specific queries.Results class that adds the Results.free method. The Results.free method must be called to free the connection that the results were generated on. Results objects that are not freed will cause the connections to remain locked and your application will eventually run out of connections in the pool.

The following examples illustrate the various behaviors that the :queries.Results class implements:

Using Results as an Iterator

results = yield session.query('SELECT * FROM foo')
for row in results
    print row
results.free()

Accessing an individual row by index

results = yield session.query('SELECT * FROM foo')
print results[1]  # Access the second row of the results
results.free()

Casting single row results as a dict

results = yield session.query('SELECT * FROM foo LIMIT 1')
print results.as_dict()
results.free()

Checking to see if a query was successful

sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'"
results = yield session.query(sql)
if results:
    print 'Success'
results.free()

Checking the number of rows by using len(Results)

results = yield session.query('SELECT * FROM foo')
print '%i rows' % len(results)
results.free()
as_dict()[source]

Return a single row result as a dictionary. If the results contain multiple rows, a ValueError will be raised.

Returns:dict
Raises:ValueError
count()[source]

Return the number of rows that were returned from the query

Return type:int
free()[source]

Release the results and connection lock from the TornadoSession object. This must be called after you finish processing the results from TornadoSession.query or TornadoSession.callproc or the connection will not be able to be reused by other asynchronous requests.

items()[source]

Return all of the rows that are in the result set.

Return type:list
query

Return a read-only value of the query that was submitted to PostgreSQL.

Return type:str
rownumber

Return the current offset of the result set

Return type:int
status

Return the status message returned by PostgreSQL after the query was executed.

Return type:str