1+ from collections .abc import Callable
2+ from typing import Annotated , Any
3+
14from fastapi import APIRouter , Depends , HTTPException , Request , status
2- from app .services .logging import get_logger
5+ from pydantic import ValidationError , WrapValidator
6+ from rotoger import get_logger
37from sqlalchemy .exc import SQLAlchemyError
48from sqlalchemy .ext .asyncio import AsyncSession
59
@@ -22,12 +26,26 @@ async def create_random_stuff(
2226 return {"id" : str (random_stuff .id )}
2327
2428
29+ failed_items : list [dict ] = [] # Global or pass via context
30+
31+ def catch_invalid (v : Any , handler : Callable [[Any ], Any ] ) -> Any :
32+ try :
33+ return handler (v )
34+ except ValidationError :
35+ failed_items .append (v ) # Intercept here!
36+ return None # Or raise if needed
37+
2538@router .post ("/add_many" , status_code = status .HTTP_201_CREATED )
2639async def create_multi_stuff (
27- payload : list [StuffSchema ], db_session : AsyncSession = Depends (get_db )
40+ payload : list [Annotated [ StuffSchema , WrapValidator ( catch_invalid )] ], db_session : AsyncSession = Depends (get_db )
2841):
42+ await logger .ainfo (f">>>{ failed_items } " )
2943 try :
30- stuff_instances = [Stuff (** stuff .model_dump ()) for stuff in payload ]
44+ await logger .ainfo (f">>>{ failed_items } " )
45+ await logger .ainfo (f">>>{ payload } " )
46+ stuff_instances = [
47+ Stuff (** stuff .model_dump ()) for stuff in payload if stuff is not None
48+ ]
3149 db_session .add_all (stuff_instances )
3250 await db_session .commit ()
3351 except SQLAlchemyError as ex :
@@ -39,6 +57,7 @@ async def create_multi_stuff(
3957 await logger .ainfo (
4058 f"{ len (stuff_instances )} Stuff instances inserted into the database."
4159 )
60+ return {"inserted" : len (stuff_instances )}
4261 return True
4362
4463
0 commit comments