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

24 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1import gzip 1abcdefg

2from typing import Callable, List 1abcdefg

3 

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

5from fastapi.routing import APIRoute 1abcdefg

6 

7 

8class GzipRequest(Request): 1abcdefg

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

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

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

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

13 body = gzip.decompress(body) 1hijklmn

14 self._body = body 1hijklmn

15 return self._body 1hijklmn

16 

17 

18class GzipRoute(APIRoute): 1abcdefg

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

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

21 

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

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

24 return await original_route_handler(request) 1hoipjqkrlsmtnu

25 

26 return custom_route_handler 1abcdefg

27 

28 

29app = FastAPI() 1abcdefg

30app.router.route_class = GzipRoute 1abcdefg

31 

32 

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

34async def sum_numbers(numbers: List[int] = Body()): 1abcdefg

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