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

26 statements  

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

1import time 1abcde

2from typing import Callable 1abcde

3 

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

5from fastapi.routing import APIRoute 1abcde

6 

7 

8class TimedRoute(APIRoute): 1abcde

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

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

11 

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

13 before = time.time() 1abcde

14 response: Response = await original_route_handler(request) 1abcde

15 duration = time.time() - before 1abcde

16 response.headers["X-Response-Time"] = str(duration) 1abcde

17 print(f"route duration: {duration}") 1abcde

18 print(f"route response: {response}") 1abcde

19 print(f"route response headers: {response.headers}") 1abcde

20 return response 1abcde

21 

22 return custom_route_handler 1abcde

23 

24 

25app = FastAPI() 1abcde

26router = APIRouter(route_class=TimedRoute) 1abcde

27 

28 

29@app.get("/") 1abcde

30async def not_timed(): 1abcde

31 return {"message": "Not timed"} 1abcde

32 

33 

34@router.get("/timed") 1abcde

35async def timed(): 1abcde

36 return {"message": "It's the time of my life"} 1abcde

37 

38 

39app.include_router(router) 1abcde