gpt4 book ai didi

python - Flask-restful - 自定义错误处理

转载 作者:太空狗 更新时间:2023-10-30 02:08:45 37 4
gpt4 key购买 nike

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

文档中建议的方法 here就是做以下事情:

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不存在。

目前,我正在做以下事情:

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:

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

这工作正常,但我想改为使用 Flask-restful 错误处理。

最佳答案

根据 the docs

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。

class CustomApi(flask_restful.Api):

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

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

相同的行为
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))

关于python - Flask-restful - 自定义错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41149409/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com