Files
SST/PythonProject/api/grade_api.py
T
2026-09-22 14:52:15 +08:00

80 lines
3.0 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 *
from fastapi import APIRouter, Depends, HTTPException, Body
gradeAPI = APIRouter(tags=['学生考核成绩管理模块'])
@gradeAPI.get("/grade/{stu_id}",summary="根据学生id查询成绩")
def get_grade(stu_id: int,db=Depends(get_db)):
try:
res=get_grade_dao(stu_id,db)
return {
"code": 200,
"detail": "查询成功",
"data": res
}
except Exception as e:
raise HTTPException(status_code=500,detail=f'数据库查询异常:{str(e)}')
@gradeAPI.post('/grade',summary='添加学生成绩')
def post_grade(o:GradeRequest,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("/grade/{score_id}", summary="成绩修改")
def put_grade(
score_id: int,
exam_order: int | None = Body(default=None),
score: float | None = Body(default=None),
db=Depends(get_db)
):
# 1. 查询这条成绩记录是否存在(未删除)
old_obj = get_score_by_id_dao(score_id=score_id, db=db)
if not old_obj:
raise HTTPException(status_code=404, detail="成绩记录不存在(已删除)")
# 2. 组装需要更新的字典,只把不为None的字段放进去
update_data = {}
if exam_order is not None:
update_data["exam_order"] = exam_order
if score is not None:
update_data["score"] = score
# 没有传入任何要修改的字段
if not update_data:
raise HTTPException(status_code=400, detail="请传入需要修改的字段:exam_order 或 score")
# 3. 如果要修改考核序次,做重复校验:同一个学生不能重复的exam_order
if "exam_order" in update_data:
exist_obj = get_score_by_stu_exam_order_dao(
stu_id=old_obj.stu_id,
exam_order=update_data["exam_order"],
db=db
)
# 查询到别的记录占用该学生该考核序次
if exist_obj and exist_obj.score_id != score_id:
raise HTTPException(status_code=409, detail="修改后的考核序次,该学生已有成绩!")
# 4.执行数据库更新
try:
rows = update_grade_dao(score_id=score_id, update_data=update_data, db=db)
except Exception:
raise HTTPException(status_code=409, detail="数据冲突,重复数据")
if rows == 0:
return {"code": 200, "totals": rows, "detail": "数据未发生变化"}
return {"code": 200, "totals": rows, "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':'删除成功'}