我正在开发一个Flask应用程序,我不确定为什么会出现以下错误:
File "app.py", line 17, in <module>
from endpoints.users.resource import UserResource
File "{basedir}/endpoints/users/resource.py", line 4, in <module>
from .model import User
File "{basedir}/endpoints/users/model.py", line 1, in <module>
from app import db
File "{basedir}/app.py", line 17, in <module>
from endpoints.users.resource import UserResource
ImportError: cannot import name 'UserResource' from 'endpoints.users.resource' ({basedir}/endpoints/users/resource.py)
从错误来看,我认为这是由于循环依赖,但我不明白为什么,因为我认为我在代码中导入东西的顺序应该绕过了这个问题:
app.py:
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
api = Api(app)
api.prefix = '/api'
from endpoints.users.resource import UserResource
api.add_resource(UserResource, '/users')
if __name__ == '__main__':
app.run(host="0.0.0.0")
endpoints/users/model.py:
from app import db
class User(db.Model):
# info about the class, requires db
endpoints/users/resource.py:
from flask_restful import Resource
from .model import User
from app import db
class UserResource(Resource):
def get(self, username=None):
# get request, requires db and User
在app.py中,由于我是在创建数据库后从endpoints.users.resource导入的,这难道不应该绕过循环依赖吗?
此外,我可以用flask run
运行它,但当我尝试使用python app.py
时,它会给我上面的错误。为什么这些会产生不同的结果?
因此,在from endpoints.users.resource import UserResource
行上,python试图将from app import db
行导入app.py
,这导致app
引用自己,这一点都不好。
解决Flask中循环导入错误的一种解决方法是使用init_app
函数,该函数存在于大多数Flask应用程序中。因此,只需创建如下database
文件:
数据库.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
应用程序
from flask import Flask
from flask_restful import Api
from database import db
from endpoints.users.resource import UserResource
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
api = Api(app)
api.prefix = '/api'
api.add_resource(UserResource, '/users')
if __name__ == '__main__':
app.run(host="0.0.0.0")
endpoints/users/model.py:
from database import db
class User(db.Model):
# info about the class, requires db
endpoints/users/resource.py:
from flask_restful import Resource
from endpoints.users.model import User
from database import db
class UserResource(Resource):
def get(self, username=None):
# get request, requires db and User
请注意,我从related重写了您的导入,所以不要忘记添加__init__.py
文件
您的结构如下:
.
├── app.py
└── database.py/
└── endpoints/
├── __init__.py
└── users/
├── __init__.py
├── model.py
└── resource.py