Python requests 与 httpx 讲解

📅 2026/8/27 20:30:19
Python requests 与 httpx 讲解
文章目录一、快速对比二、安装三、requests 基本用法常用参数会话Session—— 保持连接和 Cookie四、httpx 基本用法同步使用 Client推荐类似 Session五、httpx 异步用法重要优势六、常见实战功能1. 超时设置2. 认证3. 文件上传4. 代理5. 处理响应七、错误处理八、最佳实践建议在 Python 中发送 HTTP 请求最常用的两个库是requests经典同步库和httpx现代支持同步 异步的库。两者 API 高度相似但设计理念和功能有所不同。一、快速对比特性requestshttpx同步请求✅ 原生支持✅ 支持异步请求❌ 不支持✅ 原生支持HTTP/2❌✅ 支持API 风格简单易用高度兼容 requests更现代连接池 / 超时支持支持更灵活官方维护状态成熟稳定活跃开发推荐场景简单脚本、同步项目新项目、需要异步、HTTP/2建议新项目优先考虑httpx维护老项目或只需要简单同步请求继续用requests即可二、安装pipinstallrequests pipinstallhttpx# 如果需要 HTTP/2 支持httpxpipinstallhttpx[http2]三、requests 基本用法importrequests# GET 请求responserequests.get(https://httpbin.org/get,params{key:value})print(response.status_code)# 200print(response.text)# 文本内容print(response.json())# 解析 JSON# POST 请求responserequests.post(https://httpbin.org/post,json{name:Alice,age:25},# 自动设置 Content-Type: application/jsonheaders{User-Agent:MyApp/1.0})# 其他常用方法requests.put(url,data...)requests.delete(url)requests.patch(url)requests.head(url)常用参数responserequests.get(url,params{page:1},# 查询参数headers{Authorization:Bearer xxx},timeout10,# 超时秒allow_redirectsTrue,# 是否允许重定向verifyTrue,# SSL 证书验证)会话Session—— 保持连接和 Cookiesessionrequests.Session()session.headers.update({User-Agent:MyApp/1.0})session.get(https://example.com/login)responsesession.get(https://example.com/profile)# 自动携带 Cookie四、httpx 基本用法同步httpx 的同步 API 几乎可以无缝替换 requestsimporthttpx# GETresponsehttpx.get(https://httpbin.org/get,params{key:value})print(response.status_code)print(response.text)print(response.json())# POSTresponsehttpx.post(https://httpbin.org/post,json{name:Alice},headers{User-Agent:MyApp/1.0})使用 Client推荐类似 Sessionwithhttpx.Client(timeout10.0,headers{User-Agent:MyApp/1.0})asclient:responseclient.get(https://httpbin.org/get)print(response.json())Client会自动管理连接池性能更好也支持上下文管理器。五、httpx 异步用法重要优势importhttpximportasyncioasyncdefmain():asyncwithhttpx.AsyncClient()asclient:responseawaitclient.get(https://httpbin.org/get)print(response.status_code)print(response.json())# 并发请求tasks[client.get(https://httpbin.org/get),client.get(https://httpbin.org/ip),client.get(https://httpbin.org/user-agent),]responsesawaitasyncio.gather(*tasks)forrinresponses:print(r.status_code)asyncio.run(main())异步适合高并发爬虫同时请求多个 APIFastAPI / 异步 Web 服务中调用外部接口六、常见实战功能1. 超时设置# requestsrequests.get(url,timeout5)# 总超时requests.get(url,timeout(3,10))# 连接超时, 读取超时# httpxhttpx.get(url,timeout5.0)httpx.get(url,timeouthttpx.Timeout(5.0,connect3.0))2. 认证# Basic Authrequests.get(url,auth(user,pass))httpx.get(url,auth(user,pass))# Bearer Tokenheaders{Authorization:Bearer your_token}3. 文件上传# requests / httpx 写法几乎相同files{file:open(test.txt,rb)}responserequests.post(url,filesfiles)4. 代理proxies{http://:http://127.0.0.1:7890,https://:http://127.0.0.1:7890,}requests.get(url,proxiesproxies)httpx.get(url,proxiesproxies)5. 处理响应responsehttpx.get(url)response.status_code response.headers response.text# 字符串response.content# 字节response.json()# 字典response.raise_for_status()# 状态码不是 2xx 时抛异常七、错误处理importhttpxtry:withhttpx.Client(timeout10)asclient:responseclient.get(https://httpbin.org/status/404)response.raise_for_status()# 抛出 HTTPStatusErrorexcepthttpx.HTTPStatusErrorase:print(fHTTP 错误:{e.response.status_code})excepthttpx.RequestErrorase:print(f请求失败:{e})excepthttpx.TimeoutException:print(请求超时)requests的异常体系类似requests.HTTPError、requests.Timeout等。八、最佳实践建议生产环境优先用Client/Session而不是每次调用顶层的get()/post()必须设置超时避免请求无限挂起使用response.raise_for_status()快速发现 HTTP 错误需要并发时直接上httpx asyncio请求头统一管理User-Agent、Authorization 等敏感信息Token、密码不要硬编码用环境变量或配置管理大型项目可封装一个统一的 HTTP 客户端类简单封装示例httpximporthttpxfromtypingimportAnyclassHttpClient:def__init__(self,base_url:str,token:str|NoneNone):headers{User-Agent:MyApp/1.0}iftoken:headers[Authorization]fBearer{token}self.clienthttpx.Client(base_urlbase_url,headersheaders,timeout15.0)defget(self,path:str,**kwargs)-Any:responseself.client.get(path,**kwargs)response.raise_for_status()returnresponse.json()defclose(self):self.client.close() 感谢阅读想了解更多 我的博客网站 | 记录思考分享干货 我的个人主页 | 关于我、开源项目