目的
当用户登录时注册COOKIE,COOKIE值有两个---id和u_name(自定义,使用唯一值),用于之后的验证
当展示index页面时进行cookie验证,成功的进入index页面,否则返回登录
当退出登录时删除COOKIE
登录时注册COOKIE
def login(request):
u_name=request.GET.get("u_name")
u_pwd=request.GET.get("u_pwd")
if u_name:
user = User.objects.filter(u_name=u_name).first()
u_pwd=hashPwd(u_pwd)
if user and u_pwd == user.u_pwd:
response = redirect('/bk/index/')
response.set_cookie('u_name',u_name) #设置COOKIE
response.set_cookie('id',user.id) #设置COOKIE
return response
return render(request,'bk_management/login.html')
编写验证函数
因为日后可能还要在不同时期验证COOKIE,所以将验证COOKIE编写为类装饰器
def loginVaild(fun):
def inner(request,*args,**kwargs):
u_name=request.COOKIES.get('u_name')
id = request.COOKIES.get('id')
user = User.objects.filter(u_name=u_name,id=id).first()
if user:
return fun(request,*args,**kwargs)
else:
return redirect('/bk/login/')
return inner
主界面展示时验证COOKIE
@loginVaild
#主界面
def index(request):
return render(request,'bk_management/index.html')
退出登录时,删除COOKIE
def exit(request):
response = redirect('/bk/login/')
response.delete_cookie('id')
response.delete_cookie('u_name')
return response