首页 > 其他 > 详细

记一次Django中cookie的应用

时间:2019-11-05 19:10:03      阅读:98      评论:0      收藏:0      [点我收藏+]

cookie介绍

  因为HTTP协议是无状态的,它的执行情况与执行结果和前面或后面的请求都没有直接关系,而服务器和浏览器会话会产生一些数据,这些数据是需要我们保存的,但是因为HTTP协议的特性,这写数据不会被保存,由此便诞生了cookie,用来帮助我们保持状态,也就是保存一些数据。

  cookie也就是一小段信息,它是服务器发出保存在浏览器本地的一组组键值对,下次浏览器再访问服务器时,便会携带这些信息,服务器可从中提取有用信息

使用实例

  一个登陆的小例子,用户在未登陆时访问index页面便会跳转至登陆界面,登录后访问便会携带cookie,服务器提取到信息便可以直接访问

 1 def check_login(func):
 2     @wraps(func)
 3     def inner(request,*args,**kwargs):
 4         if request.COOKIES.get(_login) == yes:
 5             return func(request,*args,**kwargs)
 6         else:
 7             return redirect(f/login/?before_url={request.path_info})
 8     return inner
 9 
10 
11 
12 def login(request):
13     if request.method == GET:
14         return render(request,login.html)
15     elif request.method == POST:
16         user = request.POST.get(user)
17         password = request.POST.get(password)
18 
19         if user == baoyuan and password == baoyuan123:
20             nexturl = request.GET.get(before_url)
21             if nexturl:
22                 ret = redirect(nexturl)
23                 ret.set_cookie(_login,yes)
24                 return ret
25             else:
26                 ret = redirect(/index/)
27                 ret.set_cookie(_login,yes)
28                 return ret
29         else:
30             return render(request,login.html,{error:用户名或密码错误})
31 
32 @check_login
33 def index(request):
34     return render(request,index.html)
35 
36 @check_login
37 def personal_info(request):
38     return render(request,personal_info.html)

 

记一次Django中cookie的应用

原文:https://www.cnblogs.com/laycare/p/11800443.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!