mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2026-01-17 11:40:39 +03:00
add multi stuff POST endpoint
This commit is contained in:
@@ -1,25 +1,31 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, status
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from the_app.database import get_db
|
||||
from the_app.models.stuff import Stuff
|
||||
from the_app.schemas.stuff import StuffResponse, StuffSchema
|
||||
from the_app.utils import get_logger
|
||||
|
||||
router = APIRouter(prefix="/v1/stuff")
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
@router.post("/add_many", status_code=status.HTTP_201_CREATED)
|
||||
async def create_multi_stuff(payload: List[StuffSchema], db_session: AsyncSession = Depends(get_db)):
|
||||
stuff_instances = [
|
||||
Stuff(
|
||||
name=stuf.name, description=stuf.description
|
||||
)
|
||||
for stuf in payload
|
||||
]
|
||||
db_session.add_all(stuff_instances)
|
||||
await db_session.commit()
|
||||
return True
|
||||
try:
|
||||
stuff_instances = [Stuff(name=stuf.name, description=stuf.description) for stuf in payload]
|
||||
db_session.add_all(stuff_instances)
|
||||
await db_session.commit()
|
||||
except SQLAlchemyError as ex:
|
||||
# logger.exception(ex)
|
||||
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex))
|
||||
else:
|
||||
logger.info(f"{len(stuff_instances)} instances of Stuff inserted into database.")
|
||||
return True
|
||||
|
||||
|
||||
@router.post("", status_code=status.HTTP_201_CREATED, response_model=StuffResponse)
|
||||
|
||||
Reference in New Issue
Block a user