CBV加装饰器
CBV加装饰器
我们知道在函数上如何加装饰器,那么在类上如何加装饰器呢?
下面写一个登录校验示例:
导入:from django.utils.decorators import method_decorator
'''装饰器'''
def auth(func):
def inner(request,*args, **kwargs):
#登录校验
if request.session.get('is_login'): # 通过获取is_login来判断是否登录
res = func(*args, **kwargs) # 装饰器核心,接收参数,返回值
return res
else:
return redirect('/login') # 校验成功重定向到login
return inner # 必须返回inner
from django.views import View
from django.utils.decorators import method_decorator
@method_decorator(auth,name='get') #给get请求加装饰器,还可以给post加
class Index(View):
@method_decorator(auth)
def dispatch(self,request,*args,**kwargs):
return super().dispatch(request,*args,**kwargs)
# @method_decorator(auth)
def get(self, request, *args, **kwargs):
return HttpResponse('index')
def post(self, request, *args, **kwargs):
return HttpResponse('post_index')
总结
1-cbv加装饰器可以加在类上:
@method_decorator(auth,name='post') # 给post请求加装饰器
2-可以加在方法上:
@method_decorator(auth)
def get(self, request, *args, **kwargs):
pass
3-加在方法和类上
@method_decorator(auth,name='get')
class Index(View):
@method_decorator(auth)
def dispatch(self,request,*args,**kwargs):
return super().dispatch(request,*args,**kwargs)
区别是加在post或者get方法上不需要写name参数,如果加在视图类上需要写name参数,共三种方式