2016-04-27 64 views
3

非常簡單,我只想將來自aiohttp的異步HTTP請求的響應與標識符(例如dictonary關鍵字)相關聯,以便我知道哪個響應對應於哪個請求。將aiohttp請求與其響應進行關聯

例如,下面的函數調用後綴爲字典值1,23的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, ...}} 

回答

3

傳遞密鑰到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()) 
+0

謝謝,這正是我所追求的。我注意到你在'main()'裏面打開'ClientSession()'而不是'fetch()' - 這只是一個偏好問題? –

+1

@bedeabc更好的問題爲什麼你需要在這裏多次會議? – jfs

+0

@ j-f-sebastian謝謝,我明白了你的觀點。我正在使用以下文章中的模式:http://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html –