Files
SST/PythonProject/api/grade_api.py
T
2026-09-21 22:34:34 +08:00

62 lines
2.3 KiB
Python

from fastapi import APIRouter,Depends,HTTPException,Path,Form
from util.database import get_db
from model.all_model import Student_Model
from dao.grade_dao import *
from schema.grade_schema import *
gradeAPI = APIRouter(tags=['学生考核成绩'])
@gradeAPI.get("/grade/{stu_id}",response_model=list[GradeResponse],summary="根据学生id查询成绩")
def get_grade(stu_id: int,db=Depends(get_db)):
try:
res=get_grade_dao(stu_id,db)
return res
except Exception as e:
raise HTTPException(status_code=500,detail=f'数据库查询异常:{str(e)}')
@gradeAPI.post('/grade',response_model=GradeResponse,summary='添加学生成绩')
def post_grade(o:GradeRequest=Form(),db=Depends(get_db)):
d=o.model_dump()
r=add_grade_dao(g=d,db=db)
if not r:
raise HTTPException(status_code=400, detail='学生不存在')
return o
@gradeAPI.put('/{score_id}',summary='成绩修改')
def put_grade(
score_id: int
,o:GradeUpdate=Form()
,db=Depends(get_db)
):
old_obj = get_score_by_id_dao(score_id=score_id, db=db)
if not old_obj:
raise HTTPException(status_code=404, detail="成绩记录不存在(已删除)")
d = o.model_dump(exclude_unset=True)
if not d:
raise HTTPException(status_code=400,detail='请传入需要修改的字段')
if "exam_order" in d:
exist_obj = get_score_by_stu_exam_order_dao(
stu_id=old_obj.stu_id,
exam_order=d["exam_order"],
db=db
)
if exist_obj and exist_obj.id != score_id:
raise HTTPException(status_code=409, detail="修改后的考核序次,该学生已有成绩!")
try:
r = update_grade_dao(score_id=score_id, update_data=d, db=db)
except Exception:
raise HTTPException(status_code=409, detail="数据冲突,重复数据")
if r == 0:
return {"code": 200, "totals": r, "detail": "数据未发生变化"}
return {"code": 200, "totals": r, "detail": "更新成功"}
@gradeAPI.delete('/{score_id}',summary='删除成绩')
def delete_grade(score_id:int,db=Depends(get_db)):
r = delete_grade_dao(stu_id=score_id,db=db)
if not r:
raise HTTPException(status_code=404,detail='删除失败')
return {'code':200,'totals':r,'detail':'删除成功'}