程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

每天一个 Python 库:httpx异步请求,让接口测试飞起来

balukai 2025-07-10 13:15:54 文章精选 4 ℃

为什么我推荐你用httpx?

你是不是经常需要:

  • 批量调用接口、测试接口稳定性?
  • 发几十个请求跑数据分析?
  • 想爬网页但速度太慢?

老牌 requests 在这些场景早就力不从心。而 httpx 是它的全新异步增强版:

特性

requests

httpx

异步请求

不支持

原生支持

HTTP/2 支持

请求池复用

部分支持

内置

与 requests API 一致

学习本来就不是一蹴而就的事,不过只要你肯练、敢用,坚持,你一定能看到变化!


1. 快速上手:同步请求 vs 异步请求

同步示例(和 requests 几乎一样):

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish 
@File    :D22.py
@Date    :2025/6/23 20:53 
@Author : malijie
"""
import json

import httpx

r = httpx.get("https://httpbin.org/get")
print(r.status_code)
print(json.dumps(r.json(), indent=2, ensure_ascii=False))

异步示例(适合并发):

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish 
@File    :D22.py
@Date    :2025/6/23 20:53
@Author : malijie
"""
import json
import asyncio

import httpx


async def get_data():
    async with httpx.AsyncClient() as client:
        r = await client.get("https://httpbin.org/get")
        print(r.status_code)
        print(json.dumps(r.json(), indent=2, ensure_ascii=False))


asyncio.run(get_data())



2. 实战:高并发接口调用

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish 
@File    :D22.py
@Date    :2025/6/23 20:53
@Author : malijie
"""
import json
import asyncio

import httpx


urls = [f"https://httpbin.org/get?i={i}" for i in range(10)]


async def fetch(url):
    async with httpx.AsyncClient() as client:
        r = await client.get(url)
        print(f"{url} → {r.status_code}")


async def main():
    await asyncio.gather(*[fetch(u) for u in urls])

asyncio.run(main())

实际测试:10个接口同时发出,总耗时小于 1 秒!



3. 进阶用法合集(最实用功能)

携带 Token / Headers

headers = {"Authorization": "Bearer YOUR_TOKEN"}
r = httpx.get("https://api.xxx.com/data", headers=headers)

POST JSON 请求

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish 
@File    :D22.py
@Date    :2025/6/23 20:53
@Author : malijie
"""
import json

import httpx

url = "https://httpbin.org/post"
r = httpx.post(url, json={"user": "fish"})
print(json.dumps(r.json(), indent=2, ensure_ascii=False))


设置超时 / 重试

client = httpx.Client(timeout=httpx.Timeout(5.0, connect=2.0))
r = client.get("https://httpbin.org/delay/2")

代理请求

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish 
@File    :D22.py
@Date    :2025/6/23 20:53
@Author : malijie
"""
import json

import httpx

url = "https://httpbin.org/post"
r = httpx.post(url, json={"user": "fish"})
print(json.dumps(r.json(), indent=2, ensure_ascii=False))



4. 配合 FastAPI 打造异步接口调用器

适合场景:平台系统 -> 多子系统接口触发器

from fastapi import FastAPI
import httpx

app = FastAPI()

@app.get("/multi-call")
async def multi_call():
    async with httpx.AsyncClient() as client:
        r1 = await client.get("http://api1.com/data")
        r2 = await client.get("http://api2.com/status")
    return {"api1": r1.json(), "api2": r2.json()}

用 uvicorn 来启动这个 FastAPI 应用

D22 是你的文件名(不加 .py)

app 是你定义的 FastAPI 实例名

--reload 是调试模式,修改代码会自动重启

浏览器或 Postman 访问接口访问地址:
http://127.0.0.1:8000/multi-call

将看到如下类似结构的 JSON 响应

{
  "api1": {
    "args": {
      "i": "1"
    },
    "headers": {
      "Accept": "*/*",
      "Accept-Encoding": "gzip, deflate, br",
      "Host": "httpbin.org",
      "User-Agent": "python-httpx/0.24.1",
      "X-Amzn-Trace-Id": "Root=1-685a8774-6fa70a8c7e3268e41ba360b7"
    },
    "origin": "103.100.176.119",
    "url": "https://httpbin.org/get?i=1"
  },
  "api2": {
    "args": {
      "i": "2"
    },
    "headers": {
      "Accept": "*/*",
      "Accept-Encoding": "gzip, deflate, br",
      "Host": "httpbin.org",
      "User-Agent": "python-httpx/0.24.1",
      "X-Amzn-Trace-Id": "Root=1-685a8774-2ba4edb47ed0f82e7aa0b879"
    },
    "origin": "103.100.176.119",
    "url": "https://httpbin.org/get?i=2"
  }
}

5. 场景集锦(实用性超高)

场景

推荐用法

接口自动化测试

异步并发测试接口

API 并发采集(如爬虫、舆情)

async + gather

多 API 聚合查询

httpx.AsyncClient

大量数据 POST 写入

异步 POST + json

登录后请求(带 token)

headers + session



总结一句话:

httpx = 异步 + 现代 + 更强大的 requests

只要你涉及接口调用,它就是你未来必备工具!



下期预告

《每天一个 Python 库:Flask 快速构建 Web 接口,接口开发不再难!》

点赞关注不迷路,后续更新更多自动化测试经验,我们一起成长!欢迎评论区留言!

最近发表
标签列表