Question about Request.Body()
See original GitHub issueHi 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.
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:
- Created 4 years ago
- Reactions:8
- Comments:7 (2 by maintainers)
Top GitHub Comments
Any movements? Without this functionality, we don’t have access to origin request on exception handler. This is really strange.
@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