为类视图添加装饰器,可以使用三种方法:
from django.utils.decorators import method_decorator # 在类试图中对函数进行添加装饰器使用
from django.views import View
# 为函数视图准备的装饰器
def my_decorator(function):
def wrapper(request,*args,**kwargs):
print(request.path)
print("装时期先执行")
return function(request)
return wrapper
方式一:
class DemoView(View):
# @method_decorator(my_decorator)
def get(self,request):
return HttpResponse("get")
def post(self,request):
return HttpResponse("Post")
在url中添加;
根据装饰器的原理;很好理解
# url(r"demoview/",views.my_decorator(views.DemoView.as_view()))
方式二:
在类视图中添加;根据类视图中所继承的view类的调用原理来重写dispatch可实现对全部请求添加装饰器
class DemoView(View):
# 重写dispatch
# @method_decorator(my_decorator)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request,*args,**kwargs)
def get(self,request):
return HttpResponse("get")
def post(self,request):
return HttpResponse("Post")
# 局部某个请求添加装饰器
class DemoView(View):
@method_decorator(my_decorator)
def get(self,request):
return HttpResponse("get")
def post(self,request):
return HttpResponse("Post")
方式三:
method_decorator装饰器还支持使用name参数指明被装饰的方法
# name 可指定父类的dispatch,也可指定为某个方法@method_decorator(my_decorator,name="get")
@method_decorator(my_decorator,name="dispatch")
class DemoView(View):
# 重写dispatch
# @method_decorator(my_decorator)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request,*args,**kwargs)
# @method_decorator(my_decorator)
def get(self,request):
return HttpResponse("get")
def post(self,request):
return HttpResponse("Post")
为什么需要使用method_decorator???
为函数视图准备的装饰器,其被调用时,第一个参数用于接收request对象
def my_decorate(func):
def wrapper(request, *args, **kwargs): # 第一个参数request对象
...代码省略...
return func(request, *args, **kwargs)
return wrapper
而类视图中请求方法被调用时,传入的第一个参数不是request对象,而是self 视图对象本身,第二个位置参数才是request对象
class DemoView(View):
def dispatch(self, request, *args, **kwargs):
...代码省略...
def get(self, request):
...代码省略...
所以如果直接将用于函数视图的装饰器装饰类视图方法,会导致参数传递出现问题。
method_decorator的作用是为函数视图装饰器补充第一个self参数,以适配类视图方法。
如果将装饰器本身改为可以适配类视图方法的,类似如下,则无需再使用method_decorator。
def my_decorator(func):
def wrapper(self, request, *args, **kwargs): # 此处增加了self
print('自定义装饰器被调用了')
print('请求路径%s' % request.path)
return func(self, request, *args, **kwargs) # 此处增加了self
return wrapper
顺颂商祺!
本文介绍了如何在Django的类视图中添加装饰器,详细讲解了三种不同的实现方法,帮助开发者更好地理解和运用类视图装饰器。

637

被折叠的 条评论
为什么被折叠?



