Python HTTP Request Libraries: From requests to httpx
Requests should have retired long ago. Is this old relic httpx the one that actually belongs in the async era? HTTP/2 and timeouts? Requests should have had these basic configs ages ago. Native async support? Don't make me laugh—who still uses sync these days.
目录7 个章节
Introduction
If any Python library has changed the barrier to entry for internet development, requests is definitely on the list.
With a minimalist API, it put an end to the chaotic era of urllib2.
To this day, requests.get(url) is still the first line of crawler code many programmers write instinctively.
But with the full explosion of Python's async ecosystem (Asyncio), and the widespread adoption of the HTTP/2 protocol, this veteran born in 2011 has begun to show its age.
PS: Why still study new technologies yourself in the AI era?
Because AI's underlying nature is the "past."
If you don't master advanced tools, AI will use its "experiential inertia" to keep you in the old era.
Only when you understand new things can you direct AI to write more modern code.
The essence of AI is a "probabilistic model"; it tends to give the most common, most conservative solutions from its training data (which are often the old solutions)
HttpX
httpx is not trying to overthrow requests, but to complete its modernization. Its core slogan is: "Almost fully compatible with the Requests API, but with native async support."
Reasons to switch to httpx for new projects:
- Native async support: When handling thousands upon thousands of API calls, synchronous
requestswill make your program "die" while waiting on network IO. Withasync/await,httpxcan concurrently process extremely high-density requests within a single second, without consuming extra thread resources. - HTTP/2 support: Compared to HTTP/1.1, HTTP/2 supports multiplexing. This means multiple requests can be sent in parallel on the same connection, significantly reducing latency.
- Strict timeout management:
requestsnever times out by default, which is extremely dangerous in production.httpxenables timeout checks by default, better matching the robustness requirements of modern microservices.
Examples
If you're familiar with requests, the cost of migrating to httpx is almost zero.
Sync style comparison (almost identical)
# Requests
import requests
resp = requests.get("https://api.github.com/events")
# HTTPX
import httpx
resp = httpx.get("https://api.github.com/events")
Async style
import httpx
import asyncio
async def fetch_tech_news():
async with httpx.AsyncClient() as client:
# 同时发起多个请求,效率起飞
tasks = [client.get(f"https://news.com/api/{i}") for i in range(10)]
responses = await asyncio.gather(*tasks)
return [r.json() for r in responses]
asyncio.run(fetch_tech_news())
Comparison
| Feature | Requests | HTTPX |
|---|---|---|
| Async support | ❌ (requires a thread pool) | ✅ Native support (Async/Await) |
| HTTP/2 | ❌ | ✅ Supported |
| API friendliness | Extremely high | Extremely high (compatible with Requests) |
| Type hints | Average | ✅ Complete (perfect IDE fit) |
| Use cases | Simple scripts, small crawlers | Async web frameworks, high-concurrency scraping, modern engineering |
Summary
Async is great, but there are some pitfalls:
httpx'sAsyncClientis best used with anasync withcontext manager, otherwise it's easy to cause connection leaks.- Extra care is needed when using the async loop on Windows (e.g. the limitations of
SelectorEventLoop)
_EOF_
Python HTTP Request Libraries: From requests to httpx
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
Python-缓存机制与-functools-lru_cache
缓存是一种将定量数据加以保存以备迎合后续获取需求的处理方式,旨在加快数据获取的速度。数据的生成过程可能需要经过计算,规整,远程获取等操作,如果是同一份数据需要多次使用,每次都重新生成会大大浪费时间。所以,如果将计算或者远程请求等操作获得的数据缓存下来,会加快后续的数据获取需求。 先来一个简单的例子以了解缓存机制的概念: # -*- coding: utf-8 -*- import random
2022-05-27 · Python · 约 1 分钟
自己动手开发简单消息队列(异步任务队列):Python实现
又是造轮子系列咯,Python上有很多成熟完善的异步任务队列框架可以用,比如Celery,或者RQ,不过这些都不自带消息队列服务,都需要使用Redis、RabbitMQ之类的消息队列才行,我用到小项目中又不需要附带这么多东西,于是自己动手来实现咯。 思路 将需要异步执行的任务添加到队列 自动从队列中取出任务,创建新线程执行 保存任务的执行结果和输出 任务完成,调用回调函数,处理返回的数据 使用输出
2021-12-18 · Python · 约 1 分钟
Python接入企业微信推送信息到内部群里
前言 之前一篇文章提到了使用wechatpy库来实现企业微信应用登录:Django + Taro 前后端分离项目实现企业微信登录 其实这个库可以实现的功能非常多,基本微信开发涉及到的功能都能实现。 本文介绍一个很常用的场景:实时推送信息到企业微信群里。 安装 首先安装wechatpy库 pip install wechatpy 如果运行的时候提示需要安装其他库(比如加解密相关的)那就按照提示安装,
2022-04-08 · Python · 约 1 分钟
Python中的双端队列:collections-deque
关于deque 起因是我想做一个「手气不错」的功能,为了提高性能,打算用队列实现,偶然在Stack Overflow看到一个讨论「Efficiency of using a Python list as a queue」 python的list有pop方法,可以实现队列的取出功能,不过据说性能一般般,高赞回答说的 You won't run out of memory using the list
2021-12-18 · Python · 约 1 分钟
讨论
共 0 条加载评论中…