Pythoner集中营Flask实践python进阶

博客系列:flask-restful 中Resource封装方法

2018-08-20  本文已影响13人  我的昵称很霸气

flask-restful 不做果断解释

# 在flask_app>restful_api_manage中创建一个base.py
from flask import request
from flask_restful import Resource
# 同一错误集中处理
from common.error import AppError, NotFoundError, UnauthorizedError, ValidationError, ParaValidateFailError, \
    MoreValidationError, UnauthorizeError
# 统一方法返回的
from flask_app.restful_api_manage.hepler import error_response_default, unauthorized_response

class BaseErrorHandler(Resource):
    """
    注册错误管理机制
    get/post/delete/patch/put/head
    """
def base_error_check(handler, handler_func):
    def _check(*args, **kwargs):
        added_error_instances = (
        AppError, NotFoundError, UnauthorizedError, ValidationError, ParaValidateFailError, MoreValidationError)
        try:
            ret = handler_func(*args, **kwargs)
        except added_error_instances as e:
            code = getattr(e, "code", 500)
            code = 500 if code < 200 else code
            return error_response_default(handler, code, e.msg, e.error_code)
        else:
            return ret
    return _check

def __init__(self):
    if hasattr(self, 'get'):
        self.get = base_error_check(self, self.get)
    if hasattr(self, 'post'):
        self.post = base_error_check(self, self.post)
    if hasattr(self, 'delete'
        self.delete = base_error_check(self, self.delete)
    if hasattr(self, 'patch'):
        self.patch = base_error_check(self, self.patch)
    if hasattr(self, 'put'):
        self.put = base_error_check(self, self.put)
    if hasattr(self, 'head'):
        self.head = base_error_check(self, self.head)


class BaseModelHandler(BaseErrorHandler):
    def __init__(self):
        super(BaseModelleHandler, self).__init__()
上一篇下一篇

猜你喜欢

热点阅读