I'm new in bluprint, and have problem with importing db into mydatabase.py file which is models file.
I've faced with this error:
ImportError: cannot import name 'db'
The tree of my project
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"
The problem backs to from bookshelf import db
, and if I delete that, the error will be changed to:
ImportError: cannot import name '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 + "}"
Any solution?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…