【问题标题】:flask: error_handler for blueprints烧瓶:蓝图的error_handler
【发布时间】:2012-09-27 22:36:55
【问题描述】:

可以为蓝图设置error_handler吗?

@blueprint.errorhandler(404)
def page_not_found(error):
    return 'This page does not exist', 404

编辑:

https://github.com/mitsuhiko/flask/blob/18413ed1bf08261acf6d40f8ba65a98ae586bb29/flask/blueprints.py

您可以指定应用范围和蓝图本地 error_handler

【问题讨论】:

    标签: http-status-code-404 blueprint flask


    【解决方案1】:

    您可以像这样使用Blueprint.app_errorhandler 方法:

    bp = Blueprint('errors', __name__)
    
    @bp.app_errorhandler(404)
    def handle_404(err):
        return render_template('404.html'), 404
    
    @bp.app_errorhandler(500)
    def handle_500(err):
        return render_template('500.html'), 500
    

    【讨论】:

    • 即使有了这个,蓝图视图中的abort(404) 将由应用程序的错误处理程序处理,而不是这个。有关更多信息,请参阅Flask doc
    【解决方案2】:

    errorhandler 是继承自 Flask 的方法,而不是 Blueprint。 如果您使用的是蓝图,则相当于 app_errorhandler

    文档建议采用以下方法:

    def app_errorhandler(self, code):
            """Like :meth:`Flask.errorhandler` but for a blueprint.  This
            handler is used for all requests, even if outside of the blueprint.
            """
    

    因此,这应该有效:

    from flask import Blueprint, render_template
    
    USER = Blueprint('user', __name__)
    
    @USER.app_errorhandler(404)
    def page_not_found(e):
        """ Return error 404 """
        return render_template('404.html'), 404
    

    另一方面,虽然下面的方法对我没有任何错误,但它不起作用:

    from flask import Blueprint, render_template
    
    USER = Blueprint('user', __name__)
    
    @USER.errorhandler(404)
    def page_not_found(e):
        """ Return error 404 """
        return render_template('404.html'), 404
    

    【讨论】:

    • 谢谢,这很好用。应该是公认的答案。
    • 文档说我们必须使用errorhandler而不是app_errorhandler。你注意到了吗?
    【解决方案3】:

    我也无法获得评分最高的答案,但这里有一个解决方法。

    您可以在蓝图的结束处使用一个包罗万象的方法,不确定它的健壮性/推荐程度,但它确实有效。您也可以为不同的方法添加不同的错误消息。

    @blueprint.route('/<path:path>')
    def page_not_found(path):
        return "Custom failure message"
    

    【讨论】:

      【解决方案4】:

      使用请求代理对象在应用程序级别添加错误处理:

      from flask import request,jsonify
      
      @app.errorhandler(404)
      @app.errorhandler(405)
      def _handle_api_error(ex):
      if request.path.startswith('/api/'):
          return jsonify(ex)
      else:
          return ex
      

      flask Documentation

      【讨论】:

        【解决方案5】:

        惊讶于其他人没有提到 miguelgrinberg 的优秀教程。

        https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-error-handling

        我找到了用于错误处理的哨兵框架(下面的链接)。似乎过于复杂。不确定它在什么时候有用。

        https://flask.palletsprojects.com/en/1.1.x/errorhandling/

        https://docs.sentry.io/platforms/python/guides/flask/

        【讨论】:

          【解决方案6】:

          我将之前的 excellent answers 与来自 Flask 的官方文档的“Returning API Errors as JSON”部分结合起来,以便提供更通用的方法。

          这是一个有效的 PoC,您可以将其复制并粘贴到您注册的蓝图 API 路由处理程序(例如 app/api/routes.py):

          @blueprint.app_errorhandler(HTTPException)
          def handle_exception(e):
          """Return JSON instead of HTML for HTTP errors."""
          # start with the correct headers and status code from the error
          response = e.get_response()
          # replace the body with JSON
          response.data = json.dumps({
              "code": e.code,
              "name": e.name,
              "description": e.description,
          })
          response.content_type = "application/json"
          return response
          

          【讨论】:

            【解决方案7】:

            烧瓶doesnt support blueprint level error handlers for 404 and 500 errors。蓝图是一种泄漏的抽象。最好为此使用新的 WSGI 应用程序,如果您需要单独的错误处理程序,这更有意义。

            另外我建议不要使用flask,它在所有地方都使用全局变量,如果它变得更大,这会使你的代码难以管理。

            【讨论】:

            • 投反对票,因为烧瓶推荐是高度主观的,与提出的问题无关
            猜你喜欢
            • 1970-01-01
            • 2012-06-16
            • 2015-07-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-09-21
            • 1970-01-01
            • 2018-09-26
            相关资源
            最近更新 更多