Django之Cookie
Cookie是保存在浏览器端(客户端)的一个键值对
request.Cookies
服务端可以向用户浏览器写Cookies
客户端每次发请求时,会携带cookies去
Cookies在请求头中。key = value
Cookies签名:
obj.set_signed_cookie( ‘ticket‘,"123123",salt = "jjjjjjjj" ) # salt是签名加密。
set_cookie:
key:
value:‘ ‘,
max_age=None,
expires=None,
path=‘/‘,
domain=None,
secure=False,
httponly=False 只能自http请求中传入,js代码无法获取。
例子:
import datetime from datetime import timedate def login(request): if request.mothed == "GET": return render(request,‘login.html‘) else: user = request.POST.get("username") pwd = request.POST.get("password") if user=="wang" and pwd=="123": obj=redirect(‘/classes/‘) ct = datetime.datetime.utcnow() v= datetime(seconds=10) value = ct + v obj.set_signed_cookie(‘ticket‘,"123123",salt="jjjjjjjjj") #回写cookie,123123是cookie的value, return obj else: return render(request,"login.html")
回写的cookie在响应头中,set_cookie( Requset Headers )
在def classes 中,验证cookie
def classes(request): #去请求中的cookie中找凭证 #tk = request.COOKIES.get(‘ticket‘) tk = request.get_signed_cookie(‘ticket‘,salt=‘jjjjj‘) #取cookie print(tk) if not tk: return redirect(‘/login/‘)
Cookie 可以设置超时时间,(max_age) 单位是秒
set_cookie(‘ticket‘,"123123",max_age=22) #max_age是cookie只存在多久,过时间自行消失