Cooike简介

Cookie 是在 HTTP 协议下,服务器或脚本可以维护客户工作站上信息的一种方式。Cookie 是由 Web 服务器保存在用户浏览器(客户端)上的小文本文件,它可以包含有关用户的信息。无论何时用户链接到服务器,Web 站点都可以访问 Cookie 信息
目前有些 Cookie 是临时的,有些则是持续的。临时的 Cookie 只在浏览器上保存一段规定的时间,一旦超过规定的时间,该 Cookie 就会被系统清除 [2]
持续的 Cookie 则保存在用户的 Cookie 文件中,下一次用户返回时,仍然可以对它进行调用。在 Cookie 文件中保存 Cookie,有些用户担心 Cookie 中的用户信息被一些别有用心的人窃取,而造成一定的损害。其实,网站以外的用户无法跨过网站来获得 Cookie 信息。如果因为这种担心而屏蔽 Cookie,肯定会因此拒绝访问许多站点页面。因为,当今有许多 Web 站点开发人员使用 Cookie 技术,例如 Session 对象的使用就离不开 Cookie 的支持 
 
 

Cookie规范

  • Cookie大小上限为4KB;
  • 一个服务器最多在客户端浏览器上保存20个Cookie;
  • 一个浏览器最多保存300个Cookie;

上面的数据只是HTTP的Cookie规范,但在浏览器大战的今天,一些浏览器为了打败对手,为了展现自己的能力起见,可能对Cookie规范“扩展”了一些,例如每个Cookie的大小为8KB,最多可保存500个Cookie等!但也不会出现把你硬盘占满的可能! 
注意,不同浏览器之间是不共享Cookie的。也就是说在你使用IE访问服务器时,服务器会把Cookie发给IE,然后由IE保存起来,当你在使用FireFox访问服务器时,不可能把IE保存的Cookie发送给服务器。

Cookie与HTTP头

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,例如客户端的第一个请求服务器端发送的Cookie是:Set-Cookie: a=A;第二请求服务器端发送的是:Set-Cookie: a=AA,那么客户端只留下一个Cookie,即:a=AA。

Cookie相关设置属性

'''
class HttpResponseBase: def set_cookie(self, key, 键
             value='', 值
             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获取
(不是绝对,底层抓包可以获取到也可以被覆盖)
          ): pass '''

设置Cookie

response.set_cookie('is_login',True)

cookie 的值为 key value形式

获取Cookie

request.COOKIES.get('is_login')

删除Cookie

response.delete_cookie("cookie_key",path="/",domain=name)

利用Cooke做一个简单的登录

路由

from  app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/',views.login),
path('index/',views.index)
]

orm

from django.db import models

# Create your models here.

class User(models.Model):

    user = models.CharField(max_length=24)
pwd = models.CharField(max_length=24)

视图

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.
from app01.models import User
def login(request): if request.method =='POST':
user = request.POST.get('user')
pwd = request.POST.get('pwd') user_info =User.objects.filter(user=user,pwd=pwd).first() if user_info: response = HttpResponse('登录成功')
response.set_cookie('is_login',True)
response.set_cookie('username',user)
return response return render(request,'login.html') def index(request):
print(request.COOKIES)
if_login =request.COOKIES.get('is_login')
username = request.COOKIES.get('username')
if if_login:
return render(request,'index.html',locals())
return HttpResponse('未登录')

login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action=""method="post">
{% csrf_token %}
用户名<input type="text" name="user">
密码 <input type="password"name="pwd">
<input type="submit">
</form>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>index</h3>
<span>{{ username }}您好</span>
</body>
</html>

整体流程、

用户访问 》登录成功》获取Cookie》访问index 页面》显示 username 您好

用户访问》登录失败》未获取Cookie》访问index页面 》显示 未登录

访问超时

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.
from app01.models import User
def login(request): if request.method =='POST':
user = request.POST.get('user')
pwd = request.POST.get('pwd') user_info =User.objects.filter(user=user,pwd=pwd).first() if user_info: response = HttpResponse('登录成功') #从上次访问开始过期时间,不支持ie
# response.set_cookie('is_login',True,max_age=10) import datetime
times=datetime.datetime(year=2018,month=12,day=21,hour=8,minute=40,second=10)
#expires 固定过期时间
response.set_cookie('is_login',expires=times) response.set_cookie('username',user)
return response return render(request,'login.html') def index(request):
print(request.COOKIES)
if_login =request.COOKIES.get('is_login') if if_login:
username = request.COOKIES.get('username')
return render(request,'index.html',locals())
else:
return redirect('/login/')
return HttpResponse('未登录')

指定路径

默认情况下,Cookie 是对根路径下所有的视图函数共享的,但是个别时候不想让个别视图函数使用Cookie,就需要设置Cookie生效的路径

视图

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.
from app01.models import User
def login(request): if request.method =='POST':
user = request.POST.get('user')
pwd = request.POST.get('pwd') user_info =User.objects.filter(user=user,pwd=pwd).first() if user_info: response = HttpResponse('登录成功') #从上次访问开始过期时间,不支持ie
# response.set_cookie('is_login',True,max_age=10) import datetime
# times=datetime.datetime(year=2018,month=12,day=21,hour=8,minute=40,second=10)
#expires 固定过期时间
# response.set_cookie('is_login',expires=times)
response.set_cookie('is_login', True) #指定可以使用Cookie的路径,如果不设置根路径下的所有视图函数都可以取到。 response.set_cookie('username',user,path='/index/')
return response return render(request,'login.html') def index(request):
print(request.COOKIES)
if_login =request.COOKIES.get('is_login') if if_login:
username = request.COOKIES.get('username')
return render(request,'index.html',locals())
else:
return redirect('/login/')
def tests(request): print('tests------------',request.COOKIES)
return HttpResponse('ok')

