我的应用程序是这样组织的:
#---Project
# |---- core
# |_____ views.py
# |_____ __init__.py
# |_____ helpers.py
# |---- error_pages
# |_____ handlers.py
# |_____ templates
# |_____ 404.html
# |---- templates
# |_____ layout.html
# |_____ index.html
# |_____ temp.html
# |_____ tempform.html
# |_____ tempJS.html
# |---- static
# |_____ style.css
# |----- application.py
# |----- model.py
# |----- __init__.py我想处理文件夹error_pages.In中的错误--这个文件夹我有一个handles.py:
from flask import Blueprint, render_template
error_pages = Blueprint('error_pages',__name__, template_folder='/templates')
@error_pages.app_errorhandler(404)
def error_404(error):
return render_template('404.html'), 404
@error_pages.app_errorhandler(403)
def error_403(error):
return render_template('403.html'), 403我的init.py是:
# errors templates
from Project.error_pages.handlers import error_pages
app.register_blueprint(error_pages)但是,我想检查错误代码是否正常,是否已填充并且不存在html页面:错误是:
jinja2.exceptions.TemplateNotFound: 404.html
我已经完成了工作蓝图(对用户来说,.)
有人能帮忙吗?
发布于 2020-07-06 05:50:11
通过查看应用程序的树,即使没有template_folder属性,蓝图也应该知道在哪里可以找到应用程序模板文件夹。
--您可能会问,为什么存在
template_folder属性。
蓝图上下文中的template_folder的目的是向模板的搜索路径中添加另一个模板文件夹,但其优先级低于实际应用程序的模板文件夹。
如果您的应用程序结构没有很好的定义,这可能是相当棘手的。您可能会意外地重写蓝图模板。这就是为什么您需要确保为每个蓝图提供不同的相对路径(否则,注册的第一个蓝图优先于其他蓝图)。
的问题是什么,你为什么要使用“子模板”?
我称它们为“子模板”,以区分它们与应用程序模板文件夹。
当您想重构您的应用程序时,会这样做,并且为每个蓝图提供一个模板。
实例
如果您有一个名为auth的蓝图,并且希望呈现一个名为auth/login.html的模板,并将templates作为一个template_folder提供给该蓝图,那么您必须创建一个类似于以下所示的文件:yourapplication/auth/templates/auth/login.html。
所以最好的方法是像这样布局你的模板:
yourpackage/
blueprints/
auth/
templates/
auth/
login.html
__init__.py额外的auth文件夹的原因是避免在实际的应用程序模板文件夹中被模板名为login.html的模板覆盖。
然后,当您想在视图函数中呈现模板时,可以使用auth/login.html作为查找模板的名称。
如果您在加载正确的模板时遇到问题,请启用EXPLAIN_TEMPLATE_LOADING配置变量,它将指示Flask打印出在每个render_template调用中定位模板的步骤。
要回答您的问题,首先修改模板路径,如下所示:
error_pages = Blueprint('error_pages',__name__, template_folder='/templates')然后像这样修改您的项目结构
# |---- error_pages
# |_____ handlers.py
# |_____ templates
# |_____ error_pages
# |_____ 404.html发布于 2020-07-06 02:23:11
有一个微妙的,但很大的区别
error_pages = Blueprint('error_pages',__name__, template_folder='/templates')和
error_pages = Blueprint('error_pages',__name__, template_folder='templates')你用的是前者。试试后者。
https://stackoverflow.com/questions/62745839
复制相似问题