diff --git a/PythonProject/api/cla_api.py b/PythonProject/api/cla_api.py index f061525..d0e5109 100644 --- a/PythonProject/api/cla_api.py +++ b/PythonProject/api/cla_api.py @@ -3,7 +3,7 @@ from util.database import get_db from schema.cla_schema import claRequest from dao.cla_dao import add_class_dao,get_class_dao,update_class_dao,delete_class_dao -claAPI = APIRouter(prefix="/class", tags=["班级管理"]) +claAPI = APIRouter(prefix="/class", tags=["班级管理模块"]) @claAPI.post("/", summary="新增班级信息") def add_class(data: claRequest, Session = Depends(get_db)): diff --git a/PythonProject/api/employment_api.py b/PythonProject/api/employment_api.py index 783ca98..8a53b57 100644 --- a/PythonProject/api/employment_api.py +++ b/PythonProject/api/employment_api.py @@ -1,27 +1,34 @@ from fastapi import APIRouter, Query, Depends, HTTPException, Path,Form from dao import employment_dao from dao.employment_dao import add_emp_dao, update_emp_dao, delete_emp_dao -from schema.employment_schema import EmploymentRequest,EmploymentResponse +from schema.employment_schema import EmploymentRequest,UpdateEmpRequest,EmploymentResponse from util.database import get_db from typing import Optional -emp_api = APIRouter(tags=['学生就业管理系统']) -@emp_api.get('/employment/students/{stu_id}',response_model=EmploymentResponse,summary='获取学生就业信息') -def get_emp_info1(stu_id: Optional[int]=Path(description='学生编号') - ,company_name: Optional[str]=Query(None,description='公司名称') - ,min_salary: Optional[float]=Query(None,description='最低工资') - ,max_salary: Optional[float]=Query(None,description='最高工资') - ,db=Depends(get_db)): - if stu_id or company_name or min_salary or max_salary: - return [employment_dao.get_emp_dao(stu_id=stu_id,db=db)] - raise HTTPException(status_code=404, detail='该学生就业信息不存在') +emp_api = APIRouter(tags=['学生就业管理模块']) @emp_api.get('/employment/class/{class_id}',response_model=EmploymentResponse,summary='获取班级学生就业信息') def get_emp_info2(class_id: Optional[int]=Path(description='班级编号') ,db=Depends(get_db)): - if class_id: - return employment_dao.get_emp_dao(class_id=class_id,db=db) + e2 = employment_dao.get_emp_dao(class_id=class_id, db=db) + if e2: + return e2 raise HTTPException(status_code=404, detail='该班级就业信息不存在') +@emp_api.get('/employment/class/{stu_id}',response_model=list[EmploymentResponse],summary='按照学⽣编号,公司名字,⼯资范围查询学⽣就业信息') +def get_emp_info3(stu_id:int = Path(description='学生编号') + ,company_name: str|None = Query(None,description='公司名称') + ,min_salary: float|None = Query(None,ge=0,description='最低工资') + ,max_salary: float|None = Query(None,ge=0,description='最高工资') + ,db=Depends(get_db)): + if min_salary and max_salary: + if min_salary > max_salary: + raise HTTPException(status_code=404, detail='最低工资不能大于最高工资') + l1 = employment_dao.get_emp_dao(db, stu_id=stu_id + , company_name=company_name + , min_salary=min_salary + , max_salary=max_salary) + return l1 + @emp_api.post('/employment/students/{stu_id}',response_model=EmploymentResponse,summary='新增学生就业信息') def create_emp_info(emp:EmploymentRequest=Form(),db=Depends(get_db)): d=emp.model_dump(exclude_unset=False) @@ -30,17 +37,16 @@ def create_emp_info(emp:EmploymentRequest=Form(),db=Depends(get_db)): raise HTTPException(status_code=500,detail='服务器繁忙,请稍后添加!') return r -@emp_api.put('/employment/students/{stu_id}',response_model=EmploymentResponse,summary='更新学生就业信息') -def update_emp_info(stu_id:int,emp:EmploymentRequest,db=Depends(get_db)): - d = emp.model_dump(exclude_unset=True) - r = update_emp_dao(stu_id,d,db) +@emp_api.put('/employment/students/{emp_id}',summary='更新学生就业信息') +def update_emp_info(emp_id:int,emp:UpdateEmpRequest,db=Depends(get_db)): + r = update_emp_dao(emp_id,emp.model_dump(exclude_unset=True),db) if not r: - raise HTTPException(status_code=500,detail='更新失败!') + raise HTTPException(status_code=500,detail='没有更新!') return {'code':200,'totals':r,'detail':'更新成功!'} -@emp_api.delete('/employment/{stu_id}',summary='删除学生就业信息') -def delete_emp_info(stu_id:int,db=Depends(get_db)): - rows = delete_emp_dao(stu_id, db) +@emp_api.delete('/employment/{emp_id}',summary='删除学生就业信息') +def delete_emp_info(emp_id:int=Path(description='序号'),db=Depends(get_db)): + rows = delete_emp_dao(emp_id, db) if not rows: raise HTTPException(status_code=500, detail='没有删除!') return {'code':200,'detail':'删除成功!'} diff --git a/PythonProject/api/grade_api.py b/PythonProject/api/grade_api.py index 6cbce56..c0b266c 100644 --- a/PythonProject/api/grade_api.py +++ b/PythonProject/api/grade_api.py @@ -5,13 +5,17 @@ from dao.grade_dao import * from schema.grade_schema import * from fastapi import APIRouter, Depends, HTTPException, Body -gradeAPI = APIRouter(tags=['学生考核成绩']) +gradeAPI = APIRouter(tags=['学生考核成绩管理模块']) -@gradeAPI.get("/grade/{stu_id}",response_model=list[GradeResponse],summary="根据学生id查询成绩") +@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 res + return { + "code": 200, + "detail": "查询成功", + "data": res + } except Exception as e: raise HTTPException(status_code=500,detail=f'数据库查询异常:{str(e)}') diff --git a/PythonProject/api/statistics_api.py b/PythonProject/api/statistics_api.py index e327bf3..401efd1 100644 --- a/PythonProject/api/statistics_api.py +++ b/PythonProject/api/statistics_api.py @@ -1,49 +1,42 @@ from fastapi import APIRouter,Depends,Query from dao.statistics_dao import * -from schema.student_schema import StudentResponse from schema.statistics_schema import * +from schema.student_schema import * from util.database import get_db -StatisticsAPI = APIRouter() +StatisticsAPI = APIRouter(tags=['统计分析模块']) -@StatisticsAPI.get("/age",response_model=list[StudentResponse],tags=['统计分析模块'],summary='根据年龄查询学生信息') +@StatisticsAPI.get("/age",response_model=list[StudentResponse],summary='根据年龄查询学生信息') def get_students(min_age:int|None=Query(None,ge=0,le=150),max_age:int|None=Query(None,ge=0,le=150),db=Depends(get_db)): l = select_age(min_age,max_age,db) return l -@StatisticsAPI.get("/all",response_model=list[AllStuResponse],tags=['统计分析模块'],summary='统计每个班级的学员总数和男女生总数') +@StatisticsAPI.get("/all",response_model=list[AllStuResponse],summary='统计每个班级的学员总数和男女生总数') def get_students(db=Depends(get_db)): l = select_all(db) return l -@StatisticsAPI.get("/score",response_model=StudentResponse,tags=['统计分析模块'],summary='根据成绩查询学生信息') +@StatisticsAPI.get("/score",response_model=list[GetScoreResponse],summary='根据成绩查询学生信息') def get_students(min_score:int|None=None,max_score:int|None=None,db=Depends(get_db)): l = select_score(min_score,max_score,db) - return [i for i in l] + return l -@StatisticsAPI.get("/avg_score",response_model=list[AcgScoreResponse],tags=['统计分析模块'],summary='统计每次考试每个班级的平均分并排序') +@StatisticsAPI.get("/avg_score",response_model=list[AcgScoreResponse],summary='统计每次考试每个班级的平均分并排序') def get_scores(db=Depends(get_db)): l = select_avg_score(db) return l -@StatisticsAPI.get("/salary",response_model=list[StudentResponse],tags=['统计分析模块'],summary='统计薪资最高的前五名的学员信息') +@StatisticsAPI.get("/salary",response_model=list[GetStuResponse],summary='统计薪资最高的前五名的学员信息') def get_scores(db=Depends(get_db)): l = select_salary(db) return l -@StatisticsAPI.get("/avg_day",response_model=list[AvgDayResponse],tags=['统计分析模块'],summary='统计每个班级的平均就业时长') +@StatisticsAPI.get("/avg_day",response_model=list[AvgDayResponse],summary='统计每个班级的平均就业时长') def get_days(db=Depends(get_db)): - l = select_days(db) + l = select_avg_days(db) return l - -@StatisticsAPI.get('/emp',response_model=AllEmpResponse,tags=['统计分析模块'],summary='统计每个学生的就业时长') +@StatisticsAPI.get('/emp',response_model=list[AllDayResponse],summary='统计每个学生的就业时长') def get_emp(db=Depends(get_db)): - l= select_days2(db) + l= select_days(db) return l - -# 薪资区间分布:统计薪资在5k以下、5k-10k、10k-15k、15k以上的人数分布,反映学生的整体就业质量。 -@StatisticsAPI.get('/salaries',tags=['统计分析模块'],summary='统计薪资分布') -def get_salaries(db=Depends(get_db)): - s=classify_salary(db) - return s \ No newline at end of file diff --git a/PythonProject/api/student_api.py b/PythonProject/api/student_api.py index 981de80..3b1bb2b 100644 --- a/PythonProject/api/student_api.py +++ b/PythonProject/api/student_api.py @@ -1,12 +1,12 @@ -from fastapi import APIRouter,Depends,HTTPException +from fastapi import APIRouter,HTTPException,Depends from dao.student_dao import * from schema.student_schema import * from util.database import get_db -StudentAPI = APIRouter() +StudentAPI = APIRouter(tags=['学生基本信息管理模块']) -@StudentAPI.get('/students',response_model=StudentPageResponse,tags=['学⽣基本信息管理模块'],summary='学生信息查询接口',description='查询学生信息') +@StudentAPI.get('/students',response_model=StudentPageResponse,summary='学生信息查询接口',description='查询学生信息') def get_students(stu_id:int|None=None ,stu_name:str|None=None ,class_id:int|None=None @@ -27,19 +27,19 @@ def get_students(stu_id:int|None=None totals=total, data=r) -@StudentAPI.put('/{stu_id}',tags=['学⽣基本信息管理模块'],summary='学生信息更新接口',description='更新学生信息') +@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) if not d: - raise HTTPException(status_code=400, detail='更新内容不能为空!') + raise HTTPException(status_code=400, detail='更新内容不能为空') r = update_student_dao( stu_id=stu_id,update_data=d,db=db ) if not r: - raise HTTPException(status_code=500, detail='没有更新!') + raise HTTPException(status_code=500, detail='没有更新') return {'code':200,'totals':r,'detail':'更新成功'} -@StudentAPI.delete('/{stu_id}',tags=['学⽣基本信息管理模块'],summary='学生信息删除接口',description='删除学生信息') +@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 ) @@ -47,11 +47,15 @@ def del_students(stu_id:int raise HTTPException(status_code=404,detail='对象已被删除') return {'code':200,'totals':rows,'detail':'删除成功'} -@StudentAPI.post('/students',tags=['学⽣基本信息管理模块'],response_model=StugetResponse,summary='学生信息新增接口',description='新增学生信息') +@StudentAPI.post('/students',response_model=StugetResponse,summary='学生信息新增接口',description='新增学生信息') def add_students(s:StudentRequest ,db=Depends(get_db)): - d=s.model_dump(exclude_unset=True) - stu_new=add_student_dao(o=d,db=db) - if not stu_new: - raise HTTPException(status_code=404,detail='添加失败') - return stu_new + d = s.model_dump(exclude_unset=True) + if not d: + raise HTTPException(status_code=400, detail='添加内容不能为空') + r = add_student_dao( o=d, db=db) + if r == 'conflict': + raise HTTPException(status_code=409, detail='身份证号已存在,请勿重复添加') + if r == 'error': + raise HTTPException(status_code=500, detail='更添加失败,请稍后重试') + return r diff --git a/PythonProject/api/teacher_api.py b/PythonProject/api/teacher_api.py index 95f2dad..0fab498 100644 --- a/PythonProject/api/teacher_api.py +++ b/PythonProject/api/teacher_api.py @@ -6,16 +6,16 @@ from dao.teacher_dao import update_teacher from dao.teacher_dao import delete_teacher from dao.teacher_dao import get_teacher -teacher_api=APIRouter() +teacher_api=APIRouter(tags=['教师基本信息管理模块']) -@teacher_api.post("/teachers",response_model=Teacher_ResponseModel,tags=['教师基本信息管理模块'],summary='新增教师接口') +@teacher_api.post("/teachers",response_model=Teacher_ResponseModel,summary='新增教师接口') def add_teacher1(x1:Teacher_RequestModel,session=Depends(get_db)): y=add_teacher(x1.model_dump(),session) if not y: raise HTTPException(status_code=500,detail='添加异常!') return x1 -@teacher_api.get("/teachers",tags=['教师基本信息管理模块'],summary='查询教师接口') +@teacher_api.get("/teachers",summary='查询教师接口') def get_teacher1(teacid:int, session=Depends(get_db)): # r = get_teacher(id=id,session=session) # if not r: @@ -27,7 +27,7 @@ def get_teacher1(teacid:int, session=Depends(get_db)): raise HTTPException(status_code=500,detail='数据库查询异常!') -@teacher_api.put("/teachers/{t_id}",tags=['教师基本信息管理模块'],summary='更新教师接口') +@teacher_api.put("/teachers/{t_id}",summary='更新教师接口') def update_teacher1(t_id:int,teacher:Teacher_RequestModel,session=Depends(get_db)): d=teacher.model_dump(exclude_unset=True) r=update_teacher(id=t_id,req=d,session=session) @@ -36,7 +36,7 @@ def update_teacher1(t_id:int,teacher:Teacher_RequestModel,session=Depends(get_db return {'code':200,'detail':'更新成功!','data':teacher} -@teacher_api.delete("/teachers/{t_id}",tags=['教师基本信息管理模块'],summary='删除教师接口') +@teacher_api.delete("/teachers/{t_id}",summary='删除教师接口') def delete_teacher1(t_id:int,session=Depends(get_db)): r=delete_teacher(id=t_id,session=session) if not r: diff --git a/PythonProject/dao/cla_dao.py b/PythonProject/dao/cla_dao.py index 8b12825..23267a9 100644 --- a/PythonProject/dao/cla_dao.py +++ b/PythonProject/dao/cla_dao.py @@ -3,17 +3,17 @@ from fastapi import HTTPException from schema.cla_schema import claRequest -def add_class_dao(c:claRequest,session): +def add_class_dao(c: claRequest, session): try: data = c.model_dump() d = ClassManagement(**data) session.add(d) + session.commit() + session.refresh(d) + return d except: session.rollback() - return '输入有误,请重新添加班级!' - else: - session.commit() - return '添加成功!' + raise HTTPException(400, "输入有误,请重新添加班级!") def get_class_dao(n,m,session): try: @@ -22,7 +22,7 @@ def get_class_dao(n,m,session): except: raise HTTPException(status_code=406,detail="输入查询信息有误,请重新输入!") -def update_class_dao(id:int,req:ClassManagement,session): +def update_class_dao(id:int,req:claRequest,session): try: session.query(ClassManagement).filter(ClassManagement.class_id==id)\ .filter(ClassManagement.delete_status==0).update(req.model_dump(exclude_unset=True)) diff --git a/PythonProject/dao/employment_dao.py b/PythonProject/dao/employment_dao.py index cd3fe5c..2a7e1fc 100644 --- a/PythonProject/dao/employment_dao.py +++ b/PythonProject/dao/employment_dao.py @@ -1,69 +1,67 @@ -from fastapi import HTTPException, APIRouter +from fastapi import HTTPException from model.all_model import Employment_info, ClassManagement, Student_Model from datetime import datetime -emp_api = APIRouter() -def get_emp_dao(stu_id=None,class_id=None,company_name=None,min_salary=None,max_salary=None,db=None): - try: - q = db.query(Employment_info).\ - join(Student_Model,Employment_info.stu_id == Student_Model.stu_id).\ - join(ClassManagement,Student_Model.class_id == ClassManagement.class_id).\ - filter(Employment_info.delete_status == 0).\ - filter(Student_Model.delete_status == 0).\ - filter(ClassManagement.delete_status == 0) - if stu_id: - q = q.filter(Employment_info.stu_id == stu_id) - if class_id: - q = q.filter(ClassManagement.class_id == class_id) - if company_name: - q = q.filter(Employment_info.company_name == company_name) - if min_salary: - q = q.filter(Employment_info.salary >= min_salary) - if max_salary: - q = q.filter(Employment_info.salary <= max_salary) +def get_emp_dao(db,stu_id=None,class_id=None,company_name=None,min_salary=None,max_salary=None): + q = db.query(Employment_info.emp_id + ,Employment_info.stu_id + ,Student_Model.stu_name + ,Student_Model.class_id + ,Employment_info.email + ,Employment_info.employment_opening_date + ,Employment_info.offer_issuance_date + ,Employment_info.company_name + ,Employment_info.company_address + ,Employment_info.salary)\ + .join(Student_Model,Employment_info.stu_id == Student_Model.stu_id)\ + .join(ClassManagement,Student_Model.class_id == ClassManagement.class_id)\ + .filter(Employment_info.delete_status == 0)\ + .filter(Student_Model.delete_status == 0)\ + .filter(ClassManagement.delete_status == 0) + + if stu_id: + q = q.filter(Employment_info.stu_id == stu_id) + if class_id: + q = q.filter(ClassManagement.class_id == class_id) + if company_name: + q = q.filter(Employment_info.company_name == company_name) + if min_salary: + q = q.filter(Employment_info.salary >= min_salary) + if max_salary: + q = q.filter(Employment_info.salary <= max_salary) + + r = q.all() + if not r: + raise HTTPException(status_code=500,detail='查询异常,没有结果!') + return r - r = q.all() - if r: - return [{'emp_id':i.emp_id - ,'stu_id': i.stu_id - ,'stu_name':i.Student_Model.stu_name - ,'class_id':i.Student_Model.class_id - ,'email':i.email - ,'employment_opening_date':i.employment_opening_date - ,'offer_issuance_date':i.offer_issuance_date - ,'company_name':i.company_name - ,'company_address':i.company_address - ,'salary':i.salary - }for i in r - ] - except: - raise HTTPException(status_code=404,detail='信息不存在!') def add_emp_dao(o,db): try: - stu = db.query(Student_Model).filter(Student_Model.stu_id == o['stu_id'], Student_Model.delete_status == 0).first() + stu = db.query(Student_Model).filter(Student_Model.stu_id == o['stu_id'] + , Student_Model.delete_status == 0).first() if not stu: raise HTTPException(status_code=404, detail='该学生不存在,无法添加就业信息') - exist = db.query(Employment_info).filter(Employment_info.stu_id == o['stu_id'], - Employment_info.delete_status == 0).first() + exist = (db.query(Employment_info).filter(Employment_info.stu_id == o['stu_id'] + ,Employment_info.delete_status == 0).first()) if exist: raise HTTPException(status_code=409, detail='该学生已有就业信息,请勿重复增加!') e1 = Employment_info(**o) db.add(e1) db.commit() - return o - except HTTPException: - raise + return e1 except Exception as e: db.rollback() raise HTTPException(status_code=500, detail=f'新增就业信息失败: {e}') -def update_emp_dao(stu_id,o,db): +def update_emp_dao(emp_id,emp,db): try: - rows = db.query(Employment_info).filter(Employment_info.stu_id == stu_id,Employment_info.delete_status == 0).first() + rows = db.query(Employment_info)\ + .filter(Employment_info.emp_id == emp_id,Employment_info.delete_status == 0)\ + .update(emp) db.commit() return rows except: @@ -71,10 +69,11 @@ def update_emp_dao(stu_id,o,db): raise HTTPException(status_code=404,detail='该就业记录已存在') -def delete_emp_dao(stu_id,db): +def delete_emp_dao(emp_id:int,db): try: rows = db.query(Employment_info)\ - .filter(Employment_info.stu_id == stu_id,Employment_info.delete_status == 0)\ + .filter(Employment_info.emp_id == emp_id + ,Employment_info.delete_status == 0)\ .update({'delete_status':1,'delete_time': datetime.now()}) db.commit() except: diff --git a/PythonProject/dao/grade_dao.py b/PythonProject/dao/grade_dao.py index 358645e..2619fac 100644 --- a/PythonProject/dao/grade_dao.py +++ b/PythonProject/dao/grade_dao.py @@ -19,10 +19,26 @@ def get_score_by_stu_exam_order_dao(stu_id:str,exam_order:int,db): def get_grade_dao( stu_id:int , db): - r1 =db.query(WlScore).filter(WlScore.stu_id == stu_id,WlScore.delete_status == 0).all() + r1 =(db.query( WlScore.score_id + ,WlScore.stu_id + ,Student_Model.stu_name + ,WlScore.exam_order + ,WlScore.score + ) + .join(Student_Model,WlScore.stu_id == Student_Model.stu_id) + .filter(WlScore.stu_id == stu_id,WlScore.delete_status == 0,Student_Model.delete_status == 0) + .all()) if r1: - - return r1 + data_list = [] + for row in r1: + data_list.append({ + "score_id": row.score_id, + "stu_id": row.stu_id, + "stu_name": row.stu_name, + "exam_order": row.exam_order, + "score": row.score + }) + return data_list else: raise HTTPException(status_code=404,detail="学生不存在") diff --git a/PythonProject/dao/statistics_dao.py b/PythonProject/dao/statistics_dao.py index 5f79595..81e140b 100644 --- a/PythonProject/dao/statistics_dao.py +++ b/PythonProject/dao/statistics_dao.py @@ -23,7 +23,17 @@ def select_all(db): try: l1 = db.query(Student_Model.class_id,Student_Model.gender,func.count(1).label('cnt'))\ .group_by(Student_Model.class_id,Student_Model.gender).all() - return l1 + all_cnt = sum(i.cnt for i in l1) + + l2 = [] + for i in l1: + l2.append({ + "all_cnt": all_cnt, + "class_id": i.class_id, + "gender": i.gender, + "cnt": i.cnt + }) + return l2 except Exception: raise HTTPException(status_code=500,detail="查询异常") @@ -32,12 +42,23 @@ def select_score(min_score,max_score,db): try: if min_score is None and max_score is None: raise HTTPException(status_code=400, detail="请至少传入一个参数") - db = db.query(Student_Model,WlScore.score,WlScore.score)\ + db = db.query(WlScore.score + ,Student_Model.stu_name + ,Student_Model.age + ,Student_Model.gender + ,Student_Model.native_place + ,Student_Model.school + ,Student_Model.major + ,Student_Model.degree + ,Student_Model.admission_date + ,Student_Model.graduation_date + ,Student_Model.progress + )\ .join(WlScore,WlScore.stu_id == Student_Model.stu_id)\ .filter(WlScore.delete_status==0,Student_Model.delete_status == 0) if min_score is not None: db = db.filter(WlScore.score >= min_score) - if min_score is not None: + if max_score is not None: db = db.filter(WlScore.score <= max_score) return db.all() except HTTPException: @@ -60,7 +81,17 @@ def select_avg_score(db): # 实现统计薪资最高的前五名的学员信息 def select_salary(db): try: - l1 = db.query(Student_Model,Employment_info.salary)\ + l1 = db.query(Employment_info.salary + ,Student_Model.stu_name + ,Student_Model.age + ,Student_Model.gender + ,Student_Model.native_place + ,Student_Model.school + ,Student_Model.major + ,Student_Model.degree + ,Student_Model.admission_date + ,Student_Model.graduation_date + ,Student_Model.progress)\ .join(Employment_info,Employment_info.stu_id==Student_Model.stu_id)\ .filter(Employment_info.delete_status==0,Student_Model.delete_status == 0)\ .order_by(Employment_info.salary.desc())\ @@ -70,7 +101,7 @@ def select_salary(db): raise HTTPException(status_code=500,detail="查询异常") # 实现统计每个班级的平均就业时长 -def select_days(db): +def select_avg_days(db): try: l1 = db.query(Student_Model.class_id, func.coalesce( @@ -84,27 +115,20 @@ def select_days(db): Employment_info.delete_status == 0, Employment_info.employment_opening_date.isnot(None), Employment_info.offer_issuance_date.isnot(None),)\ - .group_by( Student_Model.class_id)\ + .group_by(Student_Model.class_id)\ .order_by(func.avg(func.datediff(Employment_info.offer_issuance_date,Student_Model.admission_date)).desc()).all() return l1 except Exception: raise HTTPException(status_code=500, detail="查询异常") #统计每个学⽣的就业时⻓ -def select_days2(db): +def select_days(db): try: - l2 =db.query( - Employment_info.stu_id - ,Employment_info.employment_opening_date - ,Employment_info.offer_issuance_date - ,func.datediff( - Employment_info.offer_issuance_date - ,Employment_info.employment_opening_date - ) - .label("employment_duration_day") - ).filter( - Employment_info.delete_status == 0 - ).all() + l2 =db.query(Employment_info.stu_id + ,func.coalesce(func.datediff(Employment_info.offer_issuance_date + ,Employment_info.employment_opening_date),0)\ + .label("diff_days") + ).filter(Employment_info.delete_status == 0).all() return l2 except Exception: raise HTTPException(status_code=500, detail="查询异常") diff --git a/PythonProject/dao/student_dao.py b/PythonProject/dao/student_dao.py index 9f755ac..0822d9d 100644 --- a/PythonProject/dao/student_dao.py +++ b/PythonProject/dao/student_dao.py @@ -1,19 +1,28 @@ -from fastapi import Depends -from util.database import get_db from model.all_model import Student_Model from typing import List, Optional, Dict, Any from datetime import datetime +from sqlalchemy.exc import IntegrityError def add_student_dao(o,db): + if o.get('id_card'): + conflict = (db.query(Student_Model) + .filter(Student_Model.id_card == o['id_card'], + Student_Model.delete_status == 0) + .first()) + if conflict: + return 'conflict' try: - o1 = Student_Model( **o) - db.add(o1) + o2 = Student_Model(**o) + db.add(o2) db.commit() - stu_id=o1.stu_id - return db.query(Student_Model).filter(Student_Model.stu_id == stu_id).first() - except: + db.refresh(o2) # 回填自增的 stu_id + return o2 + except IntegrityError: db.rollback() - return None + return 'conflict' + except Exception: + db.rollback() + return 'error' def delete_student_dao(stu_id,db): try: @@ -28,14 +37,14 @@ def delete_student_dao(stu_id,db): def update_student_dao(stu_id,update_data,db): try: - rows = (db.query( Student_Model ) - .filter( Student_Model.stu_id == stu_id,Student_Model.delete_status == 0) - .update( update_data )) - db.commit() + rows=(db.query(Student_Model) + .fiter(Student_Model.stu_id == stu_id,Student_Model.delete_status == 0) + .update(update_data)) except: db.rollback() return False else: + db.commit() return rows def get_student_dao(stu_id:Optional[int] diff --git a/PythonProject/main.py b/PythonProject/main.py index 3b07189..3474b17 100644 --- a/PythonProject/main.py +++ b/PythonProject/main.py @@ -5,7 +5,16 @@ from api.statistics_api import StatisticsAPI from api.teacher_api import teacher_api from api.grade_api import gradeAPI from api.cla_api import claAPI -app = FastAPI(title='沃林学⽣管理系统') + +tags_metadata = [ + {"name": "教师基本信息管理模块"}, + {"name": "班级管理模块"}, + {"name": "学生基本信息管理模块"}, + {"name": "学生考核成绩管理模块"}, + {"name": "学生就业管理模块"}, + {"name": "统计分析模块"}, +] +app = FastAPI(title='沃林学⽣管理系统',openapi_tags=tags_metadata) app.include_router(StudentAPI) diff --git a/PythonProject/model/all_model.py b/PythonProject/model/all_model.py index 4c96f84..eccb6e9 100644 --- a/PythonProject/model/all_model.py +++ b/PythonProject/model/all_model.py @@ -1,4 +1,4 @@ -from sqlalchemy import DATETIME,Column,Integer,String,DATE,ForeignKey,Numeric +from sqlalchemy import DATETIME,Column,Integer,String,DATE,ForeignKey,Numeric,UniqueConstraint from datetime import datetime from util.database import Base,engine @@ -23,6 +23,8 @@ class Student_Model(Base): native_place=Column(String(200),comment='籍贯') + id_card=Column(String(18),unique=True,comment='身份证号') + birthday=Column(DATE,comment='生日') school=Column(String(100),comment='毕业学校') @@ -54,7 +56,7 @@ class ClassManagement(Base): class_id= Column(Integer, primary_key=True, autoincrement=True,comment='班级编号') - class_name = Column(String(100), comment='班级姓名') + class_name = Column(String(100), comment='班级名字') start_class_date = Column(DATE,comment='开课时间') @@ -68,7 +70,7 @@ class ClassManagement(Base): delete_status = Column(Integer,default=0,comment='删除状态:0未删除,1已删除') - delete_time = Column(DATETIME,comment='删除时间') + delete_time = Column(DATETIME,default=datetime.now,onupdate=datetime.now,comment='删除时间') class Teacher_Model(Base): __tablename__ = 'wl_teacher' @@ -145,7 +147,7 @@ class Employment_info(Base): delete_status = Column( Integer,default=0,comment='删除状态:0未删除,1已删除') - delete_time = Column(DATETIME,comment='删除时间') + delete_time = Column(DATETIME,default=None,comment='删除时间') class WlScore(Base): __tablename__ = 'wl_score' diff --git a/PythonProject/schema/employment_schema.py b/PythonProject/schema/employment_schema.py index 9bc9a26..1505868 100644 --- a/PythonProject/schema/employment_schema.py +++ b/PythonProject/schema/employment_schema.py @@ -1,16 +1,30 @@ -from fastapi import HTTPException from pydantic import BaseModel, Field,field_validator, model_validator from datetime import date from typing import Optional class EmploymentRequest(BaseModel): - stu_id: int=Field(ge=1) - email: str|None = None - employment_opening_date:date|None = None - offer_issuance_date:date|None = None - company_name:str|None = None - company_address:str|None = None - salary:float|None = None + stu_id: int=Field(ge=1,description='学生编号') + email: Optional[str] = Field(None, description='邮箱') + employment_opening_date:Optional[date] = Field(None, description='就业开放日期') + offer_issuance_date:Optional[date] = Field(None, description='offer下发日期') + company_name:Optional[str] = Field(None, description='公司名称') + company_address:Optional[str] = Field(None, description='公司地址') + salary:Optional[float] = Field(None, description='薪资') + + @model_validator(mode='after') + def check_date(self): + if self.employment_opening_date and self.offer_issuance_date: + if self.employment_opening_date > self.offer_issuance_date: + raise ValueError('offer下发日期不能早于就业开放日期') + return self + +class UpdateEmpRequest(BaseModel): + email: Optional[str] = Field(None, description='邮箱') + employment_opening_date:Optional[date] = Field(None, description='就业开放日期') + offer_issuance_date:Optional[date] = Field(None, description='offer下发日期') + company_name:Optional[str] = Field(None, description='公司名称') + company_address:Optional[str] = Field(None, description='公司地址') + salary:Optional[float] = Field(None, description='薪资') @model_validator(mode='after') def check_date(self): @@ -22,7 +36,10 @@ class EmploymentRequest(BaseModel): class EmploymentResponse(BaseModel): code:int = 200 detail:str = 'OK' + emp_id: int stu_id:int + stu_name: Optional[str] = None + class_id: Optional[int] = None email: str|None = None employment_opening_date:date|None = None offer_issuance_date:date|None = None diff --git a/PythonProject/schema/grade_schema.py b/PythonProject/schema/grade_schema.py index 4d89cd4..a381ab9 100644 --- a/PythonProject/schema/grade_schema.py +++ b/PythonProject/schema/grade_schema.py @@ -1,5 +1,5 @@ -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, field_validator class GradeRequest(BaseModel): @@ -7,6 +7,18 @@ class GradeRequest(BaseModel): exam_order:int = Field(description='考核序次') score:float = Field(description='成绩') + @field_validator("score") + def check_score(cls, v): + if not (0 <= v <= 100): + raise ValueError("成绩必须在0~100之间") + return v + + @field_validator("exam_order") + def check_exam_order(cls, v): + if v <= 0: + raise ValueError("考核序次必须大于0") + return v + class GradeResponse(BaseModel): code: int = 200 detail: str = 'OK' diff --git a/PythonProject/schema/statistics_schema.py b/PythonProject/schema/statistics_schema.py index 2b76ae4..a61e1b7 100644 --- a/PythonProject/schema/statistics_schema.py +++ b/PythonProject/schema/statistics_schema.py @@ -1,8 +1,8 @@ -from pydantic import BaseModel,Field +from pydantic import BaseModel,field_serializer from datetime import date -from typing import List, Optional class AllStuResponse(BaseModel): + all_cnt: int class_id: int gender: str | None cnt: int @@ -11,21 +11,61 @@ class AcgScoreResponse(BaseModel): class_id: int avg_score: float +class GetScoreResponse(BaseModel): + code:int = 200 + detail:str = 'ok' + score:float + stu_name: str | None = None + age: int | None = None + gender: str | None = None + native_place: str | 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 = 0 + + @field_serializer('progress') + def int_to_string(self, progress: int): + d1 = { + 0: '学习中', + 1: '求职中', + 2: '已就业' + } + return d1.get(progress, '暂不明确') + +class GetStuResponse(BaseModel): + code:int = 200 + detail:str = 'ok' + salary:float + stu_name: str | None = None + age: int | None = None + gender: str | None = None + native_place: str | 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 = 0 + + @field_serializer('progress') + def int_to_string(self, progress: int): + d1 = { + 0: '学习中', + 1: '求职中', + 2: '已就业' + } + return d1.get(progress, '暂不明确') + class AvgDayResponse(BaseModel): class_id: int - avg_days: str | None + avg_days: float | None -class EmpRequest(BaseModel): +class AllDayResponse(BaseModel): + code:int = 200 + detail:str = 'ok' stu_id: int - -class EmpItem(BaseModel): - stu_id: int - employment_opening_date:date | None - offer_issuance_date:date | None - employment_duration_day: int | None - -class AllEmpResponse(BaseModel): - code: int - msg: str - data: List[EmpItem] + diff_days: int | None diff --git a/PythonProject/schema/student_schema.py b/PythonProject/schema/student_schema.py index 58894ec..53579eb 100644 --- a/PythonProject/schema/student_schema.py +++ b/PythonProject/schema/student_schema.py @@ -9,6 +9,7 @@ class StudentRequest(BaseModel): stu_name:str age:int |None = None gender:str |None = None + id_card:str native_place:str |None = None birthday:date |None = None school:str |None = None @@ -40,7 +41,7 @@ class StudentResponse(BaseModel): progress:int @field_serializer('progress') - def int_to_string(cls,progress:int): + def int_to_string(self,progress:int): d1 ={ 0:'学习中', 1:'求职中', @@ -57,6 +58,7 @@ class StugetResponse(BaseModel): stu_name: str | None = None age: int | None = None gender: str | None = None + id_card: str native_place: str | None = None birthday: date | None = None school: str | None = None @@ -67,7 +69,7 @@ class StugetResponse(BaseModel): progress: int = 0 @field_serializer('progress') - def int_to_string(cls, progress: int): + def int_to_string(self, progress: int): d1 = { 0: '学习中', 1: '求职中', @@ -81,4 +83,6 @@ class StudentPageResponse(BaseModel): page: int page_size: int totals: int - data: List[StugetResponse] \ No newline at end of file + data: List[StugetResponse] + +