Replies: 12 comments
-
You can return Response (or RawResponse) object directly so fastapi doesn't try to serialize it: class RawResponse(Response):
media_type = "binary/octet-stream"
def render(self, content: bytes) -> bytes:
return bytes([b ^ 0x54 for b in content])
app = FastAPI()
@app.get("/test")
async def test():
return RawResponse(content=b"\xf6j,\x90\xae\\\xf3\xd3\xaa") |
Beta Was this translation helpful? Give feedback.
-
I need to use this in a hundred endpoints, so it doesn't work for me because it's too redundant |
Beta Was this translation helpful? Give feedback.
-
I came up with this solution that wraps endpoint function to return def wrap_response(endpoint: Any, response_cls: type[Response]) -> Any:
@functools.wraps(endpoint)
async def wrapper(*args, **kwargs):
response = await endpoint(*args, **kwargs)
return response_cls(content=response)
return wrapper
class RawResponse(Response):
media_type = "binary/octet-stream"
def render(self, content: bytes) -> bytes:
return bytes([b ^ 0x54 for b in content])
class RawRoute(APIRoute):
def get_route_handler(self) -> Callable:
self.dependant.call = wrap_response(endpoint=self.dependant.call, response_cls=RawResponse)
return super().get_route_handler() |
Beta Was this translation helpful? Give feedback.
-
Any luck with implementing the above? @Redict |
Beta Was this translation helpful? Give feedback.
-
To implement that in a better way I need to go deep inside FastAPI, I don't really have time for that |
Beta Was this translation helpful? Give feedback.
-
Yep, it works, but I wonder if there's a better way of doing that, so maybe someone else would get to this issue too |
Beta Was this translation helpful? Give feedback.
-
@yinziyan1206 That doesn't solve the problem really 🤔 |
Beta Was this translation helpful? Give feedback.
-
Oops. you just return |
Beta Was this translation helpful? Give feedback.
-
They need to return binary data, and overriding pydantic internals doesn't seem like a good idea 👀 |
Beta Was this translation helpful? Give feedback.
-
@ThirVondukr I tried you solution, didn't work for me. lol. Any updates for this? |
Beta Was this translation helpful? Give feedback.
-
looks like this is by design, you will have to wrap your handler. |
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
For this code I get
'utf-8' codec can't decode byte
at routing.py:234 (serialize_response
call). How can I override this?Only one hackish solution that I've found is to b64encode(bytes) and in
RawResponse
render b64decode(content) then xor itOperating System
Windows
Operating System Details
No response
FastAPI Version
0.68.1
Python Version
Python 3.9.2
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions