我如何创建一个404页面? [英] How do I create a 404 page?

查看:140
本文介绍了我如何创建一个404页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序通过一个 @ 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文档。不要忘记从 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页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