Cache Request in scope via __new__ method
See original GitHub issueThe starting point for issues should usually be a discussion…
https://github.com/encode/starlette/discussions
Possible bugs may be raised as a “Potential Issue” discussion, feature requests may be raised as an “Ideas” discussion. We can then determine if the discussion needs to be escalated into an “Issue” or not.
This will help us ensure that the “Issues” list properly reflects ongoing or needed work on the project.
- Initially raised as discussion #495
On consuming the body there have been lots of discussions. The root reason of this problem is that Request
is initialized here and there, and the caching _body
logic does not work.
In order to resolve this, @alex-oleshkevich proposed an idea to cache the Request
in scope by introducing __new__
as below:
diff --git a/starlette/requests.py b/starlette/requests.py
index 66c510c..69cad4c 100644
--- a/starlette/requests.py
+++ b/starlette/requests.py
@@ -188,11 +188,22 @@ async def empty_send(message: Message) -> typing.NoReturn:
class Request(HTTPConnection):
+ def __new__(
+ cls, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send
+ ):
+ if "request" in scope:
+ return scope["request"]
+
+ obj = object.__new__(cls)
+ scope["request"] = obj
+ return obj
+
I’ve confirmed locally this succinct notion solves the original problem and it should not take us lots of time to test.
Issue Analytics
- State:
- Created a year ago
- Comments:11 (9 by maintainers)
Top GitHub Comments
@kigawas I am sorry if closing it was a bit premature, hadn’t had my coffee yet and was just trying to keep the repo organized. Let me know if you want me to re-open it, happy to do so.
Here’s a runnable example:
@Kludex should we add something like this to #1656 ?