郑统京 发表于 2022-11-3 00:42:20

Djangp中的CBV如何添加装饰器

# 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      

郑统京 发表于 2022-11-4 00:10:48

第三种在dispatch需要补充一下代码要继承之前的父类的方法super().dispatch

[第三种来自CBV源码dispatch]CBV里面所有的方法在执行之气那都需要经过dispatch方法(可以看成是一个路由分发概率)
class MyCBV(View):
    @method_decorator(login_auth)
    def dispatch(self,request,*args,**kwargs)
      super().dispatch(self,request,*args,**kwargs)
页: [1]
查看完整版本: Djangp中的CBV如何添加装饰器