python - 为什么 aiohttp 比 run_in_executor 包装的请求慢?

标签 python python-requests aiohttp python-asyncio

全部!

我需要向 Web 服务发出大约 10,000 个请求,并且我希望得到 JSON 响应。由于请求是相互独立的,所以我想并行运行它们。我认为 aiohttp 可以帮助我解决这个问题。我编写了以下代码:

import asyncio
import aiohttp


async def execute_module(session: aiohttp.ClientSession, module_id: str,
                         post_body: dict) -> dict:
    headers = {
        'Content-Type': r'application/json',
        'Authorization': fr'Bearer {TOKEN}',
    }

    async with session.post(
            fr'{URL}/{module_id}/steps/execute',
            headers=headers,
            json=post_body,
    ) as response:
        return await response.json()


async def execute_all(campaign_ids, post_body):
    async with aiohttp.ClientSession() as session:
        return await asyncio.gather(*[
            execute_module(session, campaign_id, post_body)
            for campaign_id in campaign_ids
        ])

campaign_ids = ['101', '102', '103'] * 400
post_body = {'inputs': [{"name": "one", "value": 1}]}

print(asyncio.run(execute_all(campaign_ids, post_body)))

附注我提出了 1,200 个测试请求。

解决该问题的另一种方法 - 将 requests.post 包装在 run_in_executor 函数中。我知道在异步函数中使用阻塞代码是错误的,但它运行得更快(~ 7 秒 vs. aiohttp 的~ 10 秒)

import requests
import asyncio


def execute_module(module_id, post_body):
    headers = {
        'Content-Type': r'application/json',
        'Authorization': fr'Bearer {TOKEN}',
    }

    return requests.post(
        fr'{URL}/{module_id}/steps/execute',
        headers=headers,
        json=post_body,
    ).json()

async def execute_all(campaign_ids, post_body):
    loop = asyncio.get_running_loop()
    return await asyncio.gather(*[
        loop.run_in_executor(None, execute_module, campaign_id, post_body)
        for campaign_id in campaign_ids
    ])

campaign_ids = ['101', '102', '103'] * 400
post_body = {'inputs': [{"name": "one", "value": 1}]}

print(asyncio.run(execute_all(campaign_ids, post_body)))

我做错了什么?

最佳答案

您尝试过 uvloop - https://github.com/MagicStack/uvloop ?这应该会提高 aiohttp 请求的速度

关于python - 为什么 aiohttp 比 run_in_executor 包装的请求慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58996572/

相关文章:

python - Django 单元测试和模拟请求模块

python-3.x - 使用 asyncio.wait FIRST_COMPLETED 时如何处理异常?

python - 运行时错误 : There is no current event loop in thread in async + apscheduler

python - Mypy 无法从文字列表中推断出项目的类型

java - 以所有可能的方式将列表拆分为两个子列表

python - django 和 Python 代码中的多处理

Python SSL 请求和让我们加密证书

python - "Get"来自 cosmosdb 的 id 文档(不知道 _rid)

python-3.7 - aiohttp - 如何在类命名空间中保存持久 session

python - 模块 'tensorflow.contrib.learn' 没有属性 'python'