Flask-restful-自定义错误处理 [英] Flask-restful - Custom error handling

查看:496
本文介绍了Flask-restful-自定义错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为Flask-restful API定义自定义错误处理.

I want to define custom error handling for a Flask-restful API.

文档此处将执行以下操作:

errors = {
    'UserAlreadyExistsError': {
        'message': "A user with that username already exists.",
        'status': 409,
    },
    'ResourceDoesNotExist': {
        'message': "A resource with that ID no longer exists.",
        'status': 410,
        'extra': "Any extra information you want.",
    },
}
app = Flask(__name__)
api = flask_restful.Api(app, errors=errors)

现在,我发现这种格式非常吸引人,但是当发生某些异常时,我需要指定更多参数.例如,遇到ResourceDoesNotExist时,我要指定什么id不存在.

Now I find this format pretty attractive but I need to specify more parameters when some exception happens. For example, when encountering ResourceDoesNotExist, I want to specify what id does not exist.

当前,我正在执行以下操作:

Currently, I'm doing the following:

app = Flask(__name__)
api = flask_restful.Api(app)


class APIException(Exception):
    def __init__(self, code, message):
        self._code = code
        self._message = message

    @property
    def code(self):
        return self._code

    @property
    def message(self):
        return self._message

    def __str__(self):
        return self.__class__.__name__ + ': ' + self.message


class ResourceDoesNotExist(APIException):
    """Custom exception when resource is not found."""
    def __init__(self, model_name, id):
        message = 'Resource {} {} not found'.format(model_name.title(), id)
        super(ResourceNotFound, self).__init__(404, message)


class MyResource(Resource):
    def get(self, id):
        try:
            model = MyModel.get(id)
            if not model:
               raise ResourceNotFound(MyModel.__name__, id)
        except APIException as e:
            abort(e.code, str(e))

当使用不存在的ID调用时MyResource将返回以下JSON:

When called with an id that doesn't exist MyResource will return the following JSON:

{'message': 'ResourceDoesNotExist: Resource MyModel 5 not found'}

这很好用,但我想改用Flask-restful错误处理.

This works fine but I'd like to use to Flask-restful error handling instead.

推荐答案

根据文档

Flask-RESTful将在Flask-RESTful路由上发生的任何400或500错误上调用handle_error()函数,并保持其他路由不变.

Flask-RESTful will call the handle_error() function on any 400 or 500 error that happens on a Flask-RESTful route, and leave other routes alone.

您可以利用它来实现所需的功能.唯一的缺点是必须创建自定义Api.

You can leverage this to implement the required functionality. The only downside is having to create a custom Api.

class CustomApi(flask_restful.Api):

    def handle_error(self, e):
        flask_restful.abort(e.code, str(e))

如果保留定义的异常,则当发生异常时,您将获得与

If you keep your defined exceptions, when an exception occurs, you'll get the same behaviour as

class MyResource(Resource):
    def get(self, id):
        try:
            model = MyModel.get(id)
            if not model:
               raise ResourceNotFound(MyModel.__name__, id)
        except APIException as e:
            abort(e.code, str(e))

这篇关于Flask-restful-自定义错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