Skip to content

Commit

Permalink
encode#493 and encode#495 cache body content
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardomomm committed May 2, 2019
1 parent d23bfd0 commit d388e06
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
10 changes: 5 additions & 5 deletions starlette/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,8 @@ def receive(self) -> Receive:
return self._receive

async def stream(self) -> typing.AsyncGenerator[bytes, None]:
if hasattr(self, "_body"):
yield self._body
if "body" in self._scope:
yield self._scope["body"]
yield b""
return

Expand All @@ -162,12 +162,12 @@ async def stream(self) -> typing.AsyncGenerator[bytes, None]:
yield b""

async def body(self) -> bytes:
if not hasattr(self, "_body"):
if not "body" in self._scope:
body = b""
async for chunk in self.stream():
body += chunk
self._body = body
return self._body
self._scope["body"] = body
return self._scope["body"]

async def json(self) -> typing.Any:
if not hasattr(self, "_json"):
Expand Down
17 changes: 17 additions & 0 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,23 @@ async def app(scope, receive, send):
assert response.json() == {"body": "<stream consumed>", "stream": "abc"}


def test_request_body_twice():
async def app(scope, receive, send):
request = Request(scope, receive)
body = await request.body()
new_request = Request(scope, receive)
new_body = await request.body()
response = JSONResponse(
{"body_one": body.decode(), "body_two": new_body.decode()}
)
await response(scope, receive, send)

client = TestClient(app)

response = client.post("/", data="abc")
assert response.json() == {"body_one": "abc", "body_two": "abc"}


def test_request_json():
async def app(scope, receive, send):
request = Request(scope, receive)
Expand Down

0 comments on commit d388e06

Please sign in to comment.