SangminKim
SangminKim

Reputation: 9146

Why does aiohttp need await to get body?

I found aiohttp server should use await keyword to get Request Body

async def handler(request):
  body = await request.json(). # or text(), read()

I think when the handler is called, the request body is already in server side memory and I don't think it is I/O intensive work, needing asynchronous operation.

Any missing point?

Upvotes: 2

Views: 1159

Answers (2)

BlackBear
BlackBear

Reputation: 22989

On the contrary, they are not in memory. Quoting the documentation:

While methods read(), json() and text() are very convenient you should use them carefully. All these methods load the whole response in memory. For example if you want to download several gigabyte sized files, these methods will load all the data in memory. Instead you can use the content attribute.

Also see the other answer for the inner workings of the HTTP protocol.

Upvotes: 3

DurandA
DurandA

Reputation: 1549

With a very large request message-body, you might not have received the complete body when the handler is called. HTTP1/1 states that the server might answer before the end of the request (from RFC 2616):

An HTTP/1.1 (or later) client sending a message-body SHOULD monitor the network connection for an error status while it is transmitting the request. If the client sees an error status, it SHOULD immediately cease transmitting the body.

So you could for example reply with an 4xx Client error code immediately if you do not accept the request (e.g. 401 Unauthorized if the token is invalid) before receiving the whole request message-body.

Upvotes: 4

Related Questions