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

24 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-05 00:03 +0000

1import gzip 1abcdef

2from typing import Callable, List 1abcdef

3 

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

5from fastapi.routing import APIRoute 1abcdef

6 

7 

8class GzipRequest(Request): 1abcdef

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

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

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

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

13 body = gzip.decompress(body) 1ghijkl

14 self._body = body 1ghijkl

15 return self._body 1ghijkl

16 

17 

18class GzipRoute(APIRoute): 1abcdef

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

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

21 

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

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

24 return await original_route_handler(request) 1gmhniojpkqlr

25 

26 return custom_route_handler 1abcdef

27 

28 

29app = FastAPI() 1abcdef

30app.router.route_class = GzipRoute 1abcdef

31 

32 

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

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

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