How to use PyMongo with Flask Blueprints?

前端 未结 2 2034
我在风中等你
我在风中等你 2021-02-19 19:00

What is the correct way of picking up mongo object inside Blueprints?

Here is how I have my parent login.py:

app.config.from_object(\         


        
2条回答
  •  深忆病人
    2021-02-19 19:42

    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.py
    
    from database import mongo
    courses = Blueprint('courses', __name__)
    

    and my database.py

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

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

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

提交回复
热议问题