前言
HTTP协议 是短连接、且状态的,所以在客户端向服务端发起请求后,服务端在响应头 加入cokie响应给浏览器,以此客户端的状态;
cook是来自服务端,保存在浏览器的键值对,主要应用于用户登录;
cookie如此重要!!那么如何在Django应用cookie呢?
一、Django应用cookie
参数介绍
1、max_age=1 :cookie生效的时间,单位是秒
2、expires:具体过期日期
3、path=‘/‘:指定那个url可以访问到cookie;‘/’是所有; path=‘/‘
4、 domain=None(None代表当前域名):指定那个域名以及它下面的二级域名(子域名)可以访问这个cookie
5、secure=False:https安全相关
6、httponly=False:限制只能通过http传输,JS无法在传输中获取和修改
设置cookie
1.普通
obj.set_cookie("tile","zhanggen",expires=value,path=‘/‘ )
2.加盐
obj.set_signed_cookie(‘k‘,‘v‘,salt="zhangge")
获取cookie
1、普通
obj.set_signed_cookie(‘k‘,‘v‘,salt="zhangge")
2、加盐
cookies=request.get_signed_cookie(‘k‘,salt=‘zhanggen‘)
最后给每个视图函数装饰cookie认证功能
from until import mysqlhelper from django.shortcuts import HttpResponse,render,redirect import json import datetime from datetime import timedelta def cookie_auth(func): def weaper(request,*args,**kwargs): cookies = request.get_signed_cookie(‘k‘, salt=‘zhanggen‘) if cookies == ‘v‘: return func(request) else: return HttpResponse(‘OK‘) return weaper now = datetime.datetime.utcnow() delta = timedelta(seconds=10) def login(request): if request.method==‘GET‘: return render(request,‘login.html‘) else: name = request.POST.get(‘N‘) pwd=request.POST.get(‘P‘) if name=="alex" and pwd=="123": obj=redirect("/modal") # obj.set_cookie("tile","zhanggen",max_age=1,) value=now+delta obj.set_cookie("tile","zhanggen",expires=value,path=‘/‘,domain=None,secure=False,httponly=False) obj.set_signed_cookie(‘k‘,‘v‘,salt="zhanggen",) return obj else: return render(request,‘login.html‘) def test(request): return render(request,‘layout.html‘) @cookie_auth def modal(request): sql=‘‘‘ SELECT teacher.id as tid,teacher.`name`as tname,class.title FROM day64.teacher LEFT JOIN teacher_class ON day64.teacher.id=day64.teacher_class.tid LEFT JOIN day64.class ON day64.teacher_class.cid=day64.class.id; ‘‘‘ teacher_list= mysqlhelper.get_list(sql,[]) res={} for row in teacher_list: tid=row["tid"] if tid in res: res[tid]["titles"].append(row["title"]) else: res[tid]={‘tid‘:row["tid"],‘tname‘:row["tname"],‘titles‘:[row["title"],]} class_list=mysqlhelper.get_list("SELECT id ,title FROM day64.class" ,[]) return render(request,‘modal.html‘,{"list":res.values(),"class_list":class_list} )
时间: 2024-10-14 00:49:27