Cookie---客户端浏览器存储的一组键值对{key:value}javascript
在django中cookie的用法:html
1.cookie值获取:java
request.COOKIE是一个字典 request.COOKIE['name'] request.COOKIE.get('name') for k,v in request.COOKIE.items(): print(k,v) print(request.COOKIE.keys()) print(request.COOKIE.values())
2.在服务器端,操做cookie方法:django
name = request.POST.get("name") res = render(request,”login.html“) res = redirect(”/login“) #设置cookie res.set_cookie("name",name)#设置cookie res.set_cookie("name",name,max_age=10)#设置cookie超时时间 res.set_signed_cookie(key,value,salt="dandnao")#加盐操做 return res #获取cookie v = request.get_signed_cookie(key,salt="dandnao")#获取cookie 注意:使用上述方法时,若是没有设置默认值,当获取不到cookie时,系统会出异常,为了解决此问题,咱们能够设置默认值,defautl=None,无此cookie返回none cookie参数: max_age = none,设置超时时间,时间单位为s expires = none,设置超时日期 example: import time current_time = datetime.datetime.utctime() current_time = current_time+datetime.timedelta(second=5) expires = current_time path:'/'#cookie生效路径,'/'表示任何url均可以访问 domain =none #cookie生效域名 secure =False,https传输 httponly = False,只能http传输,没法被javascript抓取
3.cookie保存于客户端,因此经过客户端也能够对cookie进行操做浏览器
1.javascript操做服务器
document.cookiecookie
略.....百度网络
2.jQuery操做dom
因为客户端操做cookie方式较为繁琐,咱们能够下载网络上提供用于操做cookie的插件:jQueryCookie <script src="/static/js/jQuery.cookie.js> $.cookie("list_per_num,30,{path:'/'}); </script>
4.cookie之装饰器ide
装饰器解释: def auth(func): def inner(request,*args,**kwargs): start=datetime.time() return func(request,*args,**kwargs) end = datetime.time()-start print('函数执行时间',end) return inner
调用方式1
@auth == 》index=auth(index) 返回的是index的内存地址,参数能够放置在第二层以后。。。。。 装置器之FBV: @auth def index(request): ..........
调用方式2
#须要导如jango为咱们提供的装饰模块 from django.utils.decorators import method_decorator from jango import views @method_decorator(auth,'dispatch') class index(views.View): @method_decorator(auth) def dispatch(self, request, *args, **kwargs): result = super(inidnao, self).dispatch(request, *args, **kwargs) return result @method_decorator(auth) def get(self,request): ....... def post(self,request) #注意:class 须要再urls中,views.index.as_views()