Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#493 and #495 cache body content #500

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 new_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