为什么我应该等待response.read(),但是我不需要等待response.status?

时间:2020-03-14 18:28:58

标签: python asynchronous post python-asyncio aiohttp

我不了解异步请求的工作方式。这里有一个使用POST请求发送图像的函数:

async def post_img(in_url, in_filepath, in_filename):
with open(in_filepath, 'rb') as file:
    in_files = {'file': file}
    async with ClientSession() as session:
        async with session.post(in_url, data=in_files) as response:
            status = response.status
            response = await response.read()
            print(response)

为什么我可以不等待而读取响应状态?如果我不等待请求完成,如何知道请求已完成?

1 个答案:

答案 0 :(得分:2)

为什么我无需等待即可读取响应状态?

因为您在编写async with session.post(...)时已经隐式等待它。 async with session.post(...) as response读取响应 header ,并将其数据公开在response对象中。状态代码到达响应的最开始,可用于任何正确的响应。

您必须使用await response.read()等待响应 body ,因为body的内容不是请求对象的一部分。由于身体可以是任意大小,因此自动读取它可能会花费太多时间并耗尽可用内存。

相关问题