简体   繁体   English

实现API异常烧瓶式

[英]Implementing API exception flask-restful

I am trying to catch the Exception which is raised when the url provided is a messy and wrong url and then return the error response as JSON. 我正在尝试捕获当提供的URL是一个混乱且错误的URL时引发的异常,然后将错误响应作为JSON返回。 This is what i did to implement this logic. 这就是我为实现此逻辑所做的事情。

The exception is raised inside the Analysis class when the key_id is not a valid key for S3. key_id不是S3的有效键时,在Analysis类内引发异常。

def url_error(status_code, message, reason):
    response = jsonify({
        'status': status_code,
        'message': message,
        'reason': reason
    })
    response.status_code = status_code
    return response


class RowColumnCount(Resource):
    def get(self, key_id):
        try:
            rc = Analysis(key_id=key_id)
        except S3ResponseError as e:
            return url_error(e.status, e.message, e.reason)
        json_response = json.loads(rc.count_rows_columns())
        return json_response

The above code works fine but its kinda getting repetitive for 50 different Resource classes. 上面的代码可以正常工作,但是对于50种不同的Resource类来说,它有点重复。 Each Resource class should handle this specific error. 每个Resource类都应处理此特定错误。 How to make it a decorator, such that code repetitiveness is reduced. 如何使其成为装饰器,以减少代码重复性。

I am using Flask, Flask-Restful, Python 3.4.3 我正在使用Flask,Flask-Restful,Python 3.4.3

There are a couple of ways you can achieve what you're trying to do but I think the cleanest way is to extend the Resource class as described in the Flask-Restful docs here and create a new decorator whose job is to catch the S3ResponseError and return the appropriate response. 有两种方法可以实现您要执行的操作,但是我认为最干净的方法是按照此处 Flask-Restful文档中的描述扩展Resource类,并创建一个新的装饰器,其工作是捕获S3ResponseError和返回适当的响应。 You can then subclass all your resources from your new base Resource class. 然后,您可以从新的基本Resource类继承所有资源。

Also I would suggest you specify an API level json_output method as described here and here so that way all you have to do is return a dict from any of your resources and they'll be converted to JSON appropriately. 我也建议您指定一个API级别的json_output方法,如此此处所述,这样您要做的就是从任何资源中返回一个字典,并将它们适当地转换为JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM