flask - blueprint - sqlalchemy - 无法将名称 'db' 导入 moles 文件

flask - blueprint - sqlalchemy - cannot import name 'db' into moles file

我是 bluprint 的新手,在将 db 导入模型文件 mydatabase.py 文件时遇到问题。

我遇到过这个错误:

ImportError: cannot import name 'db'

我项目的树

nikoofar/
    run.py
    bookshelf/
        __init__.py
        mydatabase.py
        main/
            controllers.py
            __init__.py

run.py

from bookshelf import app

if __name__ == '__main__':
    app.run(debug=True, port=8000)

书架/intit.py

from flask import Flask
from bookshelf.main.controllers import main
from flask_sqlalchemy import SQLAlchemy
from mydatabase import pmenu


app = Flask(__name__, instance_relative_config=True)
db = SQLAlchemy(app)
db.init_app(app)
application.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username:password@localhost/databasename'

app.config.from_object('config')

app.register_blueprint(main, url_prefix='/')

书架/主/controllers.py

from flask import Blueprint
from bookshelf.mydatabase import *
from flask_sqlalchemy import SQLAlchemy


main = Blueprint('main', __name__)


@main.route('/')
def index():
    g = pmenu.query.all()
    print (g)
    return "ok"

问题又回到了from bookshelf import db,如果我删除那个,错误会变成:

ImportError: cannot import name 'db'

书架/mydatabase.py

from bookshelf import db

class pmenu(db.Model):
    __tablename__ = 'p_menu'
    id = db.Column(db.Integer, primary_key=True)
    txt = db.Column(db.String(80), unique=True)
    link = db.Column(db.String(1024))
    def __init__(self, txt, link):
        self.txt = txt
        self.link = link
    def __repr__(self):
        return "{'txt': " + self.txt + ", 'link':" + self.link + "}"

有什么解决办法吗?

这实际上是一个简单但令人沮丧的问题。问题是您正在导入 main BEFORE 您正在 __init__.py

中创建 db 的实例

如果将导入移动到 db = SQLAlchemy(app) 之后,它将起作用:

from flask import Flask

from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://uername:password@localhost/test'

db = SQLAlchemy(app)

from bookshelf.main.controllers import main #<--move this here

app.register_blueprint(main, url_prefix='/')