Day71 分页,cookie and Session

时间:2023-03-08 21:14:23
  • cookie 是保存在客户端的键值对.

  • cookie本身最大支持4096字节,保存在客户端的

  • session是保存在服务器端的键值对.(依赖cookie)

Day71 分页,cookie and Session

cookie和session

cookie的由来?

因为http请求是没有状态的,每一次请求都是独立的(对于服务端来说,一切都是只如初见!)

cookie 是什么?

就是保存在浏览器上的键值对。

cookie的应用

1.登录、七天免登录

2. 记录用户的浏览习惯.

3.简单的投票限制。

Day71 分页,cookie and Session

Day71 分页,cookie and Session

Day71 分页,cookie and Session

Day71 分页,cookie and Session

Day71 分页,cookie and Session

cookie 默认关闭浏览器 就消失了。。。

Day71 分页,cookie and Session

Day71 分页,cookie and Session

session

session是什么 ?

是保存在服务器端的键值对.

session 必须依赖于cookie

Django中session 做的事情:

1. 在服务器端生成随机字符串

2.生成一个和上面随机字符串对应的大字典,用来保留用户数据的。

3. 随机字符串当成Cookie返回给浏览器

取Session:

1. 从请求携带的COOKIE里面找到随机字符串.

2. 拿到随机字符串 去session 中对应的大字典.

3.从大字典中根据key 取值.

session 的优势

1. 比cookie能存的数据多。

2. 安全性好 ,数据都保存在服务端。

session的缺点

1.session 数据量大,会占用一些内存.

Day71 分页,cookie and Session

Day71 分页,cookie and Session

Day71 分页,cookie and Session

Day71 分页,cookie and Session

Day71 分页,cookie and Session

Day71 分页,cookie and Session

Day71 分页,cookie and Session

获取cookie

request.COOKIES['key']
request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)

  

参数:

  • default: 默认值
  • salt: 加密盐
  • max_age: 后台控制过期时间

设置Cookie

rep = HttpResponse(...)
rep = render(request, ...) rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='加密盐',...)

  

删除cookie

def logout(request):
rep = redirect("/login/")
rep.delete_cookie("user") # 删除用户浏览器上之前设置的usercookie值
return rep

例子

def login(request):
if request.method=='POST':
user = request.POST.get('username')
print(user)
pwd =request.POST.get('pwd')
if user =='alex' and pwd =='dsb':
#登录成功
#告诉浏览器保存一个键值对
rep =redirect('/home/')
print(rep)
# rep.set_cookie('is_login',1)
rep.set_signed_cookie(' ','1',salt='s10nb') #加盐的cookie

return rep
return render(request,'login.html') def home(request):
  #从请求的cookie中找
# ret =request.COOKIES.get('is_login',0)
ret=request.get_signed_cookie('is_login',default='0',salt='s10nb')#取加过盐的cookie
if ret =='1' :
#表示已经登录过了。
return render(request,'home.html')
else:
return redirect('/login/')

  Day71 分页,cookie and Session

Day71 分页,cookie and Session

 Cookie默认关闭浏览器就失效

三、session