当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《flask-blueprint-sqlalchemy-无法将名称'db'导入moles文件》经验,为你挑选了1个好方法。

我是bluprint的新手,并且将db导入mydatabase.py文件是一个模型文件.

我遇到过这个错误:

ImportError:无法导入名称'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)

bookshelf/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='/')

bookshelf/main/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:无法导入名称'db'

bookshelf/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 + "}"

有解决方案吗



1> CodeLikeBeak..:

这实际上是一个简单但令人沮丧的问题.问题是你是从国外进口主要BEFORE要创建的实例db__init__.py

如果将导入移到您之后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='/')

推荐阅读
和谐啄木鸟
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有