|
# CBV如何添加装饰器
from django.views import View
from django.utils.decorators import method_decorator
"""
CBV中不建议你直接给类的方法加装饰器
无论该装饰器是否正常 都不建议直接加
"""
[@method_decorator(login_auth,name='get')# 方式2(可以添加多个针对不同的方法加不同的装饰器),可以加多个
@method_decorator(login_auth,name='post')]
class MyLogin(View):
[@method_decorator(login_auth) # 方式3:他会直接作用于当前类里面所有的方法]
def dispatch(self, request, *args, **kwargs):
pass
[# @method_decorator(login_auth) # 方式1 指名道姓]
def get(self,reqeust):
return HttpResponse('get请求')
def post(self,request):
return HttpResponse('post请求')
1、在CBV中Django中不允许我们直接加的,加了也会报错的,需要导入一个模块 from django.utils.decorator import method_decorator
2、①第一种用法是指名道姓给某一个方法装,括号里面要写装饰器的名字,拓展性不强 @method_decorator(login_auth) def get(self,reqeust): return HttpResponse('get请求')
②第二种是在类上面加装饰器: @method_decorator(login_auth,name='get') 可以只当给类下面的某一个方法装,拓展性变强了,可以有多个装饰器装多个方法
@method_decorator(login_auth,name='post')
③第三种在dispatch上装:在我们CBV源码中本质上的是通过self.dispatch方法的,只是我们自己没有找的父类去的,那这个时候我们可以把源码的dispatch的这个方法,自己建一个 这样加上装饰器,所有的都会统一使用一个装饰器了 [@method_decorator(login_auth) # 方式3:他会直接作用于当前类里面所有的方法]
def dispatch(self, request, *args, **kwargs):
pass
|
|
|