Search code examples
pythondatabaseasynchronoustornado

Python: Tornado and persistent database connection


I am reading tornado documentation. I would like to have persistent connection(connection is up during application lifetime) to DB and return data from DB asynchronously. Where is the best place of doing this?

  • def initialize ?
  • handler's __init__ method?
  • def prepare?
  • or other place?

Could you provide some examples?


Solution

  • The simplest thing is just to make the database connection object a module-level global variable. See this example from the Motor documentation:

    db = motor.motor_tornado.MotorClient().test_database
    
    application = tornado.web.Application([
        (r'/', MainHandler)
    ], db=db)
    
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
    

    RequestHandlers could simply use the global variable directly. Also, passing the database as the db keyword argument to Application makes it available to request handlers in their "settings" dict:

    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            db = self.settings['db']
    

    This might make it easier to access the database object from RequestHandlers defined in other files.