3

虾米歌词下载、Python Requests 库,以及 HTTP Keep-Alive

 3 years ago
source link: https://blog.lilydjwg.me/2013/11/21/xiami-lyrics-download-python-requests-and-http-keep-alive.41783.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

本文来自依云's Blog,转载请注明。

Requests

这是我第二次用 Requests 了。上一次是个下小说的脚本。我已经不记得自己为什么路过了 httplib2,也路过了 urllib3,却最终买了 Requests 的账。也许是不喜欢 httplib2 那个 Google Code 的首页,也许是厌倦了 urllib* 这种名字。不过我想更多的是开门见山的首页,以及开篇那段让人无法拒绝的介绍:

Requests is an Apache2 Licensed HTTP library, written in Python, for human beings.

Python’s standard urllib2 module provides most of the HTTP capabilities you need, but the API is thoroughly broken. It was built for a different time — and a different web. It requires an enormous amount of work (even method overrides) to perform the simplest of tasks.

Things shouldn’t be this way. Not in Python.

相比之下,中文翻译太差了(而且已经陈旧了)。我在这里再译一个版本:

Requests 是使用 Apache2 许可证的 HTTP 库。用 Python 编写,为人类编写。

Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 烂出翔来了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

事情不应该是那样的,在 Python 世界里。

Requests 使用的是 urllib3,因此继承了它的所有特性。Requests 支持 HTTP 连接保持和连接池,支持使用 cookie 保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。现代、国际化、人性化。相见恨晚

Keep-Alive

以前一直以为 Keep-Alive(连接保持)就是节省了 TCP 连接建立的时间。直到渐渐了解了 TCP 慢启动。直到自己偶然间亲自对比了一次。

使用 httrack 默认参数下载 PostgreSQL 9.3 文档,一千多个页面,29 分钟。后来才注意到 httrack 的 Keep-Alive 支持要写参数手动启用。

使用 wget,默认会使用 Keep-Alive 来复用已有连接。几乎同样的页面,只花了 12 分钟

urllib3 说 它使用 Keep-Alive 单连接从 Google 下载 15 个页面比使用 urllib 每次建立新连接快了一倍。我这里的结果比它的测试还要好呢。

也许,支持 Keep-Alive,是我的 nvchecker 使用 pycurl 要快很多的很重要的一个原因吧。

可惜的是,Requests 不支持 Tornado 的异步调度框架。不过还好,那边我可以用 libcurl,虽然 API 不 Pythonic,至少 cookie 管理和连接管理都很健全。

对了,虾米歌词下载脚本还是在老地方,歌词的获取参考了 you-get 的代码。Requests 的作者 Kenneth Reitz 也有一些其它有意思的东西,包括之前我发现但没意识到是他做的的、用于 HTTP 客户端测试的 Httpbin 网站。

发送到 Kindle


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK