python - 在 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()
返回一个我无法从中检索实际响应的协程。
我想我可能不明白一些事情,但我认为等待未来应该在它准备好时返回实际值。
我哪里错了?
解决方案
你是对的,你在等待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()
推荐阅读
- typescript - Express SSE - 向会话用户广播
- c++ - Eigen 在不存储中间结果时给出错误的结果
- java - 当TUIO基准进入处理中的目标框时,如何使TUIO基准将背景更改为不同的图像?
- vega - 在 vega 中刷/链接(不是 vega-lite)
- java - “Java 方法是元数据”是什么意思?
- objective-c - 应用非标准电源断言和创建虚拟 HID
- python-3.x - python以不同的顺序打印字典
- node.js - 使用电子代理的 Nightmarejs
- java - 需要使用 IntelliJ 更改 GUI 上的背景,但背景隐藏了按钮
- c - Difference between array of pointers and pointer to array?