Cookie
在浏览器端(客户端)保存的键值对,特性:每次http请求都会携带. 举个例子:{"name":身份证号}
1丶获取cookie
request.COOKIE['key'] request.get_signed_cookie(key,default=RAISE_ERROR,salt='',max_age=None) 参数: default:默认值 salt:加密盐 max_age:后台控制过期时间
2丶设置Cookie
def cook2(request): prnt(request.COOKIES) #print(request.get_signed_cookie('k2',None,salt='uuu')) #rep = HttpResponse('ok') #rep.set_cookie('k1',123) #rep.set_signed_cookie('k2',666,salt='uuu') rep = HttpResponse('ok') return rep
3丶Cookie的参数
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.)支持datetime,时间戳time.time这两种 path='/', Cookie生效的路径,/ 表示跟路径,特殊的:根路径的cookie可以被任何url的页面访问 domain=None, Cookie生效的域名 secure=False, https传输 httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对的,底层抓包可以获取到也可以被覆盖)
例子:
def cook1(request): #print(request.COOKIES) #获取所有的Cookie #print(request.get_signed_cookie('k2',None,salt='uuu')) #rep = HttpResponse('ok') #rep.set_cookie('k1',123) #设置Cookie #rep.set_signed_cookie('k2',666,salt='uuu') #签名的cookie,salt为加密盐 rep = HttpResponse('cook1') rep.set_cookie('k999',123,path='/cookie1/') #path是cookie生效的路径(局部的);/表示根路径,特殊的;根路径的cookie可以被任何url的页面访问 rep.set_cookie('k888',123) #全局的cookie return rep
由于cookie保存在客户端的电脑上,所以,JavaScript和Jquery也可以操作cookie.
<script src='/static/js/jquery.cookie.js'></script>
$.cookie('list_pager_num',30,{path:'/'});