这是我的项目结构:
myProject/
|
|-- src/
| |-- services/
| | |-- __init__.py
| | |-- users.py
| |
| |-- main.py
| |-- ...
...
主要是我需要在 users.py 中使用的 mongo var
# src/main.py
from flask import Flask
from flask_pymongo import PyMongo
import config
from services import api
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/myApp"
mongo = PyMongo(app)
api.init_app(app)
if __name__ == '__main__':
app.run(host=config.HOST, port=config.PORT, debug=config.DEBUG)
在服务初始化.py
# src/services/__init__.py
from flask_restx import Api
from .users import api as np_users
import config
api = Api(
title=config.NAME,
version=config.VERSION,
description=config.DESCRIPTION,
)
api.add_namespace(np_users, path='/api/v1/users/users')
我尝试在以下位置导入 mongo var:
# src/services/users.py
...
from main import mongo
api = Namespace('users', description='users')
...
当我做:
python main.py
它向我抛出了这个错误:
回溯(最后一次调用):文件“main.py”,第 7 行,从服务导入 api 文件“C:\myProject\src\services_ init _.py”,第 6 行,从 .users 导入 api 作为 ns_users文件 "C:\myProject\src\services\users.py",第 5 行,inices\users.py",第 5 行,从主导入 mongo 文件 "C:\myProject\src\main.py",第 7 行, in .py", line 7, in from services import api end_analisis_predccion_equipos_b ImportError: cannot import name 'api' from 'services' (C:\myProject\src\services_ init _.py)