Coverage for docs_src/custom_request_and_route/tutorial002.py: 100%
20 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
1from typing import Callable, List 1abcde
3from fastapi import Body, FastAPI, HTTPException, Request, Response 1abcde
4from fastapi.exceptions import RequestValidationError 1abcde
5from fastapi.routing import APIRoute 1abcde
8class ValidationErrorLoggingRoute(APIRoute): 1abcde
9 def get_route_handler(self) -> Callable: 1abcde
10 original_route_handler = super().get_route_handler() 1abcde
12 async def custom_route_handler(request: Request) -> Response: 1abcde
13 try: 1abcde
14 return await original_route_handler(request) 1abcde
15 except RequestValidationError as exc: 1abcde
16 body = await request.body() 1abcde
17 detail = {"errors": exc.errors(), "body": body.decode()} 1abcde
18 raise HTTPException(status_code=422, detail=detail) 1abcde
20 return custom_route_handler 1abcde
23app = FastAPI() 1abcde
24app.router.route_class = ValidationErrorLoggingRoute 1abcde
27@app.post("/") 1abcde
28async def sum_numbers(numbers: List[int] = Body()): 1abcde
29 return sum(numbers) 1abcde