必须在async/await上下文中使用httpx.asyncclient,因其方法返回协程需await;httpx.get()是同步接口,直接替换requests.get()无法实现异步并发。

直接用 httpx.AsyncClient 替代 requests 的同步调用,但必须在 async/await 语法上下文中运行——这是最常被忽略的前提,硬套同步写法会报 RuntimeWarning: coroutine 'AsyncClient.get' was never awaited。
为什么不能直接把 requests.get() 换成 httpx.get()?
httpx.get() 是同步接口,httpx.AsyncClient 才是异步核心。很多人误以为“httpx 就是异步版 requests”,结果写成:
import httpx
response = httpx.get("https://httpbin.org/get") # ✅ 同步用法,和 requests 类似
# 但想并发时这么写就错了:
async def fetch():
return httpx.get("https://httpbin.org/get") # ❌ 返回 coroutine,没 await
真正异步需显式创建 client 并 await 方法:
-
httpx.AsyncClient必须配合async with使用,否则连接池不释放 - 所有请求方法(
.get()、.post()等)都返回coroutine,必须await - 不能在普通函数或同步上下文(如脚本顶层、Flask route)里直接 await 异步 client
如何正确发起并发请求?
用 asyncio.gather() 并发触发多个 AsyncClient 请求,比串行快得多,且复用同一 client 实例的连接池:
import asyncio import httpx <p>async def fetch_one(client, url): response = await client.get(url) return response.status_code</p><p>async def main(): async with httpx.AsyncClient() as client: tasks = [ fetch_one(client, "<a href="https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c">https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c</a>"), fetch_one(client, "<a href="https://www.php.cn/link/ef246753a70fce661e16668898810624">https://www.php.cn/link/ef246753a70fce661e16668898810624</a>"), fetch_one(client, "<a href="https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c">https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c</a>"), ] results = await asyncio.gather(*tasks) print(results) # [200, 200, 200],耗时约 2 秒而非 4 秒</p><p>asyncio.run(main())</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8054" title="python-parallelization"><img src="https://img.php.cn/upload/skill/000/000/081/179181013081932.jpg" alt="python-parallelization" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill8054" title="python-parallelization" class="overflowclass">python-parallelization</a> <p class="overflowclass">将顺序 Python 代码转换为并行/并发实现,用于在需要并行化 Python 代码、提升性能时使用。</p> </div> <a rel="nofollow" href="/xiazai/skill8054" title="python-parallelization" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div>
- 每个
fetch_one共享同一个client,避免重复建连开销 - 不要为每个请求新建
AsyncClient,否则失去连接复用优势 -
asyncio.gather()会并发执行,失败时默认抛出首个异常;如需容错,用return_exceptions=True
headers、timeout、JSON 数据怎么传?
参数命名和 requests 高度一致,但 timeout 是 httpx.Timeout 实例或浮点数,且默认无全局超时:
-
headers:字典,和requests完全一样,如{"Authorization": "Bearer xyz"} -
timeout:传timeout=5.0表示总超时;更细粒度用httpx.Timeout(5.0, connect=3.0, read=2.0) -
json:直接传 dict,自动序列化并设Content-Type: application/json -
params:和requests一样,拼在 URL 查询字符串里 - 注意:
data是表单数据(application/x-www-form-urlencoded),不是 JSON
常见错误:httpx.Timeout 不是元组,写成 timeout=(3, 3) 会报 TypeError: unsupported operand type(s) for /: 'Timeout' and 'int'。
和 requests 最容易混淆的兼容点
响应对象行为接近但不等价:没有 .json() 的缓存机制,多次调用会重复解析;.text 和 .content 也需 await:
-
response.json()→await response.json()(必须 await) -
response.text→await response.text() -
response.content→await response.content() -
response.raise_for_status()仍可用,但不带 await,它只检查状态码
另外,httpx 默认跟随重定向(follow_redirects=True),而 requests 默认也是,这点不用改;但若关掉重定向,httpx 的 3xx 响应体默认为空,需手动读取 response.next_request 或设 follow_redirects=False 后处理。
异步不是加个 async 就完事——client 生命周期、await 位置、响应体读取时机,三处漏掉任何一环都会让代码看似跑通实则卡死或内存泄漏。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










