Day 23 · httpx 异步 HTTP

Week 4 · Day 23 / 56 · 返回大纲

一、httpx 客户端

uv add httpx

import httpx
import asyncio

# 同步客户端
client = httpx.Client()
resp = client.get("https://api.github.com")
print(resp.json())

# 异步客户端(推荐)
async def fetch():
    async with httpx.AsyncClient() as client:
        resp = await client.get("https://api.github.com")
        return resp.json()
💡 httpx vs requests: httpx 同时支持同步和异步,API 和 requests 几乎一样。

二、并发请求

async def fetch_url(client, url):
    resp = await client.get(url)
    return url, resp.status_code

async def main():
    urls = [
        "https://api.github.com",
        "https://httpbin.org/get",
        "https://docs.python.org",
    ]
    async with httpx.AsyncClient() as client:
        tasks = [fetch_url(client, url) for url in urls]
        results = await asyncio.gather(*tasks)
        for url, status in results:
            print(f"{status} {url}")

三、错误处理

async def safe_fetch(client, url):
    try:
        resp = await client.get(url, timeout=10)
        resp.raise_for_status()  # 4xx/5xx 抛异常
        return resp.json()
    except httpx.HTTPStatusError as e:
        print(f"HTTP 错误: {e.response.status_code}")
    except httpx.TimeoutException:
        print(f"超时: {url}")
    except httpx.RequestError as e:
        print(f"请求失败: {e}")

动手练习

练习 1:并发请求
并发请求多个 URL
async with httpx.AsyncClient() as client:
    tasks = [client.get(url) for url in urls]
    responses = await asyncio.gather(*tasks)
查看答案
参考答案
# 总耗时 = 最慢的那个
练习 2:错误处理
处理请求失败
try:
    resp = await client.get(url)
    resp.raise_for_status()
except httpx.HTTPError as e:
    return None
查看答案
参考答案
# raise_for_status 是好习惯
练习 3:POST 请求
发送 POST JSON 请求
resp = await client.post(url, json={"key": "value"})
查看答案
参考答案
# json= 自动序列化和设置 Content-Type

打卡验收

会用 httpx 发同步和异步请求
掌握 async with 管理客户端
会并发请求多个 URL
能处理 HTTP 错误和超时
理解 httpx 和 requests 的区别
完成 3 个动手练习
能在 FastAPI 中使用 httpx
知道为什么异步客户端更快
打卡方式: 全部勾选后,告诉我 "Day 23 打卡",并贴出你的代码。