本文介绍了烧瓶-蓝图-sqlalchemy-无法将名称“db"导入到moles文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new in bluprint, and have problem with importing db into mydatabase.py file which is models file.

我遇到了这个错误:

导入错误:无法导入名称 'db'

我的项目树

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

运行.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='/')

书架/主/控制器.py

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,如果我把那个删掉,错误会变成:

The problem backs to from bookshelf import db, and if I delete that, the error will be changed to:

导入错误:无法导入名称 'db'

书架/mydatabase.py

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

有什么解决办法吗?

推荐答案

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

This is actually a simple, yet frustrating issue. The problem is you are importing main BEFORE you are creating the instance of db in your __init__.py

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

If move the import to after your db = SQLAlchemy(app), it will work:

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

这篇关于烧瓶-蓝图-sqlalchemy-无法将名称“db"导入到moles文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 20:14