mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2025-08-26 16:40:40 +03:00
- split endpoint to find stuff for pool and traditional
This commit is contained in:
parent
514eea7231
commit
e003454647
@ -42,20 +42,43 @@ 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)
|
||||
stmt = await Stuff.find(db_session, name, compile_sql=True)
|
||||
result = await request.app.postgres_pool.fetchrow(str(stmt))
|
||||
result = dict(result)
|
||||
except SQLAlchemyError as ex:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)
|
||||
@ -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)
|
||||
|
Loading…
x
Reference in New Issue
Block a user