【发布时间】: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