为什么返回空字节作为响应?
Why are empty bytes returned as a response?
我正在学习 python 异步。我的问题是我试图以流媒体内容的形式获得答案,但由于我没有尝试,所以总是出现空字节。是什么原因?我究竟做错了什么?
我选择 Github API 作为示例。
我用的是版本python3.8,aiohttp 3.7.4。
这是我的代码:
导入 json
导入 aiohttp
导入异步
异步定义 get_response():
url = 'https://api.github.com/events'
与 aiohttp.ClientSession() 作为会话异步:
task1 = asyncio.create_task(make_request(会话, url))
结果 = 等待 asyncio.gather(任务 1)
return 结果
async def make_request(session, url):
async with session.get(url) as resp:
json_resp = await resp.json(loads=json.loads)
bytes_resp = await resp.content.read(10)
print(json_resp)
print(bytes_resp)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(get_response())
非常感谢。
得到这个
enter image description here
您不能既以 JSON 形式读取一次响应,又以字节形式再次读取响应,因为此时它已经被消耗掉了。 (aiohttp 故意不在内部缓冲响应数据。)
如果两者都需要,
bytes_resp = await resp.content.read()
json_resp = json.loads(bytes_resp)
我正在学习 python 异步。我的问题是我试图以流媒体内容的形式获得答案,但由于我没有尝试,所以总是出现空字节。是什么原因?我究竟做错了什么? 我选择 Github API 作为示例。
我用的是版本python3.8,aiohttp 3.7.4。
这是我的代码: 导入 json 导入 aiohttp 导入异步 异步定义 get_response(): url = 'https://api.github.com/events' 与 aiohttp.ClientSession() 作为会话异步: task1 = asyncio.create_task(make_request(会话, url)) 结果 = 等待 asyncio.gather(任务 1) return 结果
async def make_request(session, url):
async with session.get(url) as resp:
json_resp = await resp.json(loads=json.loads)
bytes_resp = await resp.content.read(10)
print(json_resp)
print(bytes_resp)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(get_response())
非常感谢。
得到这个 enter image description here
您不能既以 JSON 形式读取一次响应,又以字节形式再次读取响应,因为此时它已经被消耗掉了。 (aiohttp 故意不在内部缓冲响应数据。)
如果两者都需要,
bytes_resp = await resp.content.read()
json_resp = json.loads(bytes_resp)