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

时间:2017-01-24 12:51:45

标签: python flask import sqlalchemy blueprint

我是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)

书架/ 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 个答案:

答案 0 :(得分:28)

这实际上是一个简单但令人沮丧的问题。问题是您要导入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='/')