From 41e244d7ad50068352ba7491911b6615a97c9d96 Mon Sep 17 00:00:00 2001 From: LamequeFernandes Date: Thu, 1 Sep 2022 16:11:58 -0300 Subject: [PATCH] criacao de repositorie e endpoint para criar turma. #32 Co-Authored-by: JoaoP-Coelho --- src/api/endpoints/turma.py | 20 ++++++++++++++++++++ src/repositories/turma.py | 32 ++++++++++++++++++++++++++++++++ src/schemas/turma.py | 6 +++--- 3 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 src/api/endpoints/turma.py create mode 100644 src/repositories/turma.py diff --git a/src/api/endpoints/turma.py b/src/api/endpoints/turma.py new file mode 100644 index 0000000..e566892 --- /dev/null +++ b/src/api/endpoints/turma.py @@ -0,0 +1,20 @@ +from fastapi import APIRouter, status, Depends + +from typing import List + +from src.schemas.turma import TurmaSchema +from src.repositories.turma import TurmaModel +from src.repositories.turma import TurmaRepository + +from sqlalchemy.ext.asyncio import AsyncSession + +from db.database import get_session + + +router = APIRouter() + +repository_turma = TurmaRepository() + +@router.post('/', status_code=status.HTTP_201_CREATED, response_model=TurmaSchema) +async def post_turma(turma: TurmaSchema, db: AsyncSession=Depends(get_session)): + return await repository_turma.create(turma, db) diff --git a/src/repositories/turma.py b/src/repositories/turma.py new file mode 100644 index 0000000..ca51fd6 --- /dev/null +++ b/src/repositories/turma.py @@ -0,0 +1,32 @@ +from src.models.turma import TurmaModel +from src.schemas.turma import TurmaSchema + +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.future import select + +from fastapi import status, HTTPException + + +class TurmaRepository: + + async def turma_existe(self, id: int, db: AsyncSession): + async with db as session: + query_turma = select(TurmaModel).filter(TurmaModel.id == id) + result = await session.execute(query_turma) + turma: TurmaModel = result.scalar() + + if not turma: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, + detail="Turma não encontrada") + return turma + + async def create(self, turma: TurmaSchema, db: AsyncSession): + nova_turma: TurmaModel = TurmaModel(**turma.dict()) + + try: + db.add(nova_turma) + await db.commit() + except Exception as error: + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=error) + return nova_turma \ No newline at end of file diff --git a/src/schemas/turma.py b/src/schemas/turma.py index aa6eae8..6a018a7 100644 --- a/src/schemas/turma.py +++ b/src/schemas/turma.py @@ -7,10 +7,10 @@ class TurmaSchema(BaseModel): id: Optional[int] - professor: str - ano: str + professor: int + ano: int semestre: int - nome_disciplina: Optional[str] + nome_disciplina: str created_at: Optional[datetime] class Config: