backend_and_cms/backend/app/api/routes/course.py

96 lines
2.3 KiB
Python

import uuid
from typing import Any
from fastapi import APIRouter, HTTPException
from sqlmodel import func, select
from app.api.deps import CurrentUser, SessionDep
from app.models import (
Course,
CourseCreate,
CoursePublic,
CoursesPublic,
CourseUpdate,
CoursePublicWithImages,
Message,
)
router = APIRouter()
@router.get("/", response_model=CoursesPublic)
def read_courses(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
"""
Retrieve courses.
"""
count_statement = select(func.count()).select_from(Course)
count = session.exec(count_statement).one()
statement = select(Course).offset(skip).limit(limit)
courses = session.exec(statement).all()
return CoursesPublic(data=courses, count=count)
@router.get("/{id}", response_model=CoursePublicWithImages)
def read_course(session: SessionDep, id: uuid.UUID) -> Any:
"""
Get item by ID.
"""
course = session.get(Course, id)
if not course:
raise HTTPException(status_code=404, detail="course not found")
return course
@router.post("/", response_model=CoursePublic)
def create_item(
*, session: SessionDep, current_user: CurrentUser, course_in: CourseCreate
) -> Any:
"""
Create new course.
"""
course = Course.model_validate(course_in)
session.add(course)
session.commit()
session.refresh(course)
return course
@router.put("/{id}", response_model=CoursePublic)
def update_course(
*,
session: SessionDep,
current_user: CurrentUser,
id: uuid.UUID,
course_in: CourseUpdate,
) -> Any:
"""
Update an course.
"""
course = session.get(Course, id)
if not course:
raise HTTPException(status_code=404, detail="course not found")
update_dict = course_in.model_dump(exclude_unset=True)
course.sqlmodel_update(update_dict)
session.add(course)
session.commit()
session.refresh(course)
return course
@router.delete("/{id}")
def delete_course(
session: SessionDep, current_user: CurrentUser, id: uuid.UUID
) -> Message:
"""
Delete an course.
"""
course = session.get(Course, id)
if not course:
raise HTTPException(status_code=404, detail="course not found")
session.delete(course)
session.commit()
return Message(message="course deleted successfully")