【问题标题】:What is best practice for flask error handling?烧瓶错误处理的最佳实践是什么?
【发布时间】:2020-06-05 00:57:24
【问题描述】:

为了在 flask webapp 中向客户端返回 400/500 响应,我看到了以下约定:

中止

import flask
def index(arg):
    return flask.abort("Invalid request", 400)

元组

def index(arg):
    return ("Invalid request", 400)

响应

import flask
def index(arg):
    return flask.Response("Invalid request", 400)

有什么区别,什么时候会更受欢迎?

相关问题

来自Java/Spring,我习惯于定义一个带有与之关联的状态码的自定义异常,然后每当应用程序抛出该异常时,带有该状态码的响应会自动返回给用户(而不必显式地捕获它并返回如上所示的响应)。这在flask 中可行吗?这是我的小包装尝试

from flask import Response

class FooException(Exception):
    """ Binds optional status code and encapsulates returing Response when error is caught """
    def __init__(self, *args, **kwargs):
        code = kwargs.pop('code', 400)
        Exception.__init__(self)
        self.code = code

    def as_http_error(self):
        return Response(str(self), self.code)

然后使用

try:
    something()
catch FooException as ex:
    return ex.as_http_error()

【问题讨论】:

    标签: python exception flask


    【解决方案1】:

    最佳实践是创建您的自定义异常类,然后通过错误处理程序装饰器向 Flask 应用程序注册。您可以从业务逻辑引发自定义异常,然后允许 Flask 错误处理程序处理任何自定义定义的异常。 (在 Spring 中也是如此。)

    您可以使用如下装饰器并注册您的自定义异常。

    @app.errorhandler(FooException)
    def handle_foo_exception(error):
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response
    

    您可以在此处阅读更多信息Implementing API Exceptions

    【讨论】:

      猜你喜欢
      • 2011-09-22
      • 1970-01-01
      • 2019-10-03
      • 2019-07-12
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 2017-11-26
      相关资源
      最近更新 更多