title: Flask/PyMongo - Initialize pymongo at the top of the app
body: <p>I'm trying to scale up my first Flask app and am not understanding the structure needed to use a pymongo db in multiple modules. For example, here is my new structure:</p>
  
  <pre><code>run.py
  app/
  ├── __init__.py
  ├── forms.py
  ├── static/
  ├── templates/
  └── views/
      ├── __init__.py
      ├── bookmarklet.py
      ├── main.py
      └── user.py
  </code></pre>
  
  <p>Prior to trying to scale this, I had this at the top of my single <code>views.py</code> file:</p>
  
  <pre><code>from flask.ext.pymongo import PyMongo
  mongo = PyMongo(app)
  with app.app_context():
      mongo.db.user.ensure_index("email", unique=True)
  </code></pre>
  
  <p>The goal is to be able to use this <code>mongo</code> instance in all of the view modules as well as the <code>forms.py</code> module. I've tried these two things:</p>
  
  <ol>
  <li>Put the above snippet in the <code>app/__init__.py</code> file, but can't seem to make it accessible to any other modules. I tried doing this: <code>app.db = mongo.db</code> (but it wasn't available downstream)</li>
  <li>Put the above snippet into each module that needs it, but then I get the error that there are multiple mongo instances with the same prefix.</li>
  </ol>
  
  <p>Where should this initialization go in order to make it accessible everywhere in the app?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>It sounds like I'm doing it right but there is something else going on. I'm posting my more complete code and error.</p>
  
  <p>app/__init__.py</p>
  
  <pre><code>from flask import Flask
  
  app = Flask(__name__)
  from app.views import main
  
  app.config.update(
      DEBUG = True,
      SECRET_KEY = "not telling",
      WTF_CSRF_ENABLED = False,
  )
  
  app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')
  
  from flask.ext.pymongo import PyMongo
  mongo = PyMongo(app)
  with app.app_context():
      mongo.db.user.ensure_index("email", unique=True)
  </code></pre>
  
  <p>app/views/main.py</p>
  
  <pre><code>from app import app
  from flask import render_template, redirect, request, flash, url_for
  from flask.ext.jsonpify import jsonify
  from app.forms import *
  
  from app import *
  print mongo
  </code></pre>
  
  <p>Error:</p>
  
  <pre><code>(venv)imac: me$ ./run.py 
  Traceback (most recent call last):
    File "./run.py", line 4, in &lt;module&gt;
      from app import app
    File "/Users/me/Dropbox/development/test/app/__init__.py", line 4, in &lt;module&gt;
      from app.views import main
    File "/Users/me/Dropbox/development/test/app/views/main.py", line 9, in &lt;module&gt;
      print mongo
  NameError: name 'mongo' is not defined
  </code></pre>