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实现
又是造轮子系列咯,Python上有很多成熟完善的异步任务队列框架可以用,比如Celery,或者RQ,不过这些都不自带消息队列服务,都需要使用Redis、RabbitMQ之类的消息队列才行,我用到小项目中又不需要附带这么多东西,于是自己动手来实现咯。 思路 将需要异步执行的任务添加到队列 自动从队列中取出任务,创建新线程执行 保存任务的执行结果和输出 任务完成,调用回调函数,处理返回的数据 使用输出
2021-12-18 · Python · 约 1 分钟
Python:使用logging模块记录日志
先看看基本用法例子 # -*- coding: utf-8 -*- import logging import sys # 获取logger实例,如果参数为空则返回root logger logger = logging.getLogger(AppName) # 指定logger输出格式 formatter = logging.Formatter('%(asctime)s %(levelna
2022-05-27 · Python · 约 1 分钟
Python实现给图片加水印功能
前言 最近忙得连轴转,很久没更新博客了,代码倒是没啥写,积累了好些东西,接下来一有时间就来更新吧~ 本文记录使用Python实现给图片添加水印的功能实现过程 先看效果 把公众号的封面作为素材 原图是这样的 codelab 加个水印的效果 temp 实现代码 主要实现是参考GitHub上一个项目的:https://github.com/2Dou/watermarker 用到了Pillow库,使用前请
2022-09-29 · Python · 约 1 分钟
Python-本地时间和UTC时间转换
代码 import time import datetime def utc2local(utc_st): UTC时间转本地时间(+8: 00) now_stamp = time.time() local_time = datetime.datetime.fromtimestamp(now_stamp) utc_time = datetime.datetime.ut
2021-12-18 · Python · 约 1 分钟
讨论
共 0 条加载评论中…