使用协程库httpx并发请求

httpx和aiohttp都是比较常用的异步请求库,当然requests+多线程或requests+gevent也是不错的选择。

一个使用httpx进行并发请求的脚本如下:

python 复制代码
import functools
import sys
import time

import anyio
import httpx


async def fetch(client, results, index) -> int:
    url = "https://qq.com"
    results[index] = r = await client.get(url)
    return len(r.content)


def timeit(func):
    @functools.wraps(func)
    async def deco(*args, **kw):
        start = time.time()
        rv = await func(*args, **kw)
        print(f"{func.__name__} Cost: {round(time.time()-start,1)} seconds.")
        return rv

    return deco


@timeit
async def main():
    if not sys.argv[1:]:
        print(f'Usage::\n  python {sys.argv[0]} 100\n')
        return
    total = int(sys.argv[1])
    results = [None] * total
    async with httpx.AsyncClient(follow_redirects=True, timeout=60) as client:
        async with anyio.create_task_group() as tg:
            for i in range(total):
                tg.start_soon(fetch, client, results, i)
    success = sum(map(bool, results))
    print(f"{total = }; Success: {success}; Failed: {total-success}")


if __name__ == "__main__":
    anyio.run(main)
相关推荐
serve the people3 天前
python环境搭建 (十三) httpx和aiohttp
开发语言·python·httpx
深蓝电商API5 天前
httpx 异步客户端处理 WebSocket 数据
websocket·网络协议·httpx
SunnyRivers6 天前
HTTPX vs Requests vs AIOHTTP特征和性能对比指南
httpx·requests·aiohttp
SunnyRivers6 天前
Python 的下一代 HTTP 客户端 HTTPX 特性详解
python·httpx
深蓝电商API8 天前
httpx库异步爬虫实战对比aiohttp
爬虫·httpx
qq_3814549911 天前
Python httpx:现代HTTP客户端全解析
httpx
曲幽12 天前
FastAPI异步多线程:从踩坑到精通,解锁高性能API的正确姿势
python·flask·fastapi·web·thread·async·httpx·asyncio
SunnyRivers13 天前
Python 中的 HTTP 客户端:Requests、HTTPX 与 AIOHTTP 对比
python·httpx·requests·aiohttp·区别
数据知道22 天前
如何使用 httpx + SQLAlchemy 异步高效写入上亿级图片链接与MD5到 PostgreSQL
数据库·postgresql·httpx
曲幽1 个月前
重构FastAPI生产部署:用异步网关与无服务器计算应对高并发
python·serverless·fastapi·web·async·httpx·await·asyncio