CBV和FBV用户认证装饰器

#在用户认证时的一个应用 
1
装饰器: 2 FBV: 3 def auth(func): 4 def inner(reqeust,*args,**kwargs): 5 v = reqeust.COOKIES.get('user') 6 if not v: 7 return redirect('/login') 8 return func(reqeust, *args,**kwargs) 9 return inner 10 11 CBV: 12 from django import views 13 from django.utils.decorators import method_decorator 14 15 @method_decorator(auth, name='dispatch') #也可以写到类上, 这样在get,post请求都可以省略, 也可以写在类里面方法上 16 class Order(views.View): 17 #@method_decorator(auth) 18 #def dispatch(self, request, *args, **kwargs): 19 #return super(Order, self).dispatch(request, *args, **kwargs) 20 21 #@method_decorator(auth): #只对get请求有效 22 def get(self, request): 23 v = request.COOKIE.get('username') 24 return render(request, 'index.html', {'current_user': v }) 25 26 def post(self, request): 27 v = request.COOKIE.get('username') 28 return render(request, 'index.html', {'current_user': v })

 

posted @ 2017-06-07 14:03  ixiaosong  阅读(526)  评论(0编辑  收藏  举报