FBV装饰器:
def auth(func): #装饰器函数 def inner(request, *args, **kwargs): v = request.COOKIES.get(‘username‘) if not v: return redirect(‘/log/‘) return func(request, *args, **kwargs) return inner
使用方法:
在函数上加上@auth
CBV装饰器:
第一种方式:利用django自带的工具
def auth(func): #装饰器函数 对cookie进行认证 def inner(request, *args, **kwargs): v = request.COOKIES.get(‘username‘) if not v: return redirect(‘/log/‘) return func(request, *args, **kwargs) return inner from django import views from django.utils.decorators import method_decorator #导入django自带的工具 class Auth(views.View): @method_decorator(auth) #利用django自带工具 导入认证函数装饰器进行认证,灵活的放在任意需要认证的函数下面 def get(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v}) def post(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v})
第二种方式:
from django import views from django.utils.decorators import method_decorator class Auth(views.View): @method_decorator(auth) #将装饰器放在父类方法上 这样该类下所有方法都被装饰上了装饰器,不用一一在写在函数上面 def dispatch(self, request, *args, **kwargs): return super(Auth, self).dispatch(self, request, *args, **kwargs) def get(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v}) def post(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v})
第三种方式:
from django import views from django.utils.decorators import method_decorator @method_decorator(auth, name=‘dispatch‘) #将装饰器直接装饰在类上面,在用name指定装饰在父类的diapatch方法上,这样也就实现了类里面所有方法的装饰效果 class Auth(views.View): def get(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v}) def post(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v})
时间: 2024-11-08 12:26:38