当前位置: 首页 > news >正文

Python22_httpx网络请求

Python22_httpx网络请求

httpx.AsyncClient,这是 Python 中处理异步 HTTP 请求的核心类。

httpx.AsyncClient 概览

httpx.AsyncClientHTTPX库的异步客户端,基于asyncio构建,支持非阻塞的 HTTP/1.1 和 HTTP/2 请求,性能远超同步的requests库。


基本使用

1. 安装

pipinstallhttpx# 如需 HTTP/2 支持pipinstallhttpx[http2]

2. 简单请求

importhttpximportasyncioasyncdefmain():# 创建客户端(推荐用 async with 管理生命周期)asyncwithhttpx.AsyncClient()asclient:# GET 请求response=awaitclient.get("https://api.github.com")print(response.status_code)# 200print(response.json())# 解析 JSONasyncio.run(main())

核心特性详解

3. 请求方法

asyncwithhttpx.AsyncClient()asclient:# 各类 HTTP 方法r1=awaitclient.get(url,params={"key":"value"})r2=awaitclient.post(url,json={"data":"value"})# JSON 体r3=awaitclient.post(url,data={"form":"field"})# 表单数据r4=awaitclient.put(url,content=b"raw bytes")# 原始字节r5=awaitclient.patch(url,files={"file":open("a.jpg","rb")})r6=awaitclient.delete(url)r7=awaitclient.head(url)r8=awaitclient.options(url)

4. 高级配置

