recopytex/backend/api/main.py

112 lines
3.1 KiB
Python

import sqlite3
from fastapi import FastAPI, status
from fastapi.responses import JSONResponse
from backend.adapters.sqlite import create_db
from backend.api.model import StudentModel, TribeModel
from backend.model.student import Student
from backend.model.tribe import Tribe
from backend.repository.student_sqlite_repository import StudentSQLiteRepository
from backend.repository.tribe_sqlite_repository import (
TribeRepositoryError,
TribeSQLiteRepository,
)
# from sqlalchemy import create_engine
# from sqlalchemy.orm import clear_mappers, sessionmaker
# import backend.adapters.orm as orm
# from backend.repository.tribe_sqlalchemy_repository import TribeSQLAlchemyRepository
# orm.start_mappers()
# engine = create_engine("sqlite:///:memory:")
# orm.metadata.create_all(engine)
# session = sessionmaker(bind=engine)()
# tribe_repo = TribeSQLAlchemyRepository(session)
conn = sqlite3.connect("sqlite.db")
create_db(conn)
tribe_repo = TribeSQLiteRepository(conn)
student_repo = StudentSQLiteRepository(conn)
app = FastAPI()
@app.post("/tribes", status_code=status.HTTP_201_CREATED, response_model=TribeModel)
async def post_tribe(item: TribeModel):
tribe = Tribe(**item.dict())
try:
tribe_repo.add(tribe)
except TribeRepositoryError:
return JSONResponse(
status_code=status.HTTP_409_CONFLICT,
content=f"The tribe {tribe.name} already exists",
)
conn.commit()
return tribe.to_dict()
@app.get("/tribes", response_model=list[TribeModel])
async def list_tribes():
tribes = tribe_repo.list()
return [t.to_dict() for t in tribes]
@app.get("/tribes/{name}", response_model=TribeModel)
async def get_tribe(name: str):
tribe = tribe_repo.get(name)
return tribe.to_dict()
@app.post("/students", status_code=status.HTTP_201_CREATED, response_model=StudentModel)
async def post_student(item: StudentModel):
if item.id is not None:
return JSONResponse(
status_code=status.HTTP_409_CONFLICT,
content=f"You can't post a student with an id. It is already registrered. Use PUT to modify it.",
)
tribe_name = item.tribe_name
try:
tribe = tribe_repo.get(tribe_name)
except TribeRepositoryError:
return JSONResponse(
status_code=status.HTTP_409_CONFLICT,
content=f"The tribe {tribe_name} does not exists. You can't add a student in it.",
)
student = Student(item.name, tribe)
student_repo.add(student)
conn.commit()
return student.to_dict()
@app.put(
"/students/{student_id}",
status_code=status.HTTP_200_OK,
response_model=StudentModel,
)
async def put_student(student_id, item: StudentModel):
tribe_name = item.tribe_name
try:
tribe = tribe_repo.get(tribe_name)
except TribeRepositoryError:
return JSONResponse(
status_code=status.HTTP_409_CONFLICT,
content=f"The tribe {tribe_name} does not exists. You can't add a student in it.",
)
student = Student(name=item.name, tribe=tribe, id=student_id)
student_repo.update(student)
conn.commit()
return student.to_dict()