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

Fix: Caching of request body for passing down to middlewares #2387

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
2 changes: 1 addition & 1 deletion starlette/middleware/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class _CachedRequest(Request):
"""

def __init__(self, scope: Scope, receive: Receive):
super().__init__(scope, receive)
super().__init__(scope, receive, enable_request_caching=True)
self._wrapped_rcv_disconnected = False
self._wrapped_rcv_consumed = False
self._wrapped_rc_stream = self.stream()
Expand Down
18 changes: 17 additions & 1 deletion starlette/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,8 @@ class Request(HTTPConnection):
_form: typing.Optional[FormData]

def __init__(
self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send
self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send,
enable_request_caching: bool = False
):
super().__init__(scope)
assert scope["type"] == "http"
Expand All @@ -198,6 +199,8 @@ def __init__(
self._stream_consumed = False
self._is_disconnected = False
self._form = None
if not hasattr(self.state, 'enable_request_caching'):
setattr(self.state, 'enable_request_caching', enable_request_caching)

@property
def method(self) -> str:
Expand Down Expand Up @@ -233,6 +236,9 @@ async def body(self) -> bytes:
async for chunk in self.stream():
chunks.append(chunk)
self._body = b"".join(chunks)
# cache body
if getattr(self.state, 'enable_request_caching', False):
setattr(self.state, 'req_body', self._body)
return self._body

async def json(self) -> typing.Any:
Expand Down Expand Up @@ -272,6 +278,10 @@ async def _get_form(
self._form = await form_parser.parse()
else:
self._form = FormData()
# cache form data
if getattr(self.state, 'enable_request_caching', False):
setattr(self.state, 'req_body', self._form)

return self._form

def form(
Expand Down Expand Up @@ -313,3 +323,9 @@ async def send_push_promise(self, path: str) -> None:
await self._send(
{"type": "http.response.push", "path": path, "headers": raw_headers}
)

@property
def cached_req_body(self) -> typing.Union[bytes, str, FormData, None]:
if not hasattr(self.state, 'enable_request_caching'):
raise RuntimeError('Caching is not enabled')
return getattr(self.state, 'req_body', None)
Loading