在django如何给CBV添加装饰器?
在Django中,给CBV添加装饰器有几种方式?
在类视图中使用为函数视图准备的装饰器时,不能直接添加装饰器,需要使用method_decorator将其转换为适用于类视图方法的装饰器。
method_decorator装饰器使用name参数指明被装饰的方法
一、添加装饰器的方法
# urls.py
urlpatterns = [
path("login/",views.Mydecorator(views.MyView.as_view())),
]
# views.py
def Mydecorator(func):
def wrapper(*args,**kwargs):
print('你被装饰器装饰啦!')
res = func(*args,**kwargs)
return res
return wrapper
# @method_decorator(Mydecorator,name="post")
# @method_decorator(Mydecorator,name="get")
class MyView(View):
# @method_decorator(Mydecorator)
def get(self,request):
return HttpResponse("get请求")
def post(self,request):
return HttpResponse("post请求")
在url中进行添加装饰器。
二、添加装饰器的方法
def Mydecorator(func):
def wrapper(*args,**kwargs):
print('你被装饰器装饰啦!')
res = func(*args,**kwargs)
return res
return wrapper
@method_decorator(Mydecorator,name="post")
@method_decorator(Mydecorator,name="get")
class MyView(View):
# @method_decorator(Mydecorator)
def get(self,request):
return HttpResponse("get请求")
def post(self,request):
return HttpResponse("post请求")
通过装饰视图类,name="函数名称"。
三、添加装饰器的方法
如果需要为类视图的多个方法添加装饰器,但又不是所有的方法(为所有方法添加装饰器参考上面例子),也可以直接在需要添加装饰器的方法上使用method_decorator(就是为指定方法添加装饰器),如下所示:
def Mydecorator(func):
def wrapper(*args,**kwargs):
print('你被装饰器装饰啦!')
res = func(*args,**kwargs)
return res
return wrapper
# @method_decorator(Mydecorator,name="post")
# @method_decorator(Mydecorator,name="get")
class MyView(View):
@method_decorator(Mydecorator)
def get(self,request):
return HttpResponse("get请求")
def post(self,request):
return HttpResponse("post请求")
浙公网安备 33010602011771号