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})
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/zhuifeng-mayi/p/9067121.html
时间: 2024-10-10 16:11:20