0

这是我的代码

@pytest.mark.asyncio
async def test_async():
    res = []
    for file_id in range(100):
        result = await get_files_async(file_id)
        res.append(result)
    assert res == [200 for _ in range(100)]


async def get_files_async(file_id):
    kwargs = {"verify": False, "cert": (cert, key)}
    resp = requests.request('GET', url, **kwargs)
    return resp.status_code

pytest 的时间显示需要 118 秒才能完成,这非常接近按顺序向 url 发送请求的测试。有什么改进可以加快这个测试吗?谢谢。

4

1 回答 1

1

您无法使用异步加速此操作,因为您使用requests的是同步 pkg,因此每次调用都会停止偶数循环。

您可以切换到在线程中运行请求或切换到异步 pkg,如 httpx 或 aiohttp

如果您确实切换到不同的 pkg,请将其更改test_async为此以并行运行请求

@pytest.mark.asyncio
async def test_async():
    tasks = []
    for file_id in range(100):
        tasks.append(asyncio.create_task(get_files_async(file_id)))
    res = await asyncio.gather(*tasks)
    assert res == [200 for _ in range(100)]
于 2021-11-04T08:37:29.430 回答