使用协程库httpx并发请求

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

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

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)

相关推荐

  1. 使用httpx并发请求

    2024-03-12 08:04:02       44 阅读
  2. ——面试问题

    2024-03-12 08:04:02       30 阅读
  3. 并发编程2-掌握C#线使用

    2024-03-12 08:04:02       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-12 08:04:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-12 08:04:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-12 08:04:02       82 阅读
  4. Python语言-面向对象

    2024-03-12 08:04:02       91 阅读

热门阅读

  1. 测试推拉视频

    2024-03-12 08:04:02       40 阅读
  2. 前端前置知识pnpm

    2024-03-12 08:04:02       43 阅读
  3. 分布式ID(7):Zookeeper实现分布式ID生成

    2024-03-12 08:04:02       44 阅读
  4. vue的axios是干什么的

    2024-03-12 08:04:02       45 阅读
  5. 迷宫可行路径数

    2024-03-12 08:04:02       49 阅读
  6. P1177 【模板】排序

    2024-03-12 08:04:02       43 阅读
  7. WebGL之使用纹理

    2024-03-12 08:04:02       38 阅读