Last active
April 7, 2025 15:47
-
-
Save Zaczero/00f3a2679ebc0a25eb938ed82bc63553 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# SPDX-License-Identifier: 0BSD | |
from collections.abc import Callable | |
from functools import wraps | |
from fastapi.datastructures import DefaultPlaceholder | |
from fastapi.dependencies.utils import get_dependant | |
from fastapi.routing import APIRoute | |
from starlette.responses import JSONResponse | |
from starlette.routing import request_response | |
... | |
def fast_response_serialization(app: FastAPI) -> None: | |
""" | |
Setup FastAPI application to use optimized JSON serialization. | |
Default serialization behavior is slow and redundant. | |
This is quite hacky as FastAPI does not expose an easy way to override it. | |
""" | |
def wrap_endpoint(endpoint: Callable, cls: type[Response]): | |
@wraps(endpoint) | |
async def wrapper(*args, **kwargs): | |
content = await endpoint(*args, **kwargs) | |
return content if isinstance(content, Response) else cls(content) | |
return wrapper | |
for route in app.routes: | |
if not isinstance(route, APIRoute): | |
continue | |
response_class = route.response_class | |
if isinstance(response_class, DefaultPlaceholder): | |
response_class = response_class.value | |
if issubclass(response_class, JSONResponse): | |
route.endpoint = wrap_endpoint(route.endpoint, response_class) | |
route.dependant = get_dependant(path=route.path_format, call=route.endpoint) | |
route.app = request_response(route.get_route_handler()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment