cookie是什么?
- 保存在浏览器端“键值对”
- 服务端可以向用户浏览器端写cookie
- 客户端每次发请求时,会携带cookie去
应用场景:
- 投票
- 用户登录
1、获取Cookie:
request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None) 参数: default: 默认值 salt: 加密盐 max_age: 后台控制过期时间
2、设置Cookie:
rep = HttpResponse(...) 或 rep = render(request, ...) rep.set_cookie(key,value,...) rep.set_signed_cookie(key,value,salt='加密盐',...) 参数: 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获取(不是绝对,底层抓包可以获取到也可以被覆盖)
set_cookie源码:
def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False):
由于cookie保存在客户端的电脑上,所以,JavaScript和jquery也可以操作cookie。
<script src='http://t.zoukankan.com/static/js/jquery.cookie.js'></script> $.cookie("list_pager_num", 30,{ path: '/' });
#urls.py url(r'^login/', views.login), url(r'^index/', views.index), #views.py from django.shortcuts import render,redirect,HttpResponse def login(request): if request.method == "GET": return render(request,'login.html') else: user = request.POST.get("username") pwd = request.POST.get("password") print(user,pwd) if user == "alex" and pwd == "123": obj = redirect('/index/') obj.set_cookie('ticket','sdlfkjlakjfdlkfjdkljf') return obj else: return render(request,'login.html') def index(request): # 去请求的cookie中找凭证 tk = request.COOKIES.get("ticket") if not tk: return redirect('/login/') return render(request,'index.html') #login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="/login/"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit" value="提交"> </form> </body> </html> #index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>Welcome Pythoner!!!</p> </body> </html>
max_age和expires的区别: max_age=None, 超时时间【推荐】 # obj.set_cookie('ticket','sdlfkjlak',max_age=10) expires=None, 超时时间(需要调用datetime模板进行设置) #import datetime #from datetime import timedelta #ct = datetime.datetime.utcnow() #v = timedelta(seconds=10) #value = ct + v #obj.set_cookie('ticket','sdlfkjlak',expires=value)
#urls.py url(r'^li1/', views.li1), url(r'^li2/', views.li2), #views.py "path的使用" def li1(request): print(request.COOKIES) obj = HttpResponse('OK') obj.set_cookie('k2','v2',path='/li1') return obj def li2(request): print(request.COOKIES) obj = HttpResponse('OK') return obj #只有li1能获取k2
签名:
- cookie签名
- 自定义签名
#urls.py url(r'^login/', views.login), url(r'^index/', views.index), #views.py from django.shortcuts import render,redirect,HttpResponse def login(request): if request.method == "GET": return render(request,'login.html') else: user = request.POST.get("username") pwd = request.POST.get("password") print(user,pwd) if user == "alex" and pwd == "123": obj = redirect('/index/') import datetime from datetime import timedelta ct = datetime.datetime.utcnow() v = timedelta(seconds=10) value = ct + v # obj.set_cookie('ticket','sdlfkjlak',max_age=10) obj.set_signed_cookie('ticket','123123',salt='ppppppp') # obj.set_cookie('ticket','sdlfkjlak',expires=value) return obj else: return render(request,'login.html') def index(request): # 去请求的cookie中找凭证 tk = request.get_signed_cookie("ticket",salt='ppppppp') print(tk) if not tk: return redirect('/login/') return render(request,'index.html') #index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>Welcome Pythoner!!!</p> </body> </html> #login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="/login/"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit" value="提交"> </form> </body> </html>
#settings.py #SIGNING_BACKEND就相当于TimestampSigner SIGNING_BACKEND ="c1.MySigner" #c1.py from django.core.signing import TimestampSigner class MySigner(TimestampSigner): #加签名 def sign(self, value): return value+'123123123' #去签名 def unsign(self, value, max_age=None): v = value[0:-8] return v