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-04-06 01:24 +0000

1import gzip 1abcdefg

2from collections.abc import Callable 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"): 1lhimjnk

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

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

13 body = gzip.decompress(body) 1hijk

14 self._body = body 1lhimjnk

15 return self._body 1lhimjnk

16 

17 

18class GzipRoute(APIRoute): 1abcdefg

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

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

21 

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

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

24 return await original_route_handler(request) 1lhsitmjunkv

25 

26 return custom_route_handler 1abocdefpqgr

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)} 1lhimjnk