Async Psycopg for Tornado
— Frank — Share
Update: I’ve made a repositoryon Github: github.com/FSX/momoko.
Since last week I’ve been trying to get asynchronous Psycopg working with Tornado after I got some good help on the mailinglist. I’ve put the code in a gist on Github. An example is also included.
This should be considered alpha software since I didn’t test it extensively. And I’ll put it in a library when it gets bigger.
Here’s a small fragment of an example application:
from async_psycopg2 import Pool
class BaseHandler(tornado.web.RequestHandler):
@property
def db(self):
if not hasattr(self.application, 'db'):
self.application.db = Pool(1, 20, 10, **{
'host': 'localhost',
'database': 'somedatabase',
'user': 'someuser',
'password': 'password',
'async': 1
})
return self.application.db
class MainHandler(BaseHandler):
@tornado.web.asynchronous
def get(self):
self.db.execute('SELECT 42, 12, 40, 11;', callback=self._on_response)
def _on_response(self, cursor):
self.write('Query results: %s' % cursor.fetchall())
self.finish()
I was considering trying to add a way to run multiple asynchronous queries in one request, but I’ll wait with that untill I need it in the project I’m working on.