【发布时间】:2017-04-30 04:26:34
【问题描述】:
我想为 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 错误处理。
【问题讨论】:
标签: python flask flask-restful