非常简单,我只想将来自aiohttp
异步 HTTP 请求的响应与标识符(例如字典键)相关联,以便我知道哪个响应对应于哪个请求。
例如,下面的函数调用以 dict values 和 为后缀1
的2
URI 3
。如何修改它以返回与每个结果关联的键?我只需要能够跟踪哪个请求是哪个......对于熟悉的人来说无疑是微不足道的asyncio
import asyncio
import aiohttp
items = {'a': '1', 'b': '2', 'c': '3'}
def async_requests(items):
async def fetch(item):
url = 'http://jsonplaceholder.typicode.com/posts/'
async with aiohttp.ClientSession() as session:
async with session.get(url + item) as response:
return await response.json()
async def run(loop):
tasks = []
for k, v in items.items():
task = asyncio.ensure_future(fetch(v))
tasks.append(task)
responses = await asyncio.gather(*tasks)
print(responses)
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(loop))
loop.run_until_complete(future)
async_requests(items)
输出(缩写):
[{'id': 2, ...}, {'id': 3, ...}, {'id': 1...}]
期望的输出(例如):
{'b': {'id': 2, ...}, 'c': {'id': 3, ...}, 'a': {'id': 1, ...}}