使用协程库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)
相关推荐
cliffordl21 小时前
python 基于 httpx 的流式请求
开发语言·python·httpx
万粉变现经纪人2 天前
如何解决pip安装报错ModuleNotFoundError: No module named ‘tkinter’问题
python·beautifulsoup·pandas·pip·策略模式·httpx·scipy
照物华2 个月前
httpx[http2] 和 httpx 的核心区别及使用场景如下
python·httpx
猫猫村晨总2 个月前
网络爬虫学习之httpx的使用
爬虫·python·httpx
老胖闲聊2 个月前
Python httpx库终极指南
开发语言·python·httpx
浪裡遊2 个月前
利用flask设计接口
前端·后端·python·flask·web3.py·httpx
小军要奋进3 个月前
httpx模块的使用
笔记·爬虫·python·学习·httpx
Maybe_95274 个月前
httpx.AsyncClient()的stream方法设置timeout超时
python·httpx·流式接口超时
数据知道5 个月前
python中httpx库的详细使用及案例
开发语言·爬虫·python·httpx
Maybe_95275 个月前
python使用httpx_sse调用sse流式接口对响应格式为application/json的错误信息的处理
python·sse·httpx