1- from fastapi import APIRouter , Depends , HTTPException , status
1+ from fastapi import APIRouter , Depends , HTTPException , status , Request
2+ from fastapi .exceptions import ResponseValidationError
23from sqlalchemy .exc import SQLAlchemyError
34from sqlalchemy .ext .asyncio import AsyncSession
45
@@ -21,7 +22,6 @@ async def create_multi_stuff(
2122 db_session .add_all (stuff_instances )
2223 await db_session .commit ()
2324 except SQLAlchemyError as ex :
24- # logger.exception(ex)
2525 raise HTTPException (
2626 status_code = status .HTTP_422_UNPROCESSABLE_ENTITY , detail = repr (ex )
2727 ) from ex
@@ -42,11 +42,56 @@ async def create_stuff(
4242
4343
4444@router .get ("/{name}" , response_model = StuffResponse )
45- async def find_stuff (
45+ async def find_stuff (name : str , db_session : AsyncSession = Depends (get_db )):
46+ result = await Stuff .find (db_session , name )
47+ if not result :
48+ raise HTTPException (
49+ status_code = status .HTTP_404_NOT_FOUND ,
50+ detail = f"Stuff with name { name } not found." ,
51+ )
52+ return result
53+
54+
55+ @router .get ("/pool/{name}" , response_model = StuffResponse )
56+ async def find_stuff_pool (
57+ request : Request ,
4658 name : str ,
4759 db_session : AsyncSession = Depends (get_db ),
4860):
49- return await Stuff .find (db_session , name )
61+ """
62+ Asynchronous function to find a specific 'Stuff' object in the database using a connection pool.
63+
64+ This function compiles an SQL statement to find a 'Stuff' object by its name, executes the statement
65+ using a connection from the application's connection pool, and returns the result as a dictionary.
66+ If the 'Stuff' object is not found, it raises an HTTPException with a 404 status code.
67+ If an SQLAlchemyError occurs during the execution of the SQL statement, it raises an HTTPException
68+ with a 422 status code.
69+
70+ Args:
71+ request (Request): The incoming request. Used to access the application's connection pool.
72+ name (str): The name of the 'Stuff' object to find.
73+ db_session (AsyncSession): The database session. Used to compile the SQL statement.
74+
75+ Returns:
76+ dict: The found 'Stuff' object as a dictionary.
77+
78+ Raises:
79+ HTTPException: If the 'Stuff' object is not found or an SQLAlchemyError occurs.
80+ """
81+ try :
82+ stmt = await Stuff .find (db_session , name , compile_sql = True )
83+ result = await request .app .postgres_pool .fetchrow (str (stmt ))
84+ result = dict (result )
85+ except SQLAlchemyError as ex :
86+ raise HTTPException (
87+ status_code = status .HTTP_422_UNPROCESSABLE_ENTITY , detail = repr (ex )
88+ ) from ex
89+ if not result :
90+ raise HTTPException (
91+ status_code = status .HTTP_404_NOT_FOUND ,
92+ detail = f"Stuff with name { name } not found." ,
93+ )
94+ return result
5095
5196
5297@router .delete ("/{name}" )
0 commit comments