Why should I await response.read(), but I don't need to await response.status?

Viewed 1005

I don't understand how asynchronous requests work. Here I have a function that sends an image using a POST request:

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)

Why I can read response status without awaiting it? How can I tell that request is done if I am not waiting for it to finish?

1 Answers

Why I can read response status without awaiting it?

Because you have already awaited it implicitly when you wrote async with session.post(...). async with session.post(...) as response reads the response header, and exposes its data in the response object. The status code arrives the very beginning of the response and is available for any correct response.

You have to await the response body using await response.read() because the contents of the body is not part of the request object. Since the body can be of arbitrary size, reading it automatically might take too much time and exhaust available memory.

Related