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

乔尔·阿兹维多(Joel Azevedo)

是否可以使用flask在python中提供多个404页?

目前,我的views.py文件中包含以下内容:

@application.errorhandler(404)
def page_not_found(e):
    return render_template('errorpages/404.html'), 404

例如,提供三个随机的404页而不是仅提供一个404页是否可以管理?如何?

提前致谢。

尼特尼克

如果您希望服务器随机选择要提供的三个404页之一,则可以执行以下操作:

import random

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

您的网页在哪里errorpages/404_1.htmlerrorpages/404_2.html以及errorpages/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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章