CBV添加装饰器方法

视具体情况而定的装饰器
def jump_auto(func):
    def inner(*args, **kwargs):
        res = func(*args, **kwargs)
        return res
        return inner 

1、加在CBV视图的get或post方法上

from django.views import view
from django.utils import method_decorator

class MyLogin(View):
    @method_decorator(jump_auto)
    def get(self, request):
        return HttpResponse('get请求')
    
    @method_decorator(jump_auto)
    def post(self, request):
            return HttpResponse('post请求')    

2、 直接加在视图类上,但method_decorator必须传 name 关键字参数

如果get方法和post方法都需要登录校验的话就写两个装饰器

from django.views import view
from django.utils import method_decorator

@method_decorator(jump_auto1,name='get')
@method_decorator(jump_auto2,name='post')
class MyLogin(View):
    def get(self, request):
        return HttpResponse('get请求')
        
    def get(self, request):
            return HttpResponse('post请求')

3、加在dispatch方法上

from django.views import view
from django.utils import method_decorator

class MyLogin(View):
    # 这种直接作用于当前类里面所有方法
    # 因为CBV源码执行之前都需经过dispatch方法
    @method_decorator(jump_auto)
    def dispatch(self, *args, **kwargs):
        pass
    
    def get(self, request):
        return HttpResponse('get请求')
        
    def get(self, request):
            return HttpResponse('post请求')

 

posted @ 2022-11-20 17:09  weer-wmq  阅读(13)  评论(0编辑  收藏  举报