类视图装饰器

在类视图中使用为函数视图准备的装饰器时,不能直接添加装饰器,需要使用method_decorator将其转换为适用于类视图方法的装饰器

 方法一

#导入类视图装饰器包
from django.utils.decorators import method_decorator
#登录逻辑的装饰器
def login(func):
    def inner(request,*args,**kwargs):
        if not request.COOKIES.get('username'):
            return HttpResponseRedirect('/supermarket/login')
        return func(request,*args,**kwargs)
    return inner

#商品列表页    method_decorator装饰器使用name参数指明被装饰的方法
class Prolist(View):
    @method_decorator(login)
    def get(self,request):
        res = Product.objects.all()
        username = request.COOKIES.get('username',"未取到")
        #用户名解码
        try:
            username = username.encode("ISO-8859-1").decode("utf-8")
        except:
            pass
        # 解析模板
        return render(request,'supermarket/prolist.html',locals())

 方法二:

在路由中导入装饰器并用视图

path('/cartlist',login(CartList.as_view()))

原文地址:https://www.cnblogs.com/xcsg/p/10399015.html