简体   繁体   中英

Using Flask-pymongo across multiple modules

I'm having some trouble understanding how to incorporate Flask-Pymongo. My app is initiated from my rrapp.py Inside of this file, I have

rrapp.py

#
# Imports up here
#

app = Flask(__name__)
mongo = PyMongo(app)

# Code down here

Now, to use this, I simply do mongo.db.users.find() . This works fine.

Now, say I have another file called userservice.py that I call methods from one of my endpoints within rrapp.py . How do I incorporate PyMongo(app) in my userservice.py file if I don't have access to the app object? Or am I missing something obvious here?

  • you should first define mongo oustside create_app to have access to it from inside other files.
  • then init_app with that like the following:

from flask import Flask, current_app

from flask_pymongo import PyMongo

mongo = PyMongo()

def create_app(config_name):
    app = Flask(__name__, instance_relative_config=False)

    app.config.from_object(app_config[config_name])

    # INIT EXTENSIONS ----------------------

    mongo.init_app(app)

    return app

then in any file you can import mongo from above file. for example:

from ../factory import mongo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM