首页 > 解决方案 > Flask Blueprint 在 __init__ 文件中尝试在应用程序上注册蓝图时返回 NameError

问题描述

NameError: name 'i_statement_bp' is not defined在尝试注册i_statement_bp使用 ABC/app/ 中的应用程序命名的bluepring 时遇到了问题__init__.py。我有Flask app以下Blueprints结构:

ABC/
 |- run.py
 |- app/
     |--__init__.py
     |
     |--i_statement/
     |        |--__init__.py
     |        |
     |        |--templates/
     |        |        |--i_statement.html
     |        |
     |        |--i_statement.py
     |       
     |--blog/
     |
     |--static/
            |
            |--images/
            |--css/
            |--js/
            |--fonts/

我的ABC/app/__init__.py样子如下:

import flask from Flask, Blueprint

class MyApp(Flask):
 def __init__(self):
    Flask.__init__(self, __name__)  
    self.jinja_loader=jinja2.ChoiceLoader([self.jinja_loader,
    jinja2.PrefixLoader({}, delimiter = ".")])

    def create_global_jinja_loader(self):
        return self.jinja_loader

    def register_blueprint(self, bp):
        Flask.register_blueprint(self, bp)
        self.jinja_loader.loaders[1].mapping[bp.name] = bp.jinja_loader

app=MyApp()

app.register_blueprint(i_statement_bp) **<== this line of code is causing error per debugger** 

from app.i_statement import i_statement_bp

__init__.py`i_statement' 文件夹中的文件为空,仅表示这是 Python 的包。

名为的文件i_statement.py如下所示:

from flask import Blueprint, request, jsonify, session

i_statement_bp=Blueprint('i_statement_bp',__name__,
url_prefix='/i_statement',template_folder="templates")

@i_statement_bp.route('/i_statement',methods=['GET','POST'])
  def i_statement():
     some logic here
     return render_template('i_statement.html',variable=variable)

作为附加信息,MyApp 类的原因是希望在蓝图文件夹中有模板文件夹,而不是模板文件夹位于 app 文件夹中的典型方法。

ABC/run.py文件如下所示:

from app import app

app.secret_key=flask_secret_key

app.run(debug=debug)

更新:根据评论中的建议,我已将线路切换ABC/app/__init__.py如下:

from app.i_statement import i_statement_bp
app.register_blueprint(i_statement_bp) 

这种安排会产生新的错误类型:

from app import app
File "C:\ABC\app\__init__.py", line 55, in <module>
from app.i_statement import i_statement_bp
ImportError: cannot import name 'i_statement_bp' from 'app.i_statement'

标签: python-3.xflask

解决方案


看起来像

from app.i_statement import i_statement_bp

之后导入

app.register_blueprint(i_statement_bp)

尝试切换这些语句的顺序。

更新:

试试吧

from app.i_statement.i_statement import i_statement_bp

你的第二个错误。

请注意您如何拥有文件夹i_statement,然后是文件i_statement.py,因此您需要其中两个。


推荐阅读