使用Python(Flask)的多个404错误页面

Joe*_*edo 3 python flask python-2.7

是否有可能使用烧瓶在python中提供多个404页面?

目前我在views.py文件中有这个:

@application.errorhandler(404)
def page_not_found(e):
    return render_template('errorpages/404.html'), 404
Run Code Online (Sandbox Code Playgroud)

是否可以管理,例如,三个随机的404页而不是一个?怎么样?

提前致谢.

nea*_*ick 5

如果您希望服务器随机选择三个404页面中的一个进行服务,那么您可以执行以下操作:

import random

@application.errorhandler(404)
def page_not_found(e):
    return render_template(
        'errorpages/404_{}.html'.format(random.randint(0, 3)) ), 404
Run Code Online (Sandbox Code Playgroud)

你的网页在哪里errorpages/404_1.html,errorpages/404_2.htmlerrorpages/404_3.html


或者,如果您希望哪个页面服务依赖于条件,您的代码将如下所示:

@application.errorhandler(404)
def page_not_found(e):
    if condition:
        return render_template('errorpages/404_1.html'), 404
    return render_template('errorpages/404.html'), 404
Run Code Online (Sandbox Code Playgroud)