from app import db ImportError: cannot import name ‘db‘ from ‘app‘

from app import db

ImportError: cannot import name ‘db’ from ‘app’

flask bluePrint 蓝图学习避坑

掉坑里几个小时才解决
问题:
from app import db ImportError: cannot import name ‘db‘ from ‘app‘_第1张图片
原因:

导入包的顺序不对,应该在db生成后,在去注册蓝图,正确的顺序如下:

我的理解:蓝图注册的导包应该在 db=SQLAlchemy() 后面

这样是ok的:

# -*- coding:utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

import config

db = SQLAlchemy()


def create_app():
    app = Flask(__name__, template_folder='../templates')
    # 加载配置
    app.config.from_object(config.DevelopmentConfig)

    # 注册蓝图
    from app.view import init_bp
	from app.view.blog_view import blog_bp
	from app.view.ent_view import ent_bp
	from app.view.house_view import house_bp
    app.register_blueprint(init_bp, url_prefix='/')
    app.register_blueprint(blog_bp, url_prefix='/blog')
    app.register_blueprint(ent_bp, url_prefix='/ent')
    app.register_blueprint(house_bp, url_prefix='/house')

    db.init_app(app)

    return app

这样也是ok的:

# -*- coding:utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import config

db = SQLAlchemy()

from app.view import init_bp
from app.view.blog_view import blog_bp
from app.view.ent_view import ent_bp
from app.view.house_view import house_bp

def create_app():
    app = Flask(__name__, template_folder='../templates')
    # 加载配置
    app.config.from_object(config.DevelopmentConfig)

    # 注册蓝图
    app.register_blueprint(init_bp, url_prefix='/')
    app.register_blueprint(blog_bp, url_prefix='/blog')
    app.register_blueprint(ent_bp, url_prefix='/ent')
    app.register_blueprint(house_bp, url_prefix='/house')

    db.init_app(app)

    return app

参考文献:https://www.jianshu.com/p/998677d47ecc
https://www.shangmayuan.com/a/44593cea254d4a49a4b7b982.html

你可能感兴趣的:(flask,数据库,flask,python)