【问题标题】:Flask blueprints cannot import module烧瓶蓝图无法导入模块
【发布时间】:2017-01-31 21:58:37
【问题描述】:

我正在学习 Flask 蓝图,但在导入正确的模块时遇到了问题。这是我的设置:

文件夹结构:

- app.py
  templates/
  nomad/
     - __init__.py
     - nomad.py

app.py

from flask import Flask
from nomad.nomad import nblueprint

app = Flask(__name__)
app.register_blueprint(nblueprint)

nomad.py

from flask import render_template, Blueprint, abort
from app import app

nblueprint = Blueprint('nblueprint', __name__, template_folder='templates')

# Routes for this blueprint
@app.route ....

__init__.py 为空

我得到的错误:ImportError: cannot import name nblueprint。我知道我的 import 语句可能是错误的,但它应该是什么以及为什么?

编辑

如果我删除from app import app,那么我可以在app.py中成功导入nblueprint。但我需要在 nomad.py 中使用app,因为它需要处理路由。为什么该行会导致导入问题,我该如何解决?

【问题讨论】:

    标签: python python-2.7 flask


    【解决方案1】:

    Blueprints 用于定义应用程序路由,因此您无需在同一位置使用应用程序实例和蓝图来定义路由。

    #nomad.py
    @nblueprint.route('/')
    

    您收到错误是因为您在使用应用实例的同时注册了蓝图。因此,正如您所说,当您删除 from app ... 时,它可以解决问题。

    推荐的方法是在您的示例nomad 包中定义蓝图在蓝图包中的视图,它应该是这样的:

    ...
      nomad/
            __init__.py
            views.py
    #nomad/__init__.py
    nblueprint = Blueprint(...)
    #nomad/views.py
    from . import nblueprint
    @nblueprint.route('/')
    ...
    

    【讨论】: