added organ api

This commit is contained in:
2024-10-26 19:45:53 +08:00
parent ee26660d3a
commit dcf4e3efe8
4 changed files with 245 additions and 43 deletions

View File

@@ -0,0 +1,98 @@
import uuid
from typing import Any, Annotated, Optional
from app.utils import validate_file_size_type, save_picture, del_picture
from fastapi import APIRouter, HTTPException, UploadFile, File, Form
from sqlmodel import func, select
from app.api.deps import CurrentUser, SessionDep
from app.models import (
Organ,
OrganPublic,
OrganCreate,
OrganUpdate,
OrganListPublic,
Message
)
router = APIRouter()
@router.post("/", response_model=OrganPublic)
async def create_organ(
*,
session: SessionDep,
current_user: CurrentUser,
description: str = Form(),
title: str = Form(),
image: Annotated[UploadFile, File()],
index: int = Form()
) -> Any:
"""
Create new about us.
"""
validate_file_size_type(image)
imageUrl = await save_picture(file=image, folder_name="tmp")
# aboutus_in.image = imageUrl
organ_in = OrganCreate(description=description, image=imageUrl, index=index ,title=title)
organ = Organ.from_orm(organ_in)
session.add(organ)
session.commit()
session.refresh(organ)
return organ
@router.put("/{id}", response_model= OrganPublic)
async def edit_organ(
*,
session: SessionDep,
current_user: CurrentUser,
id: uuid.UUID,
description: str = Form(),
image: Annotated[UploadFile, File()] = None,
title: str = Form(),
index: int = Form()
) -> Any:
organ = session.get(Organ, id)
if image is not None:
validate_file_size_type(image)
imageUrl = await save_picture(file=image, folder_name="tmp")
await del_picture(organ.image)
organ_in = OrganUpdate(description=description, image=imageUrl, index=index, title=title)
else :
organ_in = OrganUpdate(description=description, image=organ.image, index=index, title=title)
update_dict = organ_in.model_dump(exclude_unset=True)
organ.sqlmodel_update(update_dict)
session.add(organ)
session.commit()
session.refresh(organ)
return organ
@router.get("/", response_model=OrganListPublic)
def read_organ_list(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
count_statement = select(func.count()).select_from(Organ)
count = session.exec(count_statement).one()
statement = select(Organ).offset(skip).limit(limit)
organ = session.exec(statement).all()
return OrganListPublic(data=organ, count=count)
@router.delete("/{id}")
async def delete_organ(
session: SessionDep, current_user: CurrentUser, id: uuid.UUID
) -> Message:
"""
Delete an course.
"""
organ = session.get(Organ, id)
if not organ:
raise HTTPException(status_code=404, detail="aboutUs not found")
await del_picture(organ.image)
session.delete(organ)
session.commit()
return Message(message="aboutUs deleted successfully")