用Python实现应用Last-Modified和ETag避免下载重复内容

Http 1.1中避免重复下载的标记

使用Http1.1中定义好的头信息来避免重复下载,参考HTTP/1.1 Section 14 Header Field Definitions中的14.19 ETag/14.24 If-Match/14.29 Last-Modified/14.25 If-Modified-Since

开发者把Last-Modified 和ETags请求的http报头一起使用,能够有效利用本地缓存,降低无谓的重复下载。

示例代码逻辑

1. 客户端下载一个链接(Sample);
2. 服务器返回Sample,Sample中记录Last-Modified/ETag标记;
3. 客户端再次下载这个链接,并将上次请求时服务器返回的Last-Modified/ETag一起传递给服务器;
4. 服务器检查该Last-Modified或ETag,并判断出该页面自上次客户端请求之后还未被修改,直接返回响应304和一个空的响应体。

其实在《Dive Into Python》中就有相当详细的实例代码,强烈建议没看过这本书的python程序员们认真学习一下,会提升面向对象编程和网络编程能力的。

示例代码

?Download HttpDownload.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on Nov 9, 2011@author: li3huo
'''import urllib, urllib2
import sys
import time
class DefaultErrorHandler(urllib2.HTTPDefaultErrorHandler):"""用来保证请求中记录Http状态
"""def http_error_default(self, req, fp, code, msg, headers):result = urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)result.status = codereturn resultclass Sample():"""a sample is the url i want to download
"""url = NonecontentLength = 0etag = NonelastModified = Nonedata = Nonepath = Nonedef __init__(self, url, contentLength=0, etag=None, lastModified=None):self.url = urlself.contentLength = 0self.etag = etagself.lastModified = lastModifiedself.status = 200self.file = filedef __repr__(self):return repr("Http Status=%d; Length=%d; Last Modified Time=%s; eTag=%s" % (self.status, self.contentLength, self.lastModified, self.etag))def downloadSample(self):request = urllib2.Request(self.url)request.add_header('User-Agent', "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)")if self.lastModified:request.add_header('If-Modified-Since', self.lastModified)if self.etag:request.add_header('If-None-Match', self.etag)conn = urllib2.build_opener(DefaultErrorHandler()).open(request)if hasattr(conn, 'headers'):# save ETag, if the server sent oneself.etag = conn.headers.get('ETag')# save Last-Modified header, if the server sent oneself.lastModified = conn.headers.get('Last-Modified')self.contentLength = conn.headers.get("content-length")if hasattr(conn, 'status'):self.status = conn.statusprint "status=%d" % self.statusself.data = conn.read()if self.status == 304:print "the content is same, so return nothing!"if not self.contentLength:self.contentLength = len(self.data)conn.close()if __name__ == '__main__':url = 'http://www.sina.com.cn'sample = Sample(url)sample.downloadSample()print samplesample.downloadSample()print sample

输出结果

‘Http Status=200; Length=589988; Last Modified Time=Wed, 09 Nov 2011 10:45:55 GMT; eTag=None’
status=304
the content is same, so return nothing!
‘Http Status=304; Length=0; Last Modified Time=Wed, 09 Nov 2011 10:45:55 GMT; eTag=None’

用Python实现应用Last-Modified和ETag避免下载重复内容相关推荐

  1. 如何在Python Interpreter中重新导入更新的包? [重复]

    本文翻译自:How to re import an updated package while in Python Interpreter? [duplicate] This question alr ...

  2. python安装包的方法与图解_Python下载和安装过程详解(包含所有平台)

    在开发 Python 程序之前,必须先完成一些准备工作,也就是在计算机上安装并配置 Python 解释器. 在 Windows 上安装 Python 在 Windows 上安装 Python 请按如下 ...

  3. python buildin 中的一些类中为什么方法的内容都是pass?

    python buildin 中的一些类中为什么方法的内容都是pass? 文章目录: 一.看到的一些方法的定义都是pass 二.如何查看Python的源代码 python 的源代码是用C语言写的 一. ...

  4. Python 连接FTP服务器并实现文件夹下载实例演示,python区分ftp目录下文件和文件夹方法,ftp目录下包含中文名问题处理

    Python 连接 FTP 服务器并实现文件夹下载实例演示 第一章:连接 FTP 服务器并实现文件夹下载 ① 连接 FTP 服务器 ② 进入指定目录并显示文件信息 ③ 区分文件和文件夹名 ④ 文件夹名 ...

  5. Crawler之Scrapy:Python实现scrapy框架爬虫两个网址下载网页内容信息

    Crawler之Scrapy:Python实现scrapy框架爬虫两个网址下载网页内容信息 目录 输出结果 实现代码 输出结果 后期更新-- 实现代码 import scrapy class Dmoz ...

  6. python pip配置镜像源:douban不能下载aliyun可以下载

    python pip配置镜像源:douban不能下载aliyun可以下载 [global] timeout = 6000 index-url = https://mirrors.aliyun.com/ ...

  7. Python 实现批量从不同的Linux服务器下载文件

    基于Python实现批量从不同的Linux服务器下载文件   by:授客 QQ:1033553122 实现功能 1 测试环境 1 使用方法 1 1. 编辑配置文件conf/file_for_downl ...

  8. 11小时 python自动化测试从入门到_从设计到开发Python接口自动化测试框架实战,资源教程下载...

    课程名称 从设计到开发Python接口自动化测试框架实战,资源教程下载 课程简介: 课程从接口基础知识入门,从抓包开始,到接口工具的运用,再到常见接口库.接口开发.Mock服务.unittest框架的 ...

  9. python编程入门经典-Python编程入门经典PDF文档免费下载

    作为一门面向对象的开源编程语言,python易于理解和扩展,并且使用起来非常方便.<python编程入门经典>涵盖了python的方方面面,通过学习本书,读者可以立即使用python编写程 ...

最新文章

  1. SpringBoot 实战 (九) | 整合 Mybatis
  2. 缓存的Cache Aside模式
  3. python输入文字、成为字典_Python 字典(Dictionary)操作详解
  4. mysql打印语句_最全总结 | 聊聊 Python 数据处理全家桶(Mysql 篇)
  5. PHP的- = :: self $this
  6. 【Python】理解Python(2) - help() 函数? or 类?
  7. yum -y list java* 缓存加载不了_Java开发面试宝典:分布式相关篇
  8. SD-WAN技术的详细解析
  9. 计算机考研英语书,我的计算机考研复习经验 (分5大部分,很详细)
  10. Eclipse install new software 失败 解决方案
  11. 浅谈Android数据库DBFlow
  12. 2525 小b的字符串(模拟)
  13. 如何在Web前端实现CAD图文字全文搜索
  14. Google Guava中Joiner用法
  15. MobilenetV2学习笔记 --- MobileNetV2: Inverted Residuals and Linear Bottlenecks
  16. 交换机与路由器技术-05-路由器工作原理
  17. Python代码画小鸭穿雨靴--turtle绘图
  18. waf防火墙是什么?有什么作用
  19. java se和java_Java SE 9非常适合灵活,可扩展和无服务器的未来
  20. 笔记本电脑关上盖子锁定计算机,教大家笔记本电脑合上盖子后如何自动锁定电脑...

热门文章

  1. Linux下实现一个网卡绑定多个IP地址
  2. 网络工程师和网络管理原的区别
  3. kepserver 6.5_油价下调!加满一箱油少花6.5元……
  4. 组合算法 C++高效实现 (二进制辅助法)
  5. CoreAnimation-CATransform3D-1
  6. android 模拟器 3D 开发环境配置
  7. Android中的EditText默认时不弹出软键盘的方法
  8. android4.0自定义锁屏总结【android锁屏研究一】
  9. Android应用开发——系统自带样式Android:theme
  10. JBoss 系列三十七:jBPM5示例之 Rule Task