Debian Codegraph @

docs_src/custom_request_and_route/tutorial001_py310.py

raw
1 import gzip
2 from collections.abc import Callable
3
4 from fastapi import Body, FastAPI, Request, Response
5 from fastapi.routing import APIRoute
6
7
8 class GzipRequest(Request):
9 async def body(self) -> bytes:
10 if not hasattr(self, "_body"):
11 body = await super().body()
12 if "gzip" in self.headers.getlist("Content-Encoding"):
13 body = gzip.decompress(body)
14 self._body = body
15 return self._body
16
17
18 class GzipRoute(APIRoute):
19 def get_route_handler(self) -> Callable:
20 original_route_handler = super().get_route_handler()
21
22 async def custom_route_handler(request: Request) -> Response:
23 request = GzipRequest(request.scope, request.receive)
24 return await original_route_handler(request)
25
26 return custom_route_handler
27
28
29 app = FastAPI()
30 app.router.route_class = GzipRoute
31
32
33 @app.post("/sum")
34 async def sum_numbers(numbers: list[int] = Body()):
35 return {"sum": sum(numbers)}