aio-libs / aiohttp

Asynchronous HTTP client/server framework for asyncio and Python
https://docs.aiohttp.org
Other
14.96k stars 1.99k forks source link

Behaviour post/json request content vs. method read() #2914

Open Pajinek opened 6 years ago

Pajinek commented 6 years ago

Long story short

I have created middleware for forwarding requests and I need to read content of them. I figure out behaviour that it is rather strange for me.

I send request (post/get) and text/read return body of message (post/json data is included). But content (StreamReader instance,) returns empty string.

And documentation says:

content A StreamReader instance, input stream for reading request’s BODY. Read-only property.

Expected behaviour

I suppose that content is body of message (https://docs.aiohttp.org/en/stable/web_reference.html#aiohttp.web.BaseRequest.content)

Actual behaviour

Method request.content.read() return empty string as result.

Steps to reproduce

send request: 1) await test_app.post("/get_fce", data={"hello": "kitty"})

 >>> print(await request.read())
b'hello=kitty'
 >>>  print(await request.text())
hello=kitty
 >>>  print(await request.content.read())
b''

2) await test_app.post("/get_fce", json={"hello": "kitty"})

 >>> print(await request.read())
b'{"hello": "kitty"}'
 >>> print(await request.text())
{"hello": "kitty"}
 >>> print(await request.content.read())
b''

Your environment

aiohttp==3.1.0 aioredis==1.1.0 async-timeout==2.0.1 # via aiohttp attrs==17.4.0 # via aiohttp chardet==3.0.4 # via aiohttp idna-ssl==1.0.1 # via aiohttp multidict==4.1.0 # via aiohttp, yarl ujson==1.35 yarl==1.1.1

asvetlov commented 6 years ago

The problem is that request.content is a stream. If you read the stream in middleware -- you cannot read it again in web handler. Please be careful with middleware's code.

Pajinek commented 6 years ago

Hi. I think that is really important information and it should be notice in documentation. Right? Thanks for your answer and help.

asvetlov commented 6 years ago

If you would make a PR for documentation clarification -- you are welcome.

ghost commented 3 years ago

i fell into this gotcha as well!