【发布时间】:2021-02-13 19:10:12
【问题描述】:
我是 Async 编程、Asyncio、Aiohttp 世界的新手。
我有多个请求 - 第一个请求的输出被用作第二个请求的参数。
到目前为止,我已经尝试了这么多 -
import aiohttp
import asyncio
async def get_response(session, url, params):
async with session.get(url=url, params=params) as response:
response = await response.json()
return response['output']
async def main():
tasks = []
url = "https://example.api.com/"
url_1 = url + 'path_1'
url_2 = url + 'path_2'
params = {'name': "Hello"}
async with aiohttp.ClientSession() as session:
a1 = get_response(session, url_1, params)
tasks.append(a1)
params = {'name': a1}
b1 = get_response(session, url_2, params)
tasks.append(b1)
responses = await asyncio.gather(*tasks, return_exceptions=True)
print(responses)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
我收到了这个很明显的错误 -
TypeError("Invalid variable type: value should be str, int or float, got <coroutine object get_response at 0x00000000037FA6C0> of type <class 'coroutine'>")
那么我如何将第一个请求的输出而不是协程对象传递给第二个请求 -
params = {'name': a1}
b1 = get_response(session, url_2, params)
【问题讨论】:
-
您好,请问我的回答对您的问题有帮助吗?
标签: asynchronous async-await python-asyncio aiohttp