Cookie—客户端浏览器存储的一组键值对{key:value}
在django中cookie的用法:
1.cookie值获取:
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方法:
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进行操作
- javascript
- jQuery
1.javascript操作
document.cookie
略…..百度
2.jQuery操作
由于客户端操作cookie方式较为繁琐,我们可以下载网络上提供用于操作cookie的插件:jQueryCookie <script src="/static/js/jQuery.cookie.js> $.cookie("list_per_num,30,{path:'/'}); >
4.cookie之装饰器
装饰器解释:
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):
..........
装饰器之FBV
调用方式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()
装饰器之CBV
Original: https://www.cnblogs.com/wangxingwei/p/10750841.html
Author: 土味程序员
Title: django-cookie
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/601996/
转载文章受原作者版权保护。转载请注明原作者出处!