十九. Django-Cookie的CBV和FBV的用户验证装饰器

一. Cookie的CBV和FBV的用户验证装饰器

1. FBV模式

def cookie(func):  
    def deco(request,*args,**kwargs):    
        u = request.get_signed_cookie('username', salt='user', default=None)  
        if not u:  
            return render(request,'login.html')  
        return func(request,*args,**kwargs)  
    return deco  
  
@cookie  
def houtai(request):  
    u = request.get_signed_cookie('username',salt='user',default=None)  
    return render(request,'houtai.html',{'user':u})

2. CBV模式

from django.utils.decorators import method_decorator  
from django import views  
  
# @method_decorator(cookie,name='dispatch')    # dispatch的便捷写法  
class CBVtest(views.View):  
  
    @method_decorator(cookie)   # 给dispatch方法添加装饰器,那么下面所有的get,post都会添加  
    def dispatch(self, request, *args, **kwargs):  
        return super(CBVtest,self).dispatch(request,*args,**kwargs)  
  
    # @method_decorator(cookie)  
    def get(self,request):  
        u = request.get_signed_cookie('username',salt='user',default=None)  
        return render(request,'houtai.html',{'user':u})  
  
    def post(self,request):  
        return HttpResponse('post ok')

 

转载于:https://www.cnblogs.com/lovershowtime/p/11365841.html

你可能感兴趣的:(十九. Django-Cookie的CBV和FBV的用户验证装饰器)