Coverage for docs_src / custom_request_and_route / tutorial001_py310.py: 100%

24 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1import gzip 1abc

2from collections.abc import Callable 1abc

3 

4from fastapi import Body, FastAPI, Request, Response 1abc

5from fastapi.routing import APIRoute 1abc

6 

7 

8class GzipRequest(Request): 1abc

9 async def body(self) -> bytes: 1abc

10 if not hasattr(self, "_body"): 1def

11 body = await super().body() 1def

12 if "gzip" in self.headers.getlist("Content-Encoding"): 1def

13 body = gzip.decompress(body) 1def

14 self._body = body 1def

15 return self._body 1def

16 

17 

18class GzipRoute(APIRoute): 1abc

19 def get_route_handler(self) -> Callable: 1abc

20 original_route_handler = super().get_route_handler() 1abc

21 

22 async def custom_route_handler(request: Request) -> Response: 1abc

23 request = GzipRequest(request.scope, request.receive) 1dgehfi

24 return await original_route_handler(request) 1dgehfi

25 

26 return custom_route_handler 1abc

27 

28 

29app = FastAPI() 1abc

30app.router.route_class = GzipRoute 1abc

31 

32 

33@app.post("/sum") 1abc

34async def sum_numbers(numbers: list[int] = Body()): 1abc

35 return {"sum": sum(numbers)} 1def