我有一个文件,例如app.py和views.py
from flask import Flask
from flask_pymongo import PyMongo
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://local:27017/local"
mongo = PyMongo(app)
from views import profileview
profileview.register(app, route_prefix='/profile/')
if __name__== "__main__":
app.run(debug=True)
from flask_classy import FlaskView , route
# i am unable to import the app in views
from app import mongo
class profileview(FlaskView):
route_base = '/'
@route("/user/",methods=["GET"])
def index(self):
pass
当我运行服务器时,它显示无法 从视图导入导入profileview,如何避免循环导入
答案 0 :(得分:0)
这是避免循环导入的方法:
db.py
from flask_pymongo import PyMongo
mongo = PyMongo()
app.py
if __name__ == '__main__':
from db import mongo
mongo.init_app(app)
views.py
from db import mongo
或者您可以使用工厂模式并创建一个create_app函数。
答案 1 :(得分:-1)
您只需要直接在views.py中使用,因为您已经在应用程序配置中加载了它。
在您的views.py
中尝试一下 from pymongo import MongoClient
client = MongoClient(app.config['MONGODB_URI'])
db = client.get_database()
mycollection = db.mycollection