首页 > 解决方案 > 在 Python3.5 asyncio 中等待后无法访问 Http 请求数据

问题描述

我一直在尝试使用 Python3.5 aiohttp 并编写了这个简单的包装函数 -

 async def perform_async_http(self, url, method, data='', headers={}):
    async with aiohttp.ClientSession() as session:
        if method.lower() == 'get':
            async with session.get(url, headers=headers) as response:
                return response
        async with session.post(url, data=data, headers=headers) as response:
            return response

然后,我有以下使用此功能的代码-

http_future = self.perform_async_http(url, "post", data, headers)
res = await http_future
print(res.json())

问题是res.json()orres.text()返回一个协程。访问类似的属性res.status效果很好,但是text()或者json()返回一个我无法从中检索实际响应的协程。

我想我可能不明白一些事情,但我认为等待未来应该在它准备好时返回实际值。

我哪里错了?

标签: pythonpython-3.xpython-3.5aiohttppytest-aiohttp

解决方案


你是对的,你在等待request你创造的未来。但是,当这个未来完成并且您得到响应时,还不清楚响应的所有内容是否都可用。

因此,对某些响应负载本身的访问是您必须等待的未来。

您可以在aiohttp.ClientResponse 文档中看到这一点:

协程json(*, encoding=None,loads=json.loads, content_type='application/json')

以 JSON 格式读取响应的正文,使用指定的编码和加载器返回 dict。如果数据仍然不可用,将执行读取调用 (...)

这应该可以按您的预期工作:

 async def perform_async_http(self, url, method, data='', headers={}):
    async with aiohttp.ClientSession() as session:
        if method.lower() == 'get':
            async with session.get(url, headers=headers) as response:
                return await response.json()
        async with session.post(url, data=data, headers=headers) as response:
            return await response.json()

推荐阅读