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. Mapreduce实例--去重

    数据去重"主要是为了掌握和利用并行化思想来对数据进行有意义的筛选.统计大数据集上的数据种类个数.从网站日志中计算访问地等这些看似庞杂的任务都会涉及数据去重. 数据去重的最终目标是让原始数据中 ...

  2. 翻译 | 30个 Python3 的最佳实践,技巧和窍门

    1.使用 Python3 如果你关注 Python 的话,应该会知道 Python 2 已经于今年(2020 年)1 月 1 日正式弃用了.这份教程的很多例子都是只支持 Python 3 的,如果你还 ...

  3. 写一个react hook:useLoading

    在写业务的过程中,我们总是会遇到这样的需求,在请求时显示一个 loading,然后请求结束后展示数据.以一个是不是 vip 的场景为例,如果不加入 loading 状态,页面可能在未请求的时候显示非 ...

  4. 快速了解JavaScript的基础知识

    注释 单行注释: // 单行注释 多行注释: /* 多行 注释 */ 历史上 JavaScript 可以兼容 HTML 注释,因此 <!-- 和 --> 也可以是单行注释. x = 1; ...

  5. 【C++】《C++ Primer 》第八章

    第八章 IO库 一.IO类 1. 标准库定义的IO类型 头文件 作用 类型 iostream 从标准流中读写数据 istream, wistream 从流读取数据 ostream, wostream ...

  6. 天梯赛练习 L3-006 迎风一刀斩 (30分) 几何关系

    题目分析: 对于给出的两个多边形是否可以组成一个矩形,这里我们分以下几种情况讨论 1.首先对于给出的两个多边形只有3-3,3-4,3-5,4-4才有可能组成一个矩形,并且两个多边形只可能是旋转90,1 ...

  7. maven依赖与传递性依赖

    目录 依赖范围 传递性依赖 依赖调节 可选依赖 本文主要是针对<maven实战>书中关键知识点的学习记录,未免有纰漏或描述不到之处,建议购买阅读原书 首先贴出一个pom常见的一些元素释义 ...

  8. Java 使用 mail.jar 实现邮件发送

    目录 准备工作 使用到的 jar 包 实现代码 准备工作 要想实现邮件发送, 需要先打开发送邮箱的 POP3/SMTP 服务,打开方式在 设置>帐户 中去打开,打开之后如果是qq邮箱会获得一个授 ...

  9. 5.1中repair table

    mysql> repair table xs;+---------+--------+----------+----------+| Table | Op | Msg_type | Msg_te ...

  10. mysql过滤复制