38 CBV添加装饰器的三种方式

 

 

CBV如何添加装饰器

CBV中django不建议你直接给类的方法加装饰器

无论该装饰器能都正常工作 都不建议直接加

方式一:指名道姓

from django.views import View
from django.utils.decorators import method_decorator

class MyLogin(View):
    @method_decorator(login_auth)  # 方式1:指名道姓
    def get(self,request):
        return HttpResponse("get请求")

    def post(self,request):
        return HttpResponse('post请求')

方式二:可以添加多个针对不同的方法加不同的装饰器

from django.views import View
from django.utils.decorators import method_decorator


# @method_decorator(login_auth,name='get')  # 方式2(可以添加多个针对不同的方法加不同的装饰器)
# @method_decorator(login_auth,name='post')
class MyLogin(View):

    def get(self,request):
        return HttpResponse("get请求")

    def post(self,request):
        return HttpResponse('post请求')

方式三:会直接作用于当前类里面的所有的方法

from django.views import View
from django.utils.decorators import method_decorator

class MyLogin(View):
    @method_decorator(login_auth)  # 方式3:它会直接作用于当前类里面的所有的方法
    def dispatch(self, request, *args, **kwargs):
         """
         看CBV源码可以得出 CBV里面所有的方法在执行之前都需要先经过
          dispatch方法(该方法你可以看成是一个分发方法)
        """
        return super().dispatch(request,*args,**kwargs)

    def get(self,request):
        return HttpResponse("get请求")

    def post(self,request):
        return HttpResponse('post请求')

 

posted @ 2021-12-07 19:07  甜甜de微笑  阅读(34)  评论(0编辑  收藏  举报