-
-
Notifications
You must be signed in to change notification settings - Fork 8.4k
Closed
Labels
Description
class CustomJSONResponse(JSONResponse):
media_type = "application/json"
def render(self, content: typing.Any) -> bytes:
return dumps(content)
With dumps being a custom function, managing datetime values specifically.
@router.post("/requests")
async def insert_user_request(request: Request):
return CustomJSONResponse(content={"timestamp": datetime.now()}, status_code=HTTP_201_CREATED)
Will work as expected but
@router.post("/requests", response_class=CustomJSONResponse, status_code=HTTP_201_CREATED)
async def insert_user_request(request: Request):
return {"timestamp": datetime.now()}
Will fail to use the custom dump function.
The cause is in https://github.com/tiangolo/fastapi/blob/master/fastapi/routing.py#L190 : serialize_response (which calls jsonable_encoder) is called before the response_class instantiation (https://github.com/tiangolo/fastapi/blob/master/fastapi/routing.py#L201) so datetime values are converted to str prematurely.
Apo-, akvadrako, nguyent, natskvi, feluxe and 1 more