首页 > 其他 > 详细

装饰器执行顺序

时间:2021-01-14 17:09:27      阅读:24      评论:0      收藏:0      [点我收藏+]

堆叠装饰器执行顺序

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中间件执行顺序类似

 

装饰器执行顺序

原文:https://www.cnblogs.com/buxizhizhoum/p/14277613.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!