【问题标题】:Python - how to get async result? [duplicate]Python - 如何获得异步结果? [复制]
【发布时间】:2021-08-18 13:05:23
【问题描述】:

我有异步 REST API 请求的代码,它应该发出相当多的异步 API 请求(彼此独立),从结果中收集 JSON 并返回一个列表。我将asyncio 和aiohttp 用于异步位。

我的代码:

async def async_get_clients_events(
    client: ApiClient,
    client_tokens: List[ClientToken]
):
    async with ClientSession() as session:
        tasks = [
            async_get_single_organization_events(
                client, ct.client_id, ct.private_token, session
            )
            for ct in client_tokens
        ]

        results = await asyncio.gather(*tasks)

    return results


async def async_get_single_client_events(
    client: ApiClient,
    client_id: str,
    api_key: Optional[str] = None,
    session: ClientSession = None,
) -> List[Dict]:
    if api_key is not None:
        headers = get_default_headers()
        headers["Authorization"] = "Bearer " + client.api_key
    else:
        headers = get_default_headers()

    # prepare request parameters, a bit of code omitted

    events = await asyncio.gather(async_get(session, url, headers, return_json=True))

    return events


async def async_get(
    session: ClientSession,
    url: str,
    headers: Dict[str, str] = None,
    params: Dict[str, Any] = None,
    return_json: bool = True,
) -> ClientResponse:
    headers = headers if headers is not None else {}
    params = params if params is not None else {}

    response = await session.request(
        method="GET", url=url, headers=headers, params=params
    )
    response.raise_for_status()
    if return_json:
        return await response.json()
    else:
        return response

问题:如何在async_get_clients_events 中收集结果?我只希望请求是异步的,之后我想等待所有结果并收集它们。

【问题讨论】:

    标签: python rest asynchronous async-await aiohttp


    【解决方案1】:

    事实证明,Python 中的异步函数不是函数,而是协程,并且它们在调用时不会运行。它们更像类对象,需要单独的方法调用才能实际执行它们。

    上面的代码是用async_get_clients_events(client, client_tokens)调用执行的,我认为这显然是正确的。它不是。固定版本:

    task = async_get_organizations_events(self, organizations_tokens)
    results = asyncio.run(task)
    

    我从link 1、link 2得到这个问题。

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 2013-05-14
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多