Debian Codegraph @

docs_src/custom_request_and_route/tutorial001_an_py310.py

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