How to use PyMongo with Flask Blueprints? How to use PyMongo with Flask Blueprints? flask flask

How to use PyMongo with Flask Blueprints?


One of the issues with the approach of performing an import in the blueprint as was suggest by Emanuel Ey, turns out that it causes a circular import. After much playing, it turns out that the only way (I could find) was to create a separate file called database.py that connects to the database and then I can import this connection to by blueprint as follows:

child.pyfrom database import mongocourses = Blueprint('courses', __name__)

and my database.py

from flask.ext.pymongo import PyMongomongo = PyMongo() 

and the app, login.py but has to initialize the database

from database import mongoapp = Flask(__name__)app.config.from_object('config')mongo.init_app(app) # initialize here!from child import child from child import2 child2app.register_blueprint(child.child)app.register_blueprint(child2.child2)


You're are initializing the PyMongo driver twice, once in child.py and a second time on child2.py.

Try initializing the PyMongo connection in the file which sets up your app object and then import it in the children:

login.py:

app.config.from_object('config')from flask.ext.pymongo import PyMongofrom child import childfrom child2 import child2app = Flask(__name__)mongo = PyMongo(app)# Register blueprintsdef register_blueprints(app):    # Prevents circular imports    app.register_blueprint(child2.child2)    app.register_blueprint(child.child)register_blueprints(app)

in child.py

from app import app, mongochild = Blueprint('child', __name__)

child2.py:

from app import app, mongochild2 = Blueprint('child2', __name__)