method_decorator的作用 以及不用method_decorator为装饰器添加self

method_decorator的作用是为函数视图装饰器补充第一个self参数,以适配类视图方法。

如果将装饰器本身改为可以适配类视图方法的,类似如下,则无需再使用method_decorator。

def my_decorator(view_func):
    def wrapper(request, *args, **kwargs):
        print('装饰器被调用')
        print(request.path)
        return view_func(request, *args, **kwargs)
    return wrapper


# method_decorator的作用是为函数视图装饰器补充第一个self参数,以适配类视图方法。
@method_decorator(my_decorator, name='dispatch')
class DemoView(View):

    def get(self, request):
        return HttpResponse('get page')

    def post(self, request):
        return HttpResponse('post page')

改为

def my_decorator(view_func):
    def wrapper(self, request, *args, **kwargs):
        print('装饰器被调用')
        print(request.path)
        return view_func(self, request, *args, **kwargs)
    return wrapper
    
@my_decorator
class DemoView(View):

    def get(self, request):
        return HttpResponse('get page')
	
    def post(self, request):
        return HttpResponse('post page')

你可能感兴趣的:(method_decorator的作用 以及不用method_decorator为装饰器添加self)