Python: Tornado and persistent database connection
<p>I am reading <a href="http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.initialize" rel="nofollow">tornado documentation</a>. 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?</p>

<ul>
<li><code>def initialize</code> ?</li>
<li>handler's <code>__init__</code> method?</li>
<li><code>def prepare</code>?</li>
<li>or other place?</li>
</ul>

<p>Could you provide some examples? </p>

<p>The simplest thing is just to make the database connection object a module-level global variable. See this example <a href="http://motor.readthedocs.io/en/stable/tutorial-tornado.html#tornado-application-startup-sequence" rel="nofollow">from the Motor documentation</a>:</p>

<pre><code>db = motor.motor_tornado.MotorClient().test_database

application = tornado.web.Application([
    (r'/', MainHandler)
], db=db)

application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
</code></pre>

<p>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:</p>

<pre><code>class MainHandler(tornado.web.RequestHandler):
    def get(self):
        db = self.settings['db']
</code></pre>

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

python database asynchronous tornado