【问题标题】:Multiple 404 error pages using Python (Flask)使用 Python (Flask) 的多个 404 错误页面
【发布时间】:2015-05-08 15:50:05
【问题描述】:

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

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

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

例如,提供三个随机 404 页面而不是一个页面是否易于管理?怎么样?

提前致谢。

【问题讨论】:

    标签: python python-2.7 flask


    【解决方案1】:

    如果您希望您的服务器随机选择三个 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.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-04
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多