堆叠装饰器执行顺序

def create_response(func):
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        print(2)
        print(*args, **kwargs)
        resp = func(self, *args, **kwargs)
        print(3)
        # convert response of data service to the skynet format
        # status_code = resp.status_code
        if hasattr(resp, "status_code") and resp.status_code in (200, 201):
            content = resp.content
            return ParseResponse(content).response()
        else:
            return MyResponse(
                status_code=-1, data=resp, message=resp).fail()
    return wrapper


def process_log_id(func):
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        print(1)
        headers = request.headers
        log_id = headers.get(HEADER_LOG_ID)
        if log_id:
            setattr(self, "log_id", log_id)
        resp = func(self, *args, **kwargs)
        print(4)
        if hasattr(self, "log_id"):
            log_id = getattr(self, "log_id")
            resp.headers[HEADER_LOG_ID] = log_id
        return resp
    return wrapper


@process_log_id
def test():
print("test")

>>> 1 2 3 4
和django中间件执行顺序类似

 

posted on 2021-01-14 15:42  Go_Forward  阅读(88)  评论(0编辑  收藏  举报