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

问题描述 投票:1回答:1

我不了解异步请求如何工作。这里我有一个使用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)

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

python asynchronous post python-asyncio aiohttp
1个回答
2
投票
为什么我可以不等待而读取响应状态?
因为您在编写async with session.post(...)时已经隐式等待它。 async with session.post(...) as response读取响应

header,并将其数据公开在response对象中。状态代码到达响应的最开始,可用于任何正确的响应。

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

© www.soinside.com 2019 - 2024. All rights reserved.