【问题标题】:Custom HTTP error templates not being served in FlaskFlask 中未提供自定义 HTTP 错误模板
【发布时间】:2020-10-14 23:58:23
【问题描述】:

我尝试实现此文档 https://flask.palletsprojects.com/en/1.1.x/patterns/errorpages/ 中的代码,但我为 HTTP 404 错误创建的自定义错误模板未加载(它加载了 Flask 的默认模板)。没有调用处理错误的方法,我不知道为什么。我是否正确实现了错误处理程序?

_初始化_.py

from flask import Flask

app = Flask(__name__)

def create_app():

    from flask_app.main.routes import main
    from flask_app.testing_errors.routes import testing_errors

    app.register_blueprint(main)
    app.register_blueprint(testing_errors)

    return app

运行.py

from flask_app import create_app
# importing the create_app method above creates the flask application instance after executing the command: flask run

testing_errors/routes.py

from flask import Blueprint, render_template

testing_errors = Blueprint("testing_errors", __name__)

@testing_errors.errorhandler(404)
def page_not_found(e):
    print("test")
    return render_template("404.html"), 404

404.html

 <html lang="en">
    <head>
      <title>404</title>
    </head>
    <body>
      <h1>404 Page Not Found</h1>
    </body>
 </html>

【问题讨论】:

    标签: python flask httpexception


    【解决方案1】:

    因为您使用蓝图来处理整个 Flask 应用程序错误,这是您需要 app_errorhandler 而不是 errorhandler 的最佳实践

    @testing_errors.app_errorhandler(404)
    def page_not_found(e):
        print("test")
        return render_template("404.html"), 404
    

    参考这个文档https://flask.palletsprojects.com/en/1.1.x/api/?highlight=app_errorhandler#flask.Blueprint.app_errorhandler

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 2015-11-05
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    相关资源
    最近更新 更多