title: how to create pymongo connection per request in Flask
body: <p>In my Flask application, I hope to use pymongo directly. But I am not sure what's the best way to create pymongo connection for each request and how to reclaim the connection resource.</p>
  
  <p>I know Connection in pymongo is thread-safe and has built-in pooling. I guess I need to create a global Connection instance, and use before_request to put it in flask g.</p>
  
  <p>In the app.py:</p>
  
  <pre><code>from pymongo import Connection
  from admin.views import admin
  connection = Connection()
  db = connection['test']
  
  @app.before_request
  def before_request():
      g.db = db
  
  @app.teardown_request
  def teardown_request(exception):
      if hasattr(g, 'db'):
          # FIX
          pass
  </code></pre>
  
  <p>In admin/views.py:</p>
  
  <pre><code>from flask import g
  @admin.route('/')
  def index():
      # do something with g.db
  </code></pre>
  
  <p>It actually works. So questions are:</p>
  
  <ol>
  <li><p>Is this the best way to use Connection in flask?</p></li>
  <li><p>Do I need to explicitly reclaim resources in teardown_request and how to do it?</p></li>
  </ol>