flask-sqlalchemy:导入模型出错 [英] flask-sqlalchemy: import models going wrong
问题描述
我正在使用Flask和Sqlalchemy构建一个应用程序.我的 app.py
文件开始如下:
I am building an app with Flask and Sqlalchemy.
My app.py
file starts like this:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
from models import User
和我的 models.py
像这样:
from app import db
class User
....
因此,当我运行 python app.py
时,出现错误消息无法导入用户名".我想某处有一个循环导入,我不知道如何解决它.
so when I run python app.py
, I get an error saying "cannot import name User". I guess there's a circular import somewhere, I don't understand how to fix it.
但是,如果我仅用
from app import app
app.run()
一切正常.但是,为什么这会中断循环导入?我不明白.
Everything works perfectly. But why does this break circular import? I can't understand this.
推荐答案
您做对了:这是一个循环导入问题.
You've got it right: this is a circular import problem.
解决这个问题的方法是在根目录中有另一个文件,即 shared.py
文件.在该文件中,创建数据库对象,
The way that I've gotten around this is by having another file, a shared.py
file in the root directory. In that file, create the database object,
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
在您的 app/init.py
中,不要创建新的数据库对象.相反,
In your app/init.py
, don't create a new db object. Instead, do
from shared import db
db.init_app(app)
在您想使用db对象的任何地方(包括模型文件),从 shared.py
导入它:
In any place that you want to use the db object, including your models file, import it from shared.py
:
from shared import db
# do stuff with db
这样,共享文件中的对象将已使用应用程序上下文进行了初始化,并且没有循环导入的机会.
This way, the object in the shared file will have been initialized with the app context, and there's no chance of circular imports.
这篇关于flask-sqlalchemy:导入模型出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!