将aiohttp请求与其响应进行关联
问题描述:
非常简单,我只想将来自aiohttp
的异步HTTP请求的响应与标识符(例如dictonary关键字)相关联,以便我知道哪个响应对应于哪个请求。将aiohttp请求与其响应进行关联
例如,下面的函数调用后缀为字典值1
,2
和3
的URI。如何修改它以返回与每个结果关联的键?我只需要能够跟踪哪些要求是......毫无疑问,平凡的人熟悉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, ...}}
答
传递密钥到fetch()
,返回它们的相应回应:
#!/usr/bin/env python
import asyncio
import aiohttp # $ pip install aiohttp
async def fetch(session, key, item, base_url='http://example.com/posts/'):
async with session.get(base_url + item) as response:
return key, await response.json()
async def main():
d = {'a': '1', 'b': '2', 'c': '3'}
with aiohttp.ClientSession() as session:
####tasks = map(functools.partial(fetch, session), *zip(*d.items()))
tasks = [fetch(session, *item) for item in d.items()]
responses = await asyncio.gather(*tasks)
print(dict(responses))
asyncio.get_event_loop().run_until_complete(main())
谢谢,这正是我所追求的。我注意到你在'main()'里面打开'ClientSession()'而不是'fetch()' - 这只是一个偏好问题? –
@bedeabc更好的问题为什么你需要在这里多次会议? – jfs
@ j-f-sebastian谢谢,我明白了你的观点。我正在使用以下文章中的模式:http://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html –