使用协程库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)
相关推荐
曲幽5 天前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
曲幽7 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
serve the people1 个月前
python环境搭建 (十三) httpx和aiohttp
开发语言·python·httpx
深蓝电商API1 个月前
httpx 异步客户端处理 WebSocket 数据
websocket·网络协议·httpx
SunnyRivers1 个月前
HTTPX vs Requests vs AIOHTTP特征和性能对比指南
httpx·requests·aiohttp
SunnyRivers1 个月前
Python 的下一代 HTTP 客户端 HTTPX 特性详解
python·httpx
深蓝电商API1 个月前
httpx库异步爬虫实战对比aiohttp
爬虫·httpx
qq_381454991 个月前
Python httpx:现代HTTP客户端全解析
httpx
曲幽1 个月前
FastAPI异步多线程:从踩坑到精通,解锁高性能API的正确姿势
python·flask·fastapi·web·thread·async·httpx·asyncio