如何使用 Flask 实现“页面未找到”功能?

Iam*_*ris 1 python jinja2 flask web

如果您访问的网站的子网址不存在,例如 http://www.reddit.com/notathing

它将带您进入一个带有华丽图形的自定义网站,以及返回正轨的简单链接。

将显示香草烧瓶

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Run Code Online (Sandbox Code Playgroud)

如何使用 Flask 创建一个“包罗万象”的网页来美化这样的用户错误?

dav*_*ism 5

有关错误处理程序的文档对此进行了描述。@app.errorhandler()用代替修饰视图@app.route()会将其视为给定类型错误的视图。在您的情况下,404 处理程序可能如下所示:

@app.errorhandler(404)
def not_found(e):
    cool_image = pick_cool_image()
    return render_template('404_not_found.html', image=cool_image)
Run Code Online (Sandbox Code Playgroud)

现在 404_not_found.html 模板可以使用您在处理程序中选择的酷图像来显示有趣的页面。

您可以通过这种方式处理任何错误状态代码,但也可以处理可能导致 500 错误的 Python 异常。通过这种方式,您可以制作特定于错误类型的非常详细的错误页面。例如:

class NotModeratorError(Exception):
    pass

@app.errorhandler(NotModeratorError)
def not_a_moderator(e):
    return render_template('errors/not_a_moderator.html')

@app.route('/mod_powers')
def mod_powers():
    if not current_user.is_moderator:
        raise NotModeratorError()
Run Code Online (Sandbox Code Playgroud)