Django目录:https://blog.csdn.net/qq_41106844/article/details/105554082
cookie概述
什么是cookie
Cookie 并不是它的原意“甜饼”的意思, 而是一个保存在客户机中的简单的文本文件, 这个文件与特定的 Web 文档关联在一起, 保存了该客户机访问这个Web 文档时的信息, 当客户机再次访问这个 Web 文档时这些信息可供该文档使用。
由于“Cookie”具有可以保存在客户机上的神奇特性, 因此它可以帮助我们实现记录用户个人信息的功能, 而这一切都不必使用复杂的CGI等程序 。
Cookie是由服务器创建,然后通过响应发送给客户端的一个键值对。客户端会保存Cookie,并会标注出Cookie的来源(哪个服务器的Cookie)。当客户端向服务器发出请求时会把所有这个服务器Cookie包含在请求中发送给服务器,这样服务器就可以识别客户端了。
cookie规范
- Cookie大小上限为4KB;
- 一个服务器最多在客户端浏览器上保存20个Cookie;
- 一个浏览器最多保存300个Cookie;
上面的数据只是HTTP的Cookie规范,但在浏览器大战的今天,一些浏览器为了打败对手,为了展现自己的能力起见,可能对Cookie规范“扩展”了一些,例如每个Cookie的大小为8KB,最多可保存500个Cookie等!但也不会出现把你硬盘占满的可能!
注意,不同浏览器之间是不共享Cookie的。也就是说在你使用IE访问服务器时,服务器会把Cookie发给IE,然后由IE保存起来,当你在使用FireFox访问服务器时,不可能把IE保存的Cookie发送给服务器。
cookie的特性
Cookie是通过HTTP请求和响应头在客户端和服务器端传递的:
- Cookie:请求头,客户端发送给服务器端;
- 格式:Cookie: a=A; b=B; c=C。即多个Cookie用分号离开;
Set-- Cookie:响应头,服务器端发送给客户端; - 一个Cookie对象一个Set-Cookie:
Set-Cookie: a=A
Set-Cookie: b=B
Set-Cookie: c=C
如果服务器端发送重复的Cookie那么会覆盖原有的Cookie,例如客户端的第一个请求服务器端发送的Cookie是:Set-Cookie: a=A;第二请求服务器端发送的是:Set-Cookie: a=AA,那么客户端只留下一个Cookie,即:a=AA。
实例
cooksessDemo.cooksessDemo.urls.py
---------------------------------
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.login),
path('index/', views.index)
]
cooksessDemo.app01.views.py
---------------------------
from django.shortcuts import render,redirect,HttpResponse
# Create your views here.
def login(request):
if request.method == "GET":
return render(request,"login.html")
else:
user = request.POST.get('uer')
pwd = request.POST.get('pwd')
print(user,pwd)
if user == 'alex' and pwd == '123':
return redirect('/index/')
else:
return HttpResponse('error')
def index(request):
shangpin = "香蕉"
shangpin_list = ["苹果","荔枝","榴莲"]
name = 'alex'
return render(request,"index.html",{'name':name,"shangpin":shangpin,"shangpin_list":shangpin_list})
cooksessDemo.templates.login.html
---------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form method="post">
<input type="text" name="uer">
<input type="password" name="pwd">
<input type="submit" value="登录">
{% csrf_token %}
</form>
</body>
</html>
cooksessDemo.templates.index.html
----------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
<p>{{ name }}</p>
<p>{{ shangpin }}</p>
<p>{{ shangpin_list }}</p>
</body>
</html>
我们在登录页面登录后,就会跳转到主页index。
![20155953-e7774e8093a3a0de.png](https://i-blog.csdnimg.cn/blog_migrate/83e1880152465e3674b70c6afbc0d795.png)
但是我们也可以不登录,直接访问index页面,也会跳转。
![20155953-dabd379e8f1ee158.png](https://i-blog.csdnimg.cn/blog_migrate/ec637df7dc4a21b76f16983b93c93e9b.png)
而监管我们是否登录,就是使用cookie。
cooksessDemo.app01.views.py
---------------------------
from django.shortcuts import render,redirect,HttpResponse
# Create your views here.
def login(request):
if request.method == "GET":
return render(request,"login.html")
else:
user = request.POST.get('uer')
pwd = request.POST.get('pwd')
print(user,pwd)
if user == 'alex' and pwd == '123':
#设置cookie
obj = redirect('/index/')
obj.set_cookie("username",user)
obj.set_cookie("is_login",True)
return obj
else:
return HttpResponse('error')
def index(request):
shangpin = "香蕉"
shangpin_list = ["苹果","荔枝","榴莲"]
name = 'alex'
return render(request,"index.html",{'name':name,"shangpin":shangpin,"shangpin_list":shangpin_list})
![20155953-d4cca7b3b26eacd7.png](https://i-blog.csdnimg.cn/blog_migrate/376f93a86349f67126b62e1f0999fcf8.png)
![20155953-6d95278ae5a19dfe.png](https://i-blog.csdnimg.cn/blog_migrate/dfa1fc01a2a69fb77e0de9e526f8656e.png)
上面我们只是在登录时添加了cookie,还没有进行校验,接着我们在index视图函数里面校验cookie。
cooksessDemo.app01.views.py
---------------------------
from django.shortcuts import render,redirect,HttpResponse
# Create your views here.
def login(request):
if request.method == "GET":
return render(request,"login.html")
else:
user = request.POST.get('uer')
pwd = request.POST.get('pwd')
print(user,pwd)
if user == 'alex' and pwd == '123':
#设置cookie
obj = redirect('/index/')
obj.set_cookie("username",user)
obj.set_cookie("is_login",True)
return obj
else:
return HttpResponse('error')
def index(request):
#获取cookie
coo = request.COOKIES
is_login = coo.get("is_login")
#校验cookie
if not is_login:
return redirect('/login/')
shangpin = "香蕉"
shangpin_list = ["苹果","荔枝","榴莲"]
name = 'alex'
return render(request,"index.html",{'name':name,"shangpin":shangpin,"shangpin_list":shangpin_list})
这时,如果我们直接访问index页面,因为cookie验证失败,会跳转到login页面。
![20155953-ad49b7ac98949077.png](https://i-blog.csdnimg.cn/blog_migrate/4441aaa1fdb2024e40bca85cf59eb634.png)
Django中的cookie语法
设置cookie
rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,'salt',...)
set_signed_cookie,不是对cookie进行加密,而是加签名确保cookie不会被伪造。否则如果用户修改了cookie中代表用户标识的key,就可以跨过密码认证直接访问别人的用户资源了。
我们来看一下set_cookie的源码:
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
domain=None, secure=False, httponly=False, samesite=None):
"""
Set a cookie.
``expires`` can be:
- a string in the correct format,
- a naive ``datetime.datetime`` object in UTC,
- an aware ``datetime.datetime`` object in any time zone.
If it is a ``datetime.datetime`` object then calculate ``max_age``.
"""
"""
我们来看一下set_cookie的参数信息:
key:cookie的键
value='':cookie的值
max_age=None: 超时
cookie需要延续的时间(以秒为单位)
如果参数是\ None`` ,这个cookie会延续到浏览器关闭为止。
expires=None:超时
expires默认None ,cookie失效的实际日期/时间。
path='/':Cookie生效的路径,
浏览器只会把cookie回传给带有该路径的页面,这样可以避免将
cookie传给站点中的其他的应用。
/ 表示根路径,特殊的:根路径的cookie可以被任何url的页面访问
domain=None:Cookie生效的域名
你可用这个参数来构造一个跨站cookie。
如, domain=".example.com"
所构造的cookie对下面这些站点都是可读的:
www.example.com
www2.example.com
an.other.sub.domain.example.com 。
如果该参数设置为 None ,cookie只能由设置它的站点读取。
secure=False:如果设置为 True ,浏览器将通过HTTPS来回传cookie。
httponly=False:只能http协议传输,无法被JavaScript获取
(不是绝对,底层抓包可以获取到也可以被覆盖)
"""
获取cookie
request.COOKIES
删除cookie
response.delete_cookie("cookie_key",path="/",domain=name)
两道练习题:
案例1:显示上次访问时间。
用户第一次认证时,将当前时间赋给一个key值作为初始时间,之后用户每一次访问主页,就将时间value值更新。
案例2:显示上次浏览过的商品。
我们给每一个商品页面设置一个gid,用户每浏览一个商品,就将gid实时保存到一个列表之中,这个列表则保存在cookie中。