From 85b0d97a3db86ef37ef1d43a71ecd439823f3fc4 Mon Sep 17 00:00:00 2001 From: 00MSJ1122 <1253313142@qq.com> Date: Tue, 22 Sep 2026 15:38:53 +0800 Subject: [PATCH] 1 --- PythonProject/api/student_api.py | 57 ++++++++++++-------------- PythonProject/dao/student_dao.py | 50 +++++++++++----------- PythonProject/schema/student_schema.py | 54 +++++++++++++++--------- 3 files changed, 85 insertions(+), 76 deletions(-) diff --git a/PythonProject/api/student_api.py b/PythonProject/api/student_api.py index 2cf2f1d..5006068 100644 --- a/PythonProject/api/student_api.py +++ b/PythonProject/api/student_api.py @@ -6,7 +6,7 @@ from util.database import get_db StudentAPI = APIRouter(tags=['学生基本信息管理模块']) -@StudentAPI.get('/students',response_model=StudentPageResponse,summary='学生信息查询接口',description='查询学生信息') +@StudentAPI.get('/students',response_model=StuPageResponse,summary='学生信息查询接口',description='查询学生信息') def get_students(stu_id:int|None=None ,stu_name:str|None=None ,class_id:int|None=None @@ -19,39 +19,11 @@ def get_students(stu_id:int|None=None ,page=page ,page_size=page_size ,db=db) - - if not r: - raise HTTPException(status_code=404,detail='学生不存在') return StudentPageResponse(page=page, page_size=page_size, totals=total, data=r) -@StudentAPI.put('/{stu_id}',summary='学生信息更新接口',description='更新学生信息') -def update_students(s:StudentRequest - ,stu_id:int - ,db=Depends(get_db)): - d = s.model_dump(exclude_unset=True) - d.pop('stu_id', None) - if not d: - raise HTTPException(status_code=400, detail='更新内容不能为空') - r = update_student_dao( stu_id=stu_id,update_data=d,db=db ) - if r == 'conflict': - raise HTTPException(status_code=409, detail = '身份证号已被其他学生占用') - if r == 'error': - raise HTTPException(status_code=500, detail='更新失败,请稍后重试') - if not r: - raise HTTPException(status_code=404, detail='没有更新') - return {'code':200,'totals':r,'detail':'更新成功'} - -@StudentAPI.delete('/{stu_id}',summary='学生信息删除接口',description='删除学生信息') -def del_students(stu_id:int - ,db=Depends(get_db)): - rows=delete_student_dao( stu_id=stu_id,db=db ) - if not rows: - raise HTTPException(status_code=404,detail='对象已被删除') - return {'code':200,'totals':rows,'detail':'删除成功'} - @StudentAPI.post('/students',response_model=StugetResponse,summary='学生信息新增接口',description='新增学生信息') def add_students(s:StudentRequest ,db=Depends(get_db)): @@ -62,5 +34,30 @@ def add_students(s:StudentRequest if r == 'conflict': raise HTTPException(status_code=409, detail='身份证号已存在,请勿重复添加') if r == 'error': - raise HTTPException(status_code=500, detail='更添加失败,请稍后重试') + raise HTTPException(status_code=500, detail='添加失败,请稍后重试') return r + +@StudentAPI.put('/students/{stu_id}',summary='学生信息更新接口',description='更新学生信息') +def update_students(stu_id:int + ,s:StuUpdateRequest + ,db=Depends(get_db)): + d = s.model_dump(exclude_unset=True) + d.pop('stu_id', None) + if not d: + raise HTTPException(status_code=400, detail='更新内容不能为空') + r = update_student_dao( stu_id=stu_id,update_data=d,db=db ) + if r == 'conflict': + raise HTTPException(status_code=409, detail = '身份证号已被其他学生占用') + if r == 'error': + raise HTTPException(status_code=500, detail='更新失败,请稍后重试') + if not r: + raise HTTPException(status_code=404, detail='学生不存在或已被删除,更新失败') + return {'code':200,'totals':r,'detail':'更新成功'} + +@StudentAPI.delete('/students/{stu_id}',response_model= StugetResponse,summary='学生信息删除接口',description='删除学生信息') +def del_students(stu_id:int + ,db=Depends(get_db)): + rows=delete_student_dao( stu_id=stu_id,db=db ) + if not rows: + raise HTTPException(status_code=404,detail='学生不存在或已被删除') + return {'code':200,'totals':rows,'detail':'删除成功'} diff --git a/PythonProject/dao/student_dao.py b/PythonProject/dao/student_dao.py index d947d0d..0b5b5e8 100644 --- a/PythonProject/dao/student_dao.py +++ b/PythonProject/dao/student_dao.py @@ -15,7 +15,6 @@ def add_student_dao(o,db): o2 = Student_Model(**o) db.add(o2) db.commit() - db.refresh(o2) # 回填自增的 stu_id return o2 except IntegrityError: db.rollback() @@ -24,27 +23,30 @@ def add_student_dao(o,db): db.rollback() return 'error' -def delete_student_dao(stu_id,db): +def delete_student_dao(stu_id, db): try: - rows = db.query(Student_Model).filter(Student_Model.stu_id == stu_id,Student_Model.delete_status == 0)\ - .update({'delete_status':1,'delete_time': datetime.now()}) + rows = (db.query(Student_Model) + .filter(Student_Model.stu_id == stu_id, + Student_Model.delete_status == 0) + .update({'delete_status': 1, 'delete_time': datetime.now()})) db.commit() - except: - db.rollback() - rows = 0 - finally: return rows + except Exception: + db.rollback() + raise -def update_student_dao(stu_id,update_data,db): - if update_data.get('id_card'): +def update_student_dao(stu_id, update_data, db): + if not update_data: + return 0 + id_card = update_data.get('id_card') + if id_card: conflict = (db.query(Student_Model) - .filter(Student_Model.id_card == update_data['id_card'], + .filter(Student_Model.id_card == id_card, Student_Model.stu_id != stu_id, Student_Model.delete_status == 0) .first()) if conflict: return 'conflict' - try: rows = (db.query(Student_Model) .filter(Student_Model.stu_id == stu_id, @@ -67,17 +69,13 @@ def get_student_dao(stu_id:Optional[int] ,page_size: int ,db ) -> tuple[List[Dict[str, Any]], int]: - try: - q = db.query(Student_Model).filter(Student_Model.delete_status == 0) - if stu_id: - q = q.filter(Student_Model.stu_id == stu_id) - if stu_name and stu_name.strip() != "": - q = q.filter(Student_Model.stu_name.like(f"%{stu_name}%")) - if class_id: - q= q.filter(Student_Model.class_id == class_id) - total = q.count() - r = q.offset((page - 1) * page_size).limit(page_size).all() - return r,total - except: - db.rollback() - return [],0 + q = db.query(Student_Model).filter(Student_Model.delete_status == 0) + if stu_id: + q = q.filter(Student_Model.stu_id == stu_id) + if stu_name and stu_name.strip() != "": + q = q.filter(Student_Model.stu_name.like(f"%{stu_name}%")) + if class_id: + q = q.filter(Student_Model.class_id == class_id) + total = q.count() + r = q.offset((page - 1) * page_size).limit(page_size).all() + return r, total diff --git a/PythonProject/schema/student_schema.py b/PythonProject/schema/student_schema.py index 53579eb..208c576 100644 --- a/PythonProject/schema/student_schema.py +++ b/PythonProject/schema/student_schema.py @@ -31,23 +31,34 @@ class StudentRequest(BaseModel): raise ValueError ('入学日期不能晚于毕业日期') return self +class StuUpdateRequest(BaseModel): + class_id: int | None = None + stu_name: str | None = None + age: int | None = None + gender: str | None = None + id_card: str | None = None + native_place: str | None = None + birthday: date | None = None + school: str | None = None + major: str | None = None + degree: str | None = None + admission_date: date | None = None + graduation_date: date | None = None + progress: int | None = None -class StudentResponse(BaseModel): - code:int = 200 - detail:str = 'ok' - stu_name:str - age:int - gender:str - progress:int + @field_validator('age') + @classmethod + def check_age(cls, v): + if v is not None and v < 0: + raise ValueError('年龄不能为负数') + return v - @field_serializer('progress') - def int_to_string(self,progress:int): - d1 ={ - 0:'学习中', - 1:'求职中', - 2:'已就业' - } - return d1.get(progress,'暂不明确') + @model_validator(mode='after') + def check_admission_graduation(self) -> Self: + if self.admission_date and self.graduation_date: + if self.admission_date > self.graduation_date: + raise ValueError('入学日期不能晚于毕业日期') + return self class StugetResponse(BaseModel): model_config = ConfigDict(from_attributes=True) @@ -58,7 +69,7 @@ class StugetResponse(BaseModel): stu_name: str | None = None age: int | None = None gender: str | None = None - id_card: str + id_card: str | None = None native_place: str | None = None birthday: date | None = None school: str | None = None @@ -66,18 +77,21 @@ class StugetResponse(BaseModel): degree: str | None = None admission_date: date | None = None graduation_date: date | None = None - progress: int = 0 + progress: int @field_serializer('progress') - def int_to_string(self, progress: int): + def progress_to_label(self, progress): d1 = { 0: '学习中', 1: '求职中', 2: '已就业' } - return d1.get(progress, '暂不明确') + try: + return d1.get(int(progress), '暂不明确') + except (TypeError, ValueError): + return progress -class StudentPageResponse(BaseModel): +class StuPageResponse(BaseModel): code: int = 200 detail: str = "ok" page: int