CBV加装饰器

x33g5p2x  于2022-03-11 转载在 其他  
字(0.8k)|赞(0)|评价(0)|浏览(211)


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 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

区别是加在post或者get方法上不需要写name参数,如果加在视图类上需要写name参数

相关文章

微信公众号

最新文章

更多