python-3.x - 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'
解决方案
看起来像
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
,因此您需要其中两个。
推荐阅读
- swift - 我想在 SwiftUI 中使用 NavigationLink 移动到第一个屏幕
- flutter - 从 PopupMenuButton 打开时删除项目
- java - 如何在活动打开时重新加载一次
- javascript - 带有 Mustache 和 JS 的动态 HTML 页面构建器
- python - 使用 for 循环函数进行数据抓取
- python - 如何在一行中同时使用舍入函数和绝对值函数?
- firebase - (Flutter) 无法使用 Cloud Storage 下载图片
- django - Django 更好地加入
- javascript - 有没有更优雅的方式来编写这个 If/or 条件?
- angular - 在angular8中收到错误消息后如何将金额转换为货币管道值