一招大幅提升 requests 访问速度

点击上方“编程派”,选择设为“设为星标”

优质文章,第一时间送达!


作者:kingname

我做了一个垃圾信息过滤的 HTTP 接口。现在有一千万条消息需要经过这个接口进行垃圾检测。


一开始我的代码是这样的:

import requests

messages = ['第一条', '第二条', '第三条']
for message in messages:
    resp = requests.post(url, json={'msg': message}).json()
    if resp['trash']:
        print('是垃圾消息')

我们写一段代码来看看运行速度:

访问一百次百度,竟然需要 20 秒。那我有一千万条信息,这个时间太长了。有没有什么加速的办法呢?除了我们之前文章讲到的 多线程、aiohttp 或者干脆用 Scrapy 外,还可以让 requests 保持连接从而减少频繁进行 TCP 三次握手的时间消耗。那么要如何让 requests 保持连接呢?实际上非常简单,使用Session对象即可。修改后的代码:

import requests
import time

start = time.time()
session = requests.Session()

for _ in range(100):
    resp = session.get('https://baidu.com').content.decode()
    
end = time.time()
print(f'访问一百次网页,耗时:{end - start}')

运行效果如下图所示:

性能得到了显著提升。访问 100 页只需要 5 秒钟。在官方文档[1]中,requests 也说到了 Session对象能够保持连接:

The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3’s connection pooling. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).”

Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection!”

回复下方「关键词」,获取优质资源

回复关键词「 pybook03」,立即获取主页君与小伙伴一起翻译的《Think Python 2e》电子版
回复关键词「入门资料」,立即获取主页君整理的 10 本 Python 入门书的电子版
回复关键词「m」,立即获取Python精选优质文章合集
回复关键词「book 数字」,将数字替换成 0 及以上数字,有惊喜好礼哦~
题图:pexels,CC0 授权。

好文章,我在看
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值