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

Added request body cache to Request.receive #848

Closed
wants to merge 10 commits into from
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ test.db
.mypy_cache/
starlette.egg-info/
venv/
.python-version
15 changes: 15 additions & 0 deletions starlette/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
import typing
from collections.abc import Mapping
from urllib.parse import urlencode
from http import cookies as http_cookies

from starlette.datastructures import URL, Address, FormData, Headers, QueryParams, State
Expand Down Expand Up @@ -188,6 +189,20 @@ def method(self) -> str:

@property
def receive(self) -> Receive:
body = None

if hasattr(self, "_body"):
body = self._body
elif hasattr(self, "_form"):
body = bytes(urlencode(dict(self._form)), "utf-8")

if body is not None:

async def cached_receive() -> Message:
return dict(type="http.request", body=body)

return cached_receive

return self._receive

async def stream(self) -> typing.AsyncGenerator[bytes, None]:
Expand Down
30 changes: 30 additions & 0 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,36 @@ async def app(scope, receive, send):
assert response.json() == {"body": "<stream consumed>", "stream": "abc"}


def test_request_body_then_request_body():
async def app(scope, receive, send):
request = Request(scope, receive)
body = await request.body()
request2 = Request(scope, request.receive)
body2 = await request2.body()
response = JSONResponse({"body": body.decode(), "body2": body2.decode()})
await response(scope, receive, send)

client = TestClient(app)

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


def test_request_form_then_request_form():
async def app(scope, receive, send):
request = Request(scope, receive)
form = await request.form()
request2 = Request(scope, request.receive)
form2 = await request2.form()
response = JSONResponse({"form": dict(form), "form2": dict(form2)})
await response(scope, receive, send)

client = TestClient(app)

response = client.post("/", data={"abc": "123 @"})
assert response.json() == {"form": {"abc": "123 @"}, "form2": {"abc": "123 @"}}


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