django 使用装饰器验证用户登陆
使用装饰器验证用户登陆,需要使用@method_decorator
首先需引用,method_decorator,并定义一个闭包
from django.utils.decorators import method_decorator def checkLogin(func): def wrapper(request,*args,**kwargs): is_login=request.session.get('IS_LOGIN',False) if is_login: return func(request,*args,**kwargs) else: return redirect('/Index/') return wrapper
登陆页面的定义如下例子:
class Login(View): def get(self,request): return render(request,'index.html') def post(self,request): username=request.POST.get('username') user_list=Hbuser.objects.filter(username=username).first() if user_list: request.session['IS_LOGIN']=True request.session['uname']=user_list.username else: request.session.flush() return redirect('/Index/') return redirect('/Home/')
装饰器的使用方法如下,下面是对整个类实用装饰器
@method_decorator(checkLogin,name='dispatch') class Home(View): def get(self,request): return HttpResponse('OK')