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

24 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1import gzip 1abcde

2from typing import Callable, List 1abcde

3 

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

5from fastapi.routing import APIRoute 1abcde

6 

7 

8class GzipRequest(Request): 1abcde

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

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

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

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

13 body = gzip.decompress(body) 1abcde

14 self._body = body 1abcde

15 return self._body 1abcde

16 

17 

18class GzipRoute(APIRoute): 1abcde

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

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

21 

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

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

24 return await original_route_handler(request) 1abcde

25 

26 return custom_route_handler 1abcde

27 

28 

29app = FastAPI() 1abcde

30app.router.route_class = GzipRoute 1abcde

31 

32 

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

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

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