question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Question about Request.Body()

See original GitHub issue

Hi dears developers, how can I retrieve the request.body inside an exception_handler?

My scenario:

I have an exception_handler hook that receives a request and an exception, I’m also using FastApi which tries to parse the body to a JSON, if it does not work it raises an HTTPException. So I’m trying to build a hook to log invalid JSON requests, this exception is being correctly captured by my exception_handler but when I’m trying to retrieve the body I can’t it hangs, it simple doesn’t work. It does make sense as after reading for the first time it is being cached inside the Request object but the Request object is being recreated before calling the exception_handler so I’m losing my cache and I’m able to ready from the stream again.

https://github.com/encode/starlette/blob/d23bfd0d8ff68d535d0283aa4099e5055da88bb9/starlette/exceptions.py#L79

Not sure if it is supposed to be like this by design, but I think my scenario is not that fancy, it should be something possible, what do you guys think? Any workaround?

My code:

async def httpexception_logger(request: Request, exc: HTTPException):
    body = await request.body()
    text: str = bytes.decode(body)
    logger.error("Exception at %s, status code: %s, body: %s: exception %s", request.url, exception.status_code, text, exc)
    ... other stuff...

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:8
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

16reactions
kataevcommented, Sep 4, 2019

Any movements? Without this functionality, we don’t have access to origin request on exception handler. This is really strange.

0reactions
ricardomommcommented, May 2, 2019

@tomchristie , I was reading your comments related to @blueyed changes to store the Request in the Scope and I completely agree that Request should reflect scope, and as scope is used to construct a request perhaps a small change to store/cache the body inside the scope instead of a local var, do you think this could solve this issue?

I did this changes locally just to test and it seems to work but I have not enough knowledge about the impact it may cause:

requests.py@140…171


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

        if self._stream_consumed:
            raise RuntimeError("Stream consumed")

        self._stream_consumed = True
        while True:
            message = await self._receive()
            if message["type"] == "http.request":
                body = message.get("body", b"")
                if body:
                    yield body
                if not message.get("more_body", False):
                    break
            elif message["type"] == "http.disconnect":
                self._is_disconnected = True
                raise ClientDisconnect()
        yield b""

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

Read more comments on GitHub >

github_iconTop Results From Across the Web

Request.body - Web APIs - MDN Web Docs
The read-only body property of the Request interface contains a ReadableStream with the body contents that have been added to the request.
Read more >
HTTP GET with request body - Stack Overflow
Alas the problem with PUT is that the request body has very precise semantics. Specifically, the PUT "requests that the state of the...
Read more >
Rest request body is sometimes truncated - Microsoft Q&A
I have an Asp.net API app where one of the API's requests are randomly missing some of the body's content starting from the...
Read more >
Unity API Request body Question - Connect CG to host - Dell
What ist the right format of the Request body? Headers. Accept: application/json. Content-Type: application/json. X-EMC-REST-CLIENT: true. EMC- ...
Read more >
How to read REQUEST body - Salesforce Stack Exchange
request.requestBody.toString() ); Map<String, Object> traits = (Map<String ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found