title: Flask: setting application and request-specific attributes?
body: <p>I am writing an application which connects to a database. I want to create that db connection once, and then reuse that connection throughout the life of the application.</p>
  
  <p>I also want to authenticate users. A user's auth will live for only the life of a request.</p>
  
  <p>How can I differentiate between objects stored for the life of a flask app, versus specific to the request? Where would I store them so that all modules (and subsequent blueprints) have access to them?</p>
  
  <p>Here is my sample app:</p>
  
  <pre><code>from flask import Flask, g
  
  app = Flask(__name__)
  
  @app.before_first_request
  def setup_database(*args, **kwargs):
      print 'before first request', g.__dict__
      g.database = 'DATABASE'
      print 'after first request', g.__dict__
  
  @app.route('/')
  def index():
      print 'request start', g.__dict__
      g.current_user = 'USER'
      print 'request end', g.__dict__
  
      return 'hello'
  
  if __name__ == '__main__':
      app.run(debug=True, port=6001)
  </code></pre>
  
  <p>When I run this (Flask 0.10.1) and navigate to <code>http://localhost:6001/</code>, here is what shows up in the console:</p>
  
  <pre><code>$ python app.py 
   * Running on http://127.0.0.1:6001/
   * Restarting with reloader
  
  before first request {}
  after first request {'database': 'DATABASE'}
  request start {'database': 'DATABASE'}
  request end {'current_user': 'USER', 'database': 'DATABASE'}
  127.0.0.1 - - [30/Sep/2013 11:36:40] "GET / HTTP/1.1" 200 -
  
  request start {}
  request end {'current_user': 'USER'}
  127.0.0.1 - - [30/Sep/2013 11:36:41] "GET / HTTP/1.1" 200 -
  </code></pre>
  
  <p>That is, the first request is working as expected: <code>flask.g</code> is holding my database, and when the request starts, it also has my user's information.</p>
  
  <p>However, upon my second request, flask.g is wiped clean! My database is nowhere to be found.</p>
  
  <p>Now, I know that flask.g <em>used</em> to apply to the request only. But now that it is bound to the application (as of 0.10), I want to know how to bind variables to the entire application, rather than just a single request.</p>
  
  <p>What am I missing?</p>
  
  <p><strong>edit:</strong> I'm specifically interested in MongoDB - and in my case, maintaining connections to multiple Mongo databases. Is my best bet to just create those connections in <code>__init__.py</code> and reuse those objects? </p>