Package: queries
Queriesis a BSD licensed opinionated wrapper of thepsycopg2library for
interacting with PostgreSQL.The popularpsycopg2package is a full-featured python client. Unfortunately
as a developer, you’re often repeating the same steps to get started with your
applications that use it. Queries aims to reduce the complexity of psycopg2
while adding additional features to make writing PostgreSQL client applications
both fast and easy. Check out theUsagesection below to see how easy it can be.Key features include:Simplified APISupport of Python 2.7+ and 3.4+PyPy support viapsycopg2cffiAsynchronous support forTornadoConnection information provided by URIQuery results delivered as a generator based iteratorsAutomatically registered data-type support for UUIDs, Unicode and Unicode ArraysAbility to directly access psycopg2connectionandcursorobjectsInternal connection poolingDocumentationDocumentation is available athttps://queries.readthedocs.orgInstallationQueries is available viapypiand can be installed with easy_install or pip:pipinstallqueriesUsageQueries provides a session based API for interacting with PostgreSQL.
Simply pass in theURIof the PostgreSQL server to connect to when creating
a session:session=queries.Session("postgresql://postgres@localhost:5432/postgres")Queries built-in connection pooling will re-use connections when possible,
lowering the overhead of connecting and reconnecting.When specifying a URI, if you omit the username and database name to connect
with, Queries will use the current OS username for both. You can also omit the
URI when connecting to connect to localhost on port 5432 as the current OS user,
connecting to a database named for the current user. For example, if your
username isfredand you omit the URI when issuingqueries.querythe URI
that is constructed would bepostgresql://fred@localhost:5432/fred.If you’d rather use individual values for the connection, the queries.uri()
method provides a quick and easy way to create a URI to pass into the various
methods.>>>queries.uri("server-name",5432,"dbname","user","pass")'postgresql://user:pass@server-name:5432/dbname'Environment VariablesCurrently Queries uses the following environment variables for tweaking various
configuration values.  The supported ones are:QUERIES_MAX_POOL_SIZE- Modify the maximum size of the connection pool (default: 1)Using the queries.Session classTo execute queries or call stored procedures, you start by creating an instance of thequeries.Sessionclass. It can act as a context manager, meaning you can
use it with thewithkeyword and it will take care of cleaning up after itself. For
more information on thewithkeyword and context managers, seePEP343.In addition to both thequeries.Session.queryandqueries.Session.callprocmethods that are similar to the simple API methods, thequeries.Sessionclass
provides access to the psycopg2 connection and cursor objects.Using queries.Session.queryThe following example shows how aqueries.Sessionobject can be used
as a context manager to query the database table:>>>importpprint>>>importqueries>>>>>>withqueries.Session()assession:...forrowinsession.query('SELECT * FROM names'):...pprint.pprint(row)...{'id':1,'name':u'Jacob'}{'id':2,'name':u'Mason'}{'id':3,'name':u'Ethan'}Using queries.Session.callprocThis example usesqueries.Session.callprocto execute a stored
procedure and then pretty-prints the single row results as a dictionary:>>>importpprint>>>importqueries>>>withqueries.Session()assession:...results=session.callproc('chr',[65])...pprint.pprint(results.as_dict())...{'chr':u'A'}Asynchronous Queries with TornadoIn addition to providing a Pythonic, synchronous client API for PostgreSQL,
Queries provides a very similar asynchronous API for use with Tornado.
The only major difference API difference betweenqueries.TornadoSessionandqueries.Sessionis theTornadoSession.queryandTornadoSession.callprocmethods return the entire result set instead of acting as an iterator over
the results. The following example usesTornadoSession.queryin an asynchronousTornadoweb application to send a JSON payload with the query result set.fromtornadoimportgen,ioloop,webimportqueriesclassMainHandler(web.RequestHandler):definitialize(self):self.session=queries.TornadoSession()@gen.coroutinedefget(self):results=yieldself.session.query('SELECT * FROM names')self.finish({'data':results.items()})results.free()application=web.Application([(r"/",MainHandler),])if__name__=="__main__":application.listen(8888)ioloop.IOLoop.instance().start()InspirationQueries is inspired byKenneth Reitz’sawesome
work onrequests.HistoryQueries is a fork and enhancement ofpgsql_wrapper, which can be found in the
main GitHub repository of Queries as tags prior to version 1.2.0.