使用协程库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)
相关推荐
数据知道6 天前
如何使用 httpx + SQLAlchemy 异步高效写入上亿级图片链接与MD5到 PostgreSQL
数据库·postgresql·httpx
曲幽11 天前
重构FastAPI生产部署:用异步网关与无服务器计算应对高并发
python·serverless·fastapi·web·async·httpx·await·asyncio
maozexijr13 天前
Rabbit MQ是如何保证消息不丢失的?
httpx
泡泡以安17 天前
【爬虫教程】第4章:HTTP客户端库深度定制(httpx/aiohttp)
爬虫·http·httpx
清水白石00821 天前
构建高性能异步 HTTP 客户端:aiohttp 与 httpx 实战解析与性能优化
python·http·性能优化·httpx
时光803.1 个月前
快速搭建青龙面板Docker教程
windows·ubuntu·bash·httpx
清水白石0081 个月前
《requests vs httpx:Python 网络请求库的全面对比与实战指南》
网络·python·httpx
哆来A梦没有口袋2 个月前
Python入门学习三
httpx·requests·python的async·python的await·python的http·python的http请求·python的异步
介一安全4 个月前
资产信息收集与指纹识别:HTTPX联动工具实战指南
网络安全·安全性测试·httpx·安全工具
网硕互联的小客服4 个月前
SSL部署完成,https显示连接不安全如何处理?
ssl·httpx