cookie是在客户端的键值对
# 0 会话跟踪,会话保持
# 1 cookie规范
-记住:当前网站在浏览器上cookie个数和大小有限制
-Cookie大小上限为4KB;
-一个服务器最多在客户端浏览器上保存20个Cookie;
-一个浏览器最多保存300个Cookie;
# 2 django中操作cookie
-增:obj.set_cookie('key','value')
-删: obj.delete_cookie('key') # 设置过期
-查: request.COOKIES.get('key')
-改: obj.set_cookie('key','value1')
# 3 带签名的cookie(加盐,加密)
-增:obj.set_signed_cookie('name','lqz','123')
-删: obj.delete_cookie('name') # 设置过期
-查: request.get_signed_cookie('name',salt='123')
-改: obj.set_signed_cookie('name','lqz','123')
2 cookie版登陆校验例
路由:
# cookie版登录 path('login/', views.login), path('order/', views.order), path('logout/', views.logout), path('userinfo/', views.userinfo),
视图函数:
## 登录认证装饰器 def login_auth(func): def inner(request, *args, **kwargs): # 登录校验 name = request.COOKIES.get('name') if name: res = func(request, *args, **kwargs) return res else: path = request.get_full_path() return redirect('/login/?returnUrl=%s' % path) return inner ### cookie版登录 def login(request): if request.method == 'GET': return render(request, 'login.html') else: name = request.POST.get('name') password = request.POST.get('password') if name == 'lqz' and password == '123': # 写入cookie # 登录成功,重定向 path = request.GET.get('returnUrl') if path: obj = redirect(path) else: obj = redirect('/index/') obj.set_cookie('name', name) return obj else: return HttpResponse('用户名或密码错误') # def order(request): # name = request.COOKIES.get('name') # if name: # return render(request,'order.html') # else: # return redirect('/login') ## 装饰器版本(只要加了装饰器,一旦进入这个视图函数,就表明登录成了) @login_auth def order(request): return render(request, 'order.html') @login_auth def userinfo(request): return render(request, 'userinfo.html') def logout(request): obj = HttpResponse('退出登录成功') obj.delete_cookie('name') return obj
模板:login.html:
<form action="" method="post"> <p>用户名:<input type="text" name="name"></p> <p>密码:<input type="password" name="password"></p> <p><input type="submit" value="提交"></p> </form>
order.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/logout/">点我退出</a> </body> </html>
userinfo.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户信息页面</h1> </body> </html>
标签:obj,name,request,django,cookie,使用,return,login From: https://www.cnblogs.com/97zs/p/17914254.html