问题描述
我的应用程序通过一个 @ app.route
捕获所有的url请求,但偶尔我遇到了一个坏的url,我没有匹配的jinja文件(它匹配现有的 @ app.route
)。所以我想重定向这样的请求到一个404页面的那个坏的网址。 如何区分忍者文件存在和忍者文件不存在之前返回 render_template()
?
Jinja会抛出异常如果模板没有找到: TemplateNotFound
所以不是:
def myview():
return render_template(...)
你可以这样做:
def myview():
试试:
返回render_template(...)
,除了TemplateNotFound:
abort(404)
然后按照。不要忘记从 flask
和 TemplateNotFound
中导入 abort
从 jinja2
My application catches all url requests with an @app.route
, but occasionally I bump into a bad url for which I have no matching jinja file (bu it does match an existing @app.route
). So I want to redirect such requests to a 404 page for that bad url.
How to discriminate between "a jinja file exists" and "a jinja file doesn't exist" before returning render_template()
?
Jinja will throw an exception if the template is not found: TemplateNotFound
So instead of:
def myview():
return render_template(...)
you could do something like this:
def myview():
try:
return render_template(...)
except TemplateNotFound:
abort(404)
And then handle the 404 error with a custom error page as explained in the Flask documentation. Don't forget to import abort
from flask
and TemplateNotFound
from jinja2
这篇关于我如何创建一个404页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!