我做了一个垃圾信息过滤的 HTTP 接口。现在有一千万条消息需要经过这个接口进行垃圾检测。
一开始我的代码是这样的:
)
我们写一段代码来看看运行速度:
访问一百次百度,竟然需要 20 秒。那我有一千万条信息,这个时间太长了。
有没有什么加速的办法呢?除了我们之前文章讲到的 多线程、aiohttp 或者干脆用 Scrapy 外,还可以让 requests 保持连接从而减少频繁进行 TCP 三次握手的时间消耗。
那么要如何让 requests 保持连接呢?实际上非常简单,使用Session
对象即可。
修改后的代码:
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!
”
参考资料
官方文档: https://2.python-requests.org/en/master/user/advanced/#session-objects
点击阅读原文,阅读菜鸟学Python 400篇干货!
本篇文章来源于: 菜鸟学Python
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ python里面有什么09/27
- ♥ python如何对矩阵进行转置?09/05
- ♥ 教你如何在python中使用循环for和while11/29
- ♥ python转义字符无效的原因是什么?09/19
- ♥ python adb的作用是什么?12/15
- ♥ python代码运行助手是什么意思11/08
内容反馈