将aiohttp请求与其响应相关联

时间:2016-04-27 14:53:40

标签: python-3.x python-requests python-asyncio aiohttp

很简单,我只想将来自process.Start(); process.CloseMainWindow(); 异步HTTP请求的响应与标识符(例如dictonary key)相关联,以便我知道哪个响应对应于哪个请求。

例如,下面的函数调用以dict值process.Start(); while (process.MainWindowHandle == IntPtr.Zero) { process.Refresh(); } var handle = process.MainWindowHandle; ShowWindow(handle, 0) //ShowWindow from user32.dll aiohttp1为后缀的URI。如何修改以返回与每个结果相关联的键?我只需要能够跟踪哪个请求是哪个......对于熟悉2

的人来说无疑是微不足道的
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)

1 个答案:

答案 0 :(得分:4)

将密钥传递给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())