1.获取Cookie
request.COOKIES request.COOKIES['key'] # 获取带签名的cookie request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None) #获取signed类型cookies default: 默认值 salt: 加密盐 max_age: 后台控制过期时间
2.设置Cookie
rep = HttpResponse(...) rep = render(request, ...) rep.set_cookie(key,value,...) # 带签名的cookie rep.set_signed_cookie(key,value,salt='加密盐', max_age=None, ...) return rep 参数: key, 键 value='', 值 max_age=None, 超时时间 expires=None, 超时时间(IE requires expires, so set it if hasn't been already.) path='/', Cookie生效的路径,/ 表示根路径,特殊的:根路径的cookie可以被任何url的页面访问 domain=None, Cookie生效的域名 secure=False, https传输 httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)
3.删除Cookie
def logout(request): rep = redirect("/login/") rep.delete_cookie("user") # 删除用户浏览器上之前设置的usercookie值,实质是将浏览器的cookies清空 return rep
4.django中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')
5.登录认证示例:
def login_auth(func): def inner(request,*args,**kwargs): is_login = request.COOKIES.get('is_login') print(is_login) if is_login == 'True': res = func(request,*args,**kwargs) print('##############################') return res else: return redirect('login') return inner @login_auth def index(request): return render(request, 'cookies/index.html') @login_auth def home(request): return render(request, 'cookies/home.html') def login(request): if request.method == 'GET': return render(request, 'cookies/login.html') else: username = request.POST.get('username') password = request.POST.get('password') if username == 'bge' and password == '666': path = request.GET.get('returnurl') if path: ret = redirect(path}) else ret = redirect('index') ret.set_cookie('is_login',True) return ret else: return HttpResponse('登录失败')
标签:cookies,set,return,入门,request,Django,cookie,key,login From: https://www.cnblogs.com/panwenbin-logs/p/16631773.html