python-3.x - 将 aiohttp 请求与其响应相关联

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

很简单,我只想将来自 aiohttp 的回复联系起来。带有标识符(例如字典键)的异步 HTTP 请求,以便我知道哪个响应对应于哪个请求。

例如,下面的函数调用后缀为 dict 值 1 的 URI。 , 23 .如何修改它以返回与每个结果关联的键?我只需要能够跟踪哪个请求是哪个......对于熟悉 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, ...}}

最佳答案

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

关于python-3.x - 将 aiohttp 请求与其响应相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36893468/

相关文章:

Python aiohttp 请求停止但没有引发异常

python - django 中的关系数据库以弹出形式

python-3.x - 在远程服务器上执行 tensorflow python3,子进程无法解释所有 tensorflow 输入 args。导入错误 : No module named 'scripts'

python - 将列表内的整数转换为字符串,然后转换为 python 3.x 中的日期

python - 如何在 Python 中从 API 结果创建数据框

python - 使用请求从谷歌距离矩阵 api 获取响应时出现连接错误

python - 如何使用 Python 请求清除缓存?

python - 使用 twitter API 进行复杂查询 - python 包装器

python 3.6 协程从未被期待

python - 异步: sleep for sub-millisecond interval