输出

{'username': 'liu ', 'is_login': 'True'}
tests------------ {'is_login': 'True'}

只有访问 ‘/index/’ 才可以拿到 username 的Cookie 的值,访问tests 无法拿到 Cookie

显示用户上次登录时间

视图

def index(request):
print(request.COOKIES)
if_login =request.COOKIES.get('is_login') if if_login:
import datetime
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') last_time =request.COOKIES.get('last_login','') username = request.COOKIES.get('username')
response = render(request,'index.html',locals())
response.set_cookie('last_login',now) return response
else:
return redirect('/login/')

流程

用户登录成功后,先保存当前时间到Cookie中,下次用户登录到时候获取Cookie值,在前端模版进行显示。

Cookie (设置与读取、超时设置、指定路径、显示用户上次登录时间)的更多相关文章

  1. 使用Cookie实现显示用户上次访问时间

    一. 常用Cookie API介绍 1. 获取cookie request.getCookies();  // 返回Cookie[] 2. 创建cookie Cookie(String key, St ...

  2. Servlet—Cookie(显示用户上次访问时间、显示商品浏览历史)

    1 . 什么是会话? 会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话. 1.1 会话过程中要解决的一些问题? 每个用户在使用浏览器 ...

  3. HttpClient代理IP及设置连接读取超时

    1.不废话,上代码: public static void main(String[] args) throws Exception { CloseableHttpClient httpClient ...

  4. cookie案例-显示用户上次访问网站的时间

    package cn.itcast.cookie; import java.io.IOException; import java.io.PrintWriter; import java.util.D ...

  5. Cookie实现--用户上次访问时间

    用户上次访问时间  

  6. golang网络通信超时设置

    网络通信中,为了防止长时间无响应的情况,经常会用到网络连接超时.读写超时的设置. 本文结合例子简介golang的连接超时和读写超时设置. 1.超时设置 1.1 连接超时 func DialTimeou ...

  7. org.apache.http.client.HttpClient; HttpClient 4.3超时设置

    可用的code import org.apache.commons.lang.StringUtils;import org.apache.http.HttpEntity;import org.apac ...

  8. HttpClient 3.X 4.3 4.x超时设置

    HttpClient 4.3.HttpClient这货和Lucene一样,每个版本的API都变化很大,这有点让人头疼.就好比创建一个HttpClient对象吧,每一个版本的都不一样, 3.X是这样的 ...

  9. 设置全局context变量 (显示用户登录名)

    比如在每个页面的最上面部分需要显示用户的登录名称,如果不登录则显示为Guest.这部分内容在每个页面都会出现,所以可将该部分内容作为一个公共模板(如userauth.html),如然后在其他模板中进行 ...

随机推荐

  1. Python基础(中篇)

    本篇文章主要内容:数据类型的常用方法,条件语句,循环语句. 在开始正篇之前我们先来看看上一篇留下的题目. 题目: 定义一个字典a,有两个键值对:一个键值对key是可乐,value是18:另一个键值对k ...

  2. 【python接口自动化】- DDT数据驱动测试

    简单介绍 ​ DDT(Date Driver Test),所谓数据驱动测试,简单来说就是由数据的改变从而驱动自动化测试的执行,最终引起测试结果的改变.通过使用数据驱动测试的方法,可以在需要验证多组数据 ...

  3. RPC框架学习+小Demo实例

    一.什么是RPC协议? 全称:远程过程调度协议 效果:使消费者向调用本地方法一样调用远程服务方法,对使用者透明 目前常用:Dubbo.Thirft.Sofa.... 功能: 建立远程通信(socket ...

  4. 洛谷P1055 字符串的处理-----ISBN

    题目描述 每一本正式出版的图书都有一个ISBN号码与之对应,ISBN码包括99位数字.11位识别码和33位分隔符,其规定格式如x-xxx-xxxxx-x,其中符号-就是分隔符(键盘上的减号),最后一位 ...

  5. MySQL审计audit

    导读: MySQL社区版是不带审计功能的,如果要使用MySQL审计,可以考虑使用中间件(例如proxysql)或者是MariaDB的审计插件.这里以MariaDB的审计插件为例,实现MySQL 5.7 ...

  6. Java并发包源码学习系列:ReentrantLock可重入独占锁详解

    目录 基本用法介绍 继承体系 构造方法 state状态表示 获取锁 void lock()方法 NonfairSync FairSync 公平与非公平策略的差异 void lockInterrupti ...

  7. 用python做youtube自动化下载器 代码

    目录 项目地址 思路 流程 1. post i. 先把post中的headers格式化 ii.然后把参数也格式化 iii. 最后再执行requests库的post请求 iv. 封装成一个函数 2. 调 ...

  8. 解锁Renderbus客户端使用新技巧----快速渲染效果图篇

    度娘说,效果图最基本的要求就是:应该符合事物的本身尺寸,不能为了美观而使用效果把相关模型的尺寸变动,那样的效果图不但不能起到表现设计的作用,反而成为影响设计的一个因素.可见高效渲染效果图是都是当下我们 ...

  9. docker save 保存导出镜像

    Docker保存镜像 tag 镜像 # 镜像打 tag 标签 # docker tag 镜像id/名 新名字 docker tag fce91102e17d tomcat01 commit 镜像 注意 ...

  10. Spring Boot 2.x基础教程:配置元数据的应用

    在使用Spring Boot开发应用的时候,你是否有发现这样的情况:自定义属性是有高量背景的,鼠标放上去,有一个Cannot resolve configuration property的配置警告. ...