使用协程库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)
相关推荐
CodeZ-Hao12 天前
httpx上传文件/IO流缓慢的问题分析及解决
python·压力测试·httpx
waketzheng1 个月前
httpx.AsyncClient报错ProxyError: 504 Gateway Time-out
gateway·httpx
SunnyRivers1 个月前
基础库httpx的使用
爬虫·httpx
xybm16052 个月前
Dowex 50WX8 ion-exchange resin可以用于去除水中的金属离子(如钠、钾、镁、钙等)和其他杂质,提高水质,11119-67-8
python·flask·httpx·tornado
Learner_HJ4 个月前
猿人学 — 第1届第17题(解题思路附源码)
python·网络爬虫·httpx·猿人学
@技术无疆4 个月前
【Python】FeinCMS:轻量级且可扩展的Django内容管理系统
数据库·python·django·sqlite·pip·pygame·httpx
Tony聊跨境5 个月前
HTTPX 与 AIOHTTP 与 Requests:选择哪个?
运维·tcp/ip·ip·教育电商·httpx
开出南方的花5 个月前
python进阶篇-day05-网络编程(TCP)与进程
开发语言·网络·python·网络协议·numpy·tcp·httpx
溟洵6 个月前
网络协议栈应用层的意义(内含思维导图和解析图通俗易懂超易理解)
网络·网络协议·计算机网络·http·httpx
小鸿的摸鱼日常6 个月前
httpx,一个网络请求的 Python 新宠儿
python·httpx·python 库之旅