3
非常簡單,我只想將來自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, ...}}
謝謝,這正是我所追求的。我注意到你在'main()'裏面打開'ClientSession()'而不是'fetch()' - 這只是一個偏好問題? –
@bedeabc更好的問題爲什麼你需要在這裏多次會議? – jfs
@ j-f-sebastian謝謝,我明白了你的觀點。我正在使用以下文章中的模式:http://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html –