python restful接口返回类型出错_Flask restful-自定义错误处理

我想为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'}

这可以很好地工作,但我想用烧瓶restful错误处理代替。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值