- split endpoint to find stuff for pool and traditional

This commit is contained in:
Jakub Miazek 2024-05-11 16:09:10 +02:00
parent 514eea7231
commit e003454647

View File

@ -42,17 +42,40 @@ async def create_stuff(
@router.get("/{name}", response_model=StuffResponse)
async def find_stuff(
async def find_stuff(name: str, db_session: AsyncSession = Depends(get_db)):
result = await Stuff.find(db_session, name)
if not result:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Stuff with name {name} not found.")
return result
@router.get("/pool/{name}", response_model=StuffResponse)
async def find_stuff_pool(
request: Request,
name: str,
pool: bool = False,
db_session: AsyncSession = Depends(get_db),
):
"""
Asynchronous function to find a specific 'Stuff' object in the database using a connection pool.
This function compiles an SQL statement to find a 'Stuff' object by its name, executes the statement
using a connection from the application's connection pool, and returns the result as a dictionary.
If the 'Stuff' object is not found, it raises an HTTPException with a 404 status code.
If an SQLAlchemyError occurs during the execution of the SQL statement, it raises an HTTPException
with a 422 status code.
Args:
request (Request): The incoming request. Used to access the application's connection pool.
name (str): The name of the 'Stuff' object to find.
db_session (AsyncSession): The database session. Used to compile the SQL statement.
Returns:
dict: The found 'Stuff' object as a dictionary.
Raises:
HTTPException: If the 'Stuff' object is not found or an SQLAlchemyError occurs.
"""
try:
if not pool:
result = await Stuff.find(db_session, name)
else:
# execute the compiled SQL statement
stmt = await Stuff.find(db_session, name, compile_sql=True)
result = await request.app.postgres_pool.fetchrow(str(stmt))
result = dict(result)
@ -68,6 +91,7 @@ async def find_stuff(
return result
@router.delete("/{name}")
async def delete_stuff(name: str, db_session: AsyncSession = Depends(get_db)):
stuff = await Stuff.find(db_session, name)