我是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 + "}"
有解决方案吗
这实际上是一个简单但令人沮丧的问题.问题是你是从国外进口主要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='/')