client=httpx.AsyncClient(# 超时设置(连接、读取、写入)timeout=httpx.Timeout(10.0,connect=5.0),# 请求头headers={"User-Agent":"MyApp/1.0"},# 基础 URL(后续请求可写相对路径)base_url="https://api.example.com/v1",# 启用 HTTP/2http2=True,# 跟随重定向follow_redirects=True,# 验证 SSL(开发时可关闭)verify=True,# 或 verify=False(不推荐生产环境)# 代理proxies="http://localhost:8080",# 或按协议区分:proxies={"http://": "...", "https://": "..."}# 认证auth=("username","password"),# Basic Auth# 或 auth=httpx.BearerToken("token")# Cookie 持久化cookies={"session":"abc123"},# 限制连接池limits=httpx.Limits(max_connections=100,max_keepalive_connections=20))# 使用 base_url 后response=awaitclient.get("/users")# 实际请求 https://api.example.com/v1/users

5. 并发请求(核心优势)

importasyncioimporthttpxasyncdeffetch(client,url):response=awaitclient.get(url)returnresponse.json()asyncdefmain():urls=["https://api.github.com/users/octocat","https://api.github.com/users/torvalds","https://api.github.com/users/gvanrossum"]asyncwithhttpx.AsyncClient()asclient:# 并发执行所有请求tasks=[fetch(client,url)forurlinurls]results=awaitasyncio.gather(*tasks)print(results)asyncio.run(main())

6. 流式响应(大文件下载)

asyncwithhttpx.AsyncClient()asclient:# 流式读取,避免内存溢出asyncwithclient.stream("GET","https://example.com/large-file.zip")asresponse:asyncforchunkinresponse.aiter_bytes():# 处理每个数据块print(f"Received{len(chunk)}bytes")# 或流式文本asyncwithclient.stream("GET",url)asresponse:asyncforlineinresponse.aiter_lines():print(line)

7. 请求/响应钩子

deflog_request(request):print(f"→ Request:{request.method}{request.url}")deflog_response(response):print(f"← Response:{response.status_code}")asyncwithhttpx.AsyncClient(event_hooks={"request":[log_request],"response":[log_response]})asclient:awaitclient.get("https://httpbin.org/get")

与同步 Client 对比

特性httpx.Clienthttpx.AsyncClient
执行方式同步阻塞异步非阻塞
适用场景脚本、简单任务高并发、Web 服务
性能一般极高(可处理数千并发)
使用方式with client:async with client:
依赖无额外依赖需要asyncio

最佳实践

importhttpximportasyncioclassAPIClient:"""封装示例:带重试和错误处理的异步客户端"""def__init__(self):self.client=httpx.AsyncClient(base_url="https://api.example.com",timeout=30.0,http2=True,limits=httpx.Limits(max_connections=50))asyncdef__aenter__(self):returnselfasyncdef__aexit__(self,*args):awaitself.client.aclose()# 确保关闭asyncdefget_user(self,user_id:int):try:response=awaitself.client.get(f"/users/{user_id}")response.raise_for_status()# 自动抛出 4xx/5xx 异常returnresponse.json()excepthttpx.HTTPStatusErrorase:print(f"HTTP error:{e.response.status_code}")raiseexcepthttpx.RequestErrorase:print(f"Request failed:{e}")raise# 使用asyncdefmain():asyncwithAPIClient()asapi:user=awaitapi.get_user(123)print(user)asyncio.run(main())

常见异常处理

异常说明
httpx.RequestError网络连接错误
httpx.HTTPStatusErrorHTTP 错误状态码(需调用raise_for_status()
httpx.TimeoutException请求超时
httpx.ConnectError连接失败

httpx.AsyncClient是现代 Python 异步编程中处理 HTTP 请求的首选工具,特别适合FastAPI/Starlette等异步 Web 框架的后端服务调用。


http://www.jsqmd.com/news/651079/

相关文章:

  • Linux下C++内存泄漏排查实战:用Valgrind的memcheck工具保姆级教程
  • 【Cell Systems】SpotGF空间转录组去噪算法文献分享
  • 2026奇点智能技术大会AI情感陪伴全栈技术图谱(含NLP+多模态情感识别+伦理沙盒实测报告)
  • 寻求有资质的厂房管道安装工程公司?这家企业在生物医药领域表现卓越 - 品牌2026
  • 告别OpenAI API费用:手把手教你用Ollama+本地模型免费跑通微软GraphRAG
  • 人人必备!从“养龙虾”到“养爱马仕”,2026最强Java代码治理工具来了
  • 【ROS2实战笔记-6】RobotPerf:机器人计算系统的基准测试方法论
  • 终极指南:如何优化Theatre动画在移动设备上的性能表现
  • Python条形码识别终极指南:3分钟掌握pyzbar的完整教程
  • 保姆级教程:手把手教你为SAP交货单(VL01N)实现客户许可证校验增强
  • 如何找到优秀的厂房恒温恒湿工程公司?这家设计施工一体化承包商值得考虑 - 品牌2026
  • GetQzonehistory:重新掌控你的数字记忆,QQ空间历史说说备份终极指南
  • 【开发者指南】KittenTTS:轻量级文本转语音模型的集成与应用实践
  • CTF逆向实战:当栈溢出遇到动态链接,如何用ret2libc拿下jarvisoj_level2的flag
  • 微信小程序API请求封装技巧:如何利用环境变量提升开发效率
  • 义乌购商品详情接口实战:生产级签名与数据解析(附完整 Python 代码)
  • 如何选择PostgreSQL Docker镜像:Alpine vs Debian深度对比
  • 终极解决方案:免费让Windows原生支持iPhone HEIC照片缩略图
  • 告别烧管!深入剖析线性可调电源中IGBT的驱动与Multisim热仿真要点
  • 终极指南:如何用PyPortfolioOpt构建风险优化的投资组合
  • 5分钟搞定uniapp与webview双向通信:最新uni.webview.js 1.5.6实战教程
  • LinuxMint20.1桌面系统安装后必做的10项优化(含字体/输入法/分区配置)
  • 如何用PyPortfolioOpt实现贝叶斯投资组合优化:Black-Litterman模型完整指南
  • Orchard CMS核心架构解析:模块化设计与可扩展性原理
  • 【RT-Thread 源码深度解析(二)】对象容器机制:统一管理系统对象的内核设计
  • 推特(X)的视频链接403的解决办法
  • 深度剖析 XOR 交换技巧:真有用还是花架子?
  • xilinx的fadd_5_full_dsp_32说明
  • OpenRocket终极指南:免费开源火箭设计仿真软件完全教程
  • Apache Camel版本升级终极指南:从旧版本平滑迁移到最新版本的10个关键步骤