Python: Tornado and persistent database connection Python: Tornado and persistent database connection database database

Python: Tornado and persistent database connection


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_databaseapplication = 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.