fix _read_request_body to re-use parsed body already (#7722)

This commit is contained in:
Ishaan Jaff 2025-01-12 15:41:40 -08:00 committed by GitHub
parent 2c25ea5737
commit 95183f2103
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -21,26 +21,32 @@ async def _read_request_body(request: Optional[Request]) -> Dict:
try:
if request is None:
return {}
# Check if we already read and parsed the body
if hasattr(request.state, "parsed_body"):
return request.state.parsed_body
_request_headers: dict = _safe_get_request_headers(request=request)
content_type = _request_headers.get("content-type", "")
if "form" in content_type:
return dict(await request.form())
parsed_body = dict(await request.form())
else:
# Read the request body
body = await request.body()
# Return empty dict if body is empty or None
if not body:
return {}
parsed_body = {}
parsed_body = orjson.loads(body)
# Attempt JSON parsing (safe for untrusted input)
return orjson.loads(body)
# Cache the parsed result
request.state.parsed_body = parsed_body
return parsed_body
except (json.JSONDecodeError, orjson.JSONDecodeError):
# Log detailed information for debugging
verbose_proxy_logger.exception("Invalid JSON payload received.")
return {}
except Exception as e:
# Catch unexpected errors to avoid crashes
verbose_proxy_logger.exception(