Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f90c6a5c3 | ||
|
|
1be706c267 | ||
|
|
6033504d76 | ||
|
|
9c24a229c7 | ||
|
|
fd3e52f4ff | ||
|
|
1933466e3d | ||
|
|
9a0f2d533a | ||
|
|
2807c30683 | ||
|
|
bca68a56f4 | ||
|
|
ca427bc8d2 | ||
|
|
7c0129bcc7 | ||
|
|
d0c3abbebb | ||
|
|
49e651b9f3 | ||
|
|
93f2356c5d | ||
|
|
505e59280e | ||
|
|
c40fae3948 | ||
|
|
5c873491c6 | ||
|
|
6e0185d38a | ||
|
|
4d59d79812 | ||
|
|
1e453d159f | ||
|
|
cd619d687d | ||
|
|
c7744308bc | ||
|
|
f71d769bb2 | ||
|
|
34eef4f575 | ||
|
|
4d49bfce6f | ||
|
|
e0ad464acf | ||
|
|
ce64044898 | ||
|
|
8a3850511c | ||
|
|
eb62d5bb7f | ||
|
|
4230262aed | ||
|
|
1029221fde | ||
|
|
acd5bc4954 | ||
|
|
02492719c4 | ||
|
|
fa4fd4a402 | ||
|
|
13357e8935 | ||
|
|
52269842d8 | ||
|
|
569443f489 | ||
|
|
d34ec5a29e | ||
|
|
b70994d9bb | ||
|
|
12a2126806 | ||
|
|
099a2eb5a0 | ||
|
|
458cdac004 | ||
|
|
1577daac42 | ||
|
|
2cf4744929 | ||
|
|
87fa2514bf | ||
|
|
b034829b06 |
+4
-1
@@ -8,6 +8,9 @@ __pycache__/
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
.env
|
||||
.env.local
|
||||
.local-data-backups/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
@@ -20,4 +23,4 @@ Thumbs.db
|
||||
|
||||
.idea/
|
||||
.idea.backup/
|
||||
.run/
|
||||
.run/
|
||||
|
||||
+36
-34
@@ -10,45 +10,47 @@ classes_router = APIRouter()
|
||||
|
||||
#以下分别定义增、删、改、查的路由的接口函数,以便api接口函数中执行
|
||||
|
||||
# ————定义班级表"更新"信息的"接口"函数————
|
||||
@classes_router.post('/',response_model=ClassResponse,summary='新增班级信息') # 定义班级创建路由,POST请求,指定返回数据格式为 ClassResponse
|
||||
def post_classes(classes:ClassCreate,db=Depends(get_db)): # 定义更新接口函数,参数classes声明创建请求模型,参数db依赖于数据库会话的上下文管理器
|
||||
c = classes.model_dump() # 变量c用来接收通过model_dump将Pydantic模型对象解析为Python的字典,方便后续解包传参
|
||||
r = post_classes_dao( c , db ) # 变量r用来接收dao层post_classes_dao函数的返回值,执行函数时以变量c的数据和db依赖函数入参
|
||||
if r : # 判断 DAO 层的返回结果,如果为True
|
||||
return ClassResponse( total=1,data=c ) # 返回成功响应,携带新增的数据给前端
|
||||
else : # 如果为False
|
||||
# ————定义班级表"新增"信息的接口函数————
|
||||
@classes_router.post('/',response_model=ClassResponse,summary='新增班级信息') # POST新增请求,指定返回数据格式为 ClassResponse
|
||||
def post_classes(classes:ClassCreate,db=Depends(get_db)): # 定义更新接口函数,参数classes声明创建请求模型,参数db依赖于数据库会话的上下文管理器
|
||||
c = classes.model_dump() # 变量c用来接收通过model_dump将Pydantic模型对象解析为Python的字典,方便后续解包传参
|
||||
r = post_classes_dao( c , db ) # 变量r用来接收dao层post_classes_dao函数的返回值,执行函数时以变量c的数据和db依赖函数入参
|
||||
if r : # 判断 DAO 层的返回结果,如果为True
|
||||
return ClassResponse( total=1,data=c ) # 返回成功响应,携带新增的数据给前端
|
||||
else : # 如果为False
|
||||
raise HTTPException(status_code=500,detail='添加失败,服务器繁忙,请稍后添加!') # 抛出 500 内部服务器错误 和提示
|
||||
|
||||
|
||||
@classes_router.put('/{id}',response_model=ClassResponse,summary='更新班级信息')
|
||||
def put_classes(classes:ClassUpdate,id:int,db=Depends(get_db)):
|
||||
updates = classes.model_dump( exclude_unset=True )
|
||||
r = update_classes_dao( id, db, updates )
|
||||
if not r :
|
||||
raise HTTPException(status_code=500, detail='更新失败,该班级已不存在或服务器繁忙,请稍后更新!')
|
||||
return ClassResponse(detail='更新成功', total=1 ,data = updates )
|
||||
# ————定义班级表"更新"信息的接口函数————
|
||||
@classes_router.put('/{id}',response_model=ClassResponse,summary='更新班级信息') # put更新请求,指定返回数据格式为 ClassResponse
|
||||
def put_classes( classes:ClassUpdate , id:int , db=Depends( get_db ) ): # 定义更新接口函数,id参数接收前端输入的数据,参数classes声明更新请求体模型,参数db依赖于数据库会话的上下文管理器
|
||||
updates = classes.model_dump( exclude_unset=True ) # 变量updates用来接收通过model_dump将Pydantic模型对象解析为Python的字典(只解析输入的数据),方便后续解包传参
|
||||
r = update_classes_dao( id, db, updates ) # 变量r用来接收dao层update_classes_dao函数的返回值,执行函数时以变量c的数据、db依赖函数、和前端更新的数据入参
|
||||
if r : # 判断 DAO 层的返回结果,如果为True
|
||||
return ClassResponse( detail='更新成功', total=1 ,data = updates ) # 返回成功响应,携带更新的数据给前端
|
||||
raise HTTPException( status_code=500, detail='更新失败,该班级已不存在或服务器繁忙,请稍后更新!' ) # 如果为False,抛出 500 内部服务器错误 和提示
|
||||
|
||||
|
||||
@classes_router.get('',summary='查询班级信息')
|
||||
def get_classes( id:int|None = None
|
||||
, class_no:str|None = None
|
||||
, class_name:str|None = None
|
||||
, page:int = 1
|
||||
, page_size:int = 5
|
||||
, db=Depends(get_db)
|
||||
# ————定义班级表"查询"信息的接口函数————
|
||||
@classes_router.get('',summary='查询班级信息') # get查询请求
|
||||
def get_classes( id:int|None = None # id参数接收前端输入的数据,声明是整数,可以为空默认为空
|
||||
, class_no:str|None = None # class_no参数接收前端输入的数据,声明是字符串,可以为空默认为空
|
||||
, class_name:str|None = None # class_name参数接收前端输入的数据,声明是字符串,可以为空默认为空
|
||||
, page:int = 1 # page参数接收前端输入的数据,声明是整数,默认是1
|
||||
, page_size:int = 5 # page参数接收前端输入的数据,声明是整数,默认是5
|
||||
, db=Depends(get_db) # 参数db依赖于数据库会话的上下文管理器
|
||||
):
|
||||
t,r = get_classes_dao( id , class_no , class_name , page , page_size ,db )
|
||||
if t != 0 :
|
||||
return ClassResponse( total = t, data = r )
|
||||
else :
|
||||
return ClassResponse( code = 404,detail = '没有符合条件的班级,请检查输入是否有误')
|
||||
t,r = get_classes_dao( id , class_no , class_name , page , page_size ,db ) # 变量t,r用来接收dao层get_classes_dao函数的返回值,执行函数时以前端输入的id , class_no , class_name , page , page_size 、db依赖函数入参
|
||||
if t != 0 : # 判断 DAO 层的返回结果,如果为条数不为0
|
||||
return ClassResponse( total = t, data = r ) # 返回成功响应,返回符合条件的总条数,携带符合条件的数据给前端
|
||||
return ClassResponse( code = 404,detail = '没有符合条件的班级,请检查输入是否有误') # 判断 DAO 层的返回结果,如果为条数为0,返回404响应,提示没有符合条件的提示给前端
|
||||
|
||||
|
||||
@classes_router.delete('/{id}',response_model=ClassResponse,summary='删除班级信息')
|
||||
def delete_classes(id:int,db=Depends(get_db)):
|
||||
r = delete_classes_dao( id , db )
|
||||
if r :
|
||||
return ClassResponse( total=1,data='已成功删除班级信息' )
|
||||
else :
|
||||
raise HTTPException(status_code=500, detail='删除失败,该班级信息已不存在或服务器繁忙,请稍后更新!')
|
||||
|
||||
# ————定义班级表"删除"信息的接口函数————
|
||||
@classes_router.delete('/{id}',response_model=ClassResponse,summary='删除班级信息') # delete删除请求,指定返回数据格式为 ClassResponse
|
||||
def delete_classes(id:int,db=Depends(get_db)): # 定义删除接口函数,id参数接收前端输入的数据,参数db依赖于数据库会话的上下文管理器
|
||||
r = delete_classes_dao( id , db ) # 变量r用来接收dao层delete_classes_dao函数的返回值,执行函数时以以前端输入的id 数据、db依赖函数入参
|
||||
if r : # 判断 DAO 层的返回结果,如果是True
|
||||
return ClassResponse( total=1,data='已成功删除班级信息' ) # 返回成功响应和提示给前端 # 如果是False
|
||||
raise HTTPException(status_code=500, detail='删除失败,该班级信息已不存在或服务器繁忙,请稍后更新!') # 如果为False,抛出 500 内部服务器错误 和提示
|
||||
+45
-36
@@ -1,21 +1,19 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from core.database import get_db
|
||||
from dao.employment import (
|
||||
create_employment,
|
||||
get_employment_by_id,
|
||||
get_employment_by_student_id,
|
||||
get_employment_list,
|
||||
update_employment,
|
||||
delete_employment_logic
|
||||
)
|
||||
from schemas.employment import (
|
||||
EmploymentCreate,
|
||||
EmploymentUpdate,
|
||||
EmploymentResponse
|
||||
)
|
||||
from dao.employment import (create_employment,
|
||||
get_employment_by_id,
|
||||
get_employment_by_student_id,
|
||||
get_employment_list,
|
||||
update_employment,
|
||||
delete_employment_logic,
|
||||
recover_employment_delete)
|
||||
|
||||
employment_router = APIRouter(prefix="/employments", tags=["就业管理模块"])
|
||||
from schemas.employment import (EmploymentCreate,
|
||||
EmploymentUpdate,
|
||||
EmploymentResponse)
|
||||
|
||||
employment_router = APIRouter( tags=["就业管理模块"])
|
||||
|
||||
|
||||
@employment_router.post("/", response_model=EmploymentResponse, summary="新增就业信息")
|
||||
@@ -31,36 +29,38 @@ def add_employment(body: EmploymentCreate, db: Session = Depends(get_db)):
|
||||
return res
|
||||
|
||||
|
||||
@employment_router.get("/students/{student_id}", response_model=EmploymentResponse, summary="查询指定学生的就业信息")
|
||||
def query_student_employment(student_id: int, db: Session = Depends(get_db)):
|
||||
"""根据学生id获取对应就业记录"""
|
||||
record = get_employment_by_student_id(db, student_id)
|
||||
if not record:
|
||||
raise HTTPException(status_code=404, detail="未找到该学生的就业信息")
|
||||
return record
|
||||
#
|
||||
|
||||
# @employment_router.get("/students/{student_id}", response_model=EmploymentResponse, summary="查询指定学生的就业信息")
|
||||
# def query_student_employment(student_id: int, db: Session = Depends(get_db)):
|
||||
# """根据学生id获取对应就业记录"""
|
||||
# record = get_employment_by_student_id(db, student_id)
|
||||
# if not record:
|
||||
# raise HTTPException(status_code=404, detail="未找到该学生的就业信息")
|
||||
# return record
|
||||
|
||||
|
||||
@employment_router.get("/", summary="就业信息列表,支持筛选")
|
||||
def query_employment_list(
|
||||
company_name: str | None = Query(None, description="公司名称模糊查询"),
|
||||
salary_min: float | None = Query(None, description="最低薪资"),
|
||||
salary_max: float | None = Query(None, description="最高薪资"),
|
||||
skip: int = Query(0, ge=0, description="偏移量"),
|
||||
limit: int = Query(20, ge=1, le=100, description="每页条数"),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
def query_employment_list(eid:int| None = Query(None, description="就业编号"),
|
||||
student_id:int| None = Query(None,description="学生id"),
|
||||
company_name: str | None = Query(None, description="公司名称模糊查询"),
|
||||
salary_min: float | None = Query(None, description="最低薪资"),
|
||||
salary_max: float | None = Query(None, description="最高薪资"),
|
||||
skip: int = Query(0, ge=0, description="偏移量"),
|
||||
limit: int = Query(20, ge=1, le=100, description="每页条数"),
|
||||
db: Session = Depends(get_db)):
|
||||
# 调用dao列表查询,拿到数据字典列表和总条数
|
||||
data_list, total = get_employment_list(db, company_name, salary_min, salary_max, skip, limit)
|
||||
return {"total": total, "data": data_list}
|
||||
|
||||
|
||||
@employment_router.get("/{eid}", response_model=EmploymentResponse, summary="根据id查询就业详情")
|
||||
def query_employment_detail(eid: int, db: Session = Depends(get_db)):
|
||||
"""根据就业主键id查询单条就业记录"""
|
||||
record = get_employment_by_id(db, eid)
|
||||
if not record:
|
||||
raise HTTPException(status_code=404, detail="就业记录不存在或已被逻辑删除")
|
||||
return record
|
||||
# @employment_router.get("/{eid}", response_model=EmploymentResponse, summary="根据id查询就业详情")
|
||||
# def query_employment_detail(eid: int, db: Session = Depends(get_db)):
|
||||
# """根据就业主键id查询单条就业记录"""
|
||||
# record = get_employment_by_id(db, eid)
|
||||
# if not record:
|
||||
# raise HTTPException(status_code=404, detail="就业记录不存在或已被逻辑删除")
|
||||
# return record
|
||||
|
||||
|
||||
@employment_router.put("/{eid}", response_model=EmploymentResponse, summary="修改就业信息")
|
||||
@@ -80,3 +80,12 @@ def logic_delete_employment(eid: int, db: Session = Depends(get_db)):
|
||||
raise HTTPException(status_code=404, detail="删除失败,记录不存在")
|
||||
# 删除成功返回提示字典
|
||||
return {"code": 200, "msg": "逻辑删除成功"}
|
||||
|
||||
@employment_router.get("/{eid}", summary="回档逻辑删除就业记录")
|
||||
def recover_delete_employment(eid: int, db: Session = Depends(get_db)):
|
||||
"""执行逻辑删除,is_deleted置1,不会真正删除数据库行"""
|
||||
ok = recover_employment_delete(db, eid)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=404, detail="回档失败,记录已经存在")
|
||||
# 删除成功返回提示字典
|
||||
return {"code": 200, "msg": "回档成功"}
|
||||
@@ -0,0 +1,23 @@
|
||||
from fastapi import APIRouter, Depends, FastAPI
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.database import get_db
|
||||
from magic_llm.llm_func import llm_func
|
||||
|
||||
|
||||
|
||||
magic_router = APIRouter(tags=["智能数据库接口"])
|
||||
|
||||
|
||||
class MagicRequest(BaseModel):
|
||||
user_request: str
|
||||
|
||||
|
||||
@magic_router.post("/magic")
|
||||
def Fastapi_magic(req: MagicRequest, db: Session = Depends(get_db)):
|
||||
executor, code = llm_func(req.user_request)
|
||||
return {"generated_code": code, "result": executor(db)}
|
||||
|
||||
|
||||
|
||||
+4
-3
@@ -1,7 +1,7 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from core.database import get_db
|
||||
from dao.score import post_score_dao, update_score_dao, get_score_dao, delete_score_dao, exist_student_exam_dao
|
||||
from dao.score import post_score_dao, update_score_dao, get_score_dao,delete_score_dao, exist_student_exam_dao
|
||||
from schemas.score import ScoreCreate, ScoreUpdate, ScorePageResp
|
||||
|
||||
scores_router = APIRouter(prefix="/scores", tags=["成绩接口"])
|
||||
@@ -12,14 +12,13 @@ def create_score(req: ScoreCreate, db: Session = Depends(get_db)):
|
||||
# 业务校验:联合唯一
|
||||
if exist_student_exam_dao(req.student_id, req.exam_seq, db):
|
||||
raise HTTPException(status_code=400, detail="该学生本次考试成绩已存在,不能重复录入")
|
||||
|
||||
ok = post_score_dao(req.model_dump(), db)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=400, detail="新增成绩失败,请检查学生id是否存在")
|
||||
return {"msg": "新增成功"}
|
||||
|
||||
|
||||
@scores_router.get("", response_model=ScorePageResp, summary="查询成绩接口")
|
||||
@scores_router.get("", response_model=ScorePageResp, summary="个人成绩查询接口")
|
||||
def list_score(
|
||||
score_id: int|None=None,
|
||||
student_id: int |None=None,
|
||||
@@ -32,6 +31,8 @@ def list_score(
|
||||
return {"total": total, "data": data_list}
|
||||
|
||||
|
||||
|
||||
|
||||
@scores_router.put("{score_id}", summary="更新成绩接口")
|
||||
def modify_score(score_id: int, req: ScoreUpdate, db: Session = Depends(get_db)):
|
||||
update_dict = req.model_dump(exclude_unset=True)
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ from schemas.common import SuccessResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
statistics_router=APIRouter(tags=['statistics'])
|
||||
statistics_router=APIRouter(tags=['统计接口'])
|
||||
|
||||
|
||||
@statistics_router.get("/students/age-over-30",response_model=SuccessResponse)
|
||||
|
||||
+61
-13
@@ -1,4 +1,5 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException,Query,Path
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.database import get_db
|
||||
@@ -6,7 +7,7 @@ from schemas.student import StudentCreate, StudentUpdate
|
||||
from dao import student as student_dao
|
||||
student_router = APIRouter()
|
||||
|
||||
@student_router.post("",summary='添加学生')
|
||||
@student_router.put("",summary='添加学生')
|
||||
def create_student(request:StudentCreate,db:Session = Depends(get_db)):
|
||||
d = request.model_dump()
|
||||
r = student_dao.create_students(d,db)
|
||||
@@ -14,7 +15,7 @@ def create_student(request:StudentCreate,db:Session = Depends(get_db)):
|
||||
raise HTTPException(status_code=500,detail='服务器繁忙,请稍后添加!')
|
||||
return {'code':200,'detail':"添加学生成功"}
|
||||
|
||||
@student_router.put("/{id}", summary="修改学生")
|
||||
@student_router.post("/{id}", summary="更新学生信息")
|
||||
def update_student(
|
||||
id: int,
|
||||
request: StudentUpdate,
|
||||
@@ -34,38 +35,69 @@ def update_student(
|
||||
if student is False:
|
||||
raise HTTPException(status_code=500, detail="修改学生失败")
|
||||
|
||||
#传入空字典报400
|
||||
if not data:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="没有传入需要修改的字段",
|
||||
)
|
||||
|
||||
return {
|
||||
"code": 200,
|
||||
"detail": "修改学生成功",
|
||||
"data": student,
|
||||
}
|
||||
|
||||
@student_router.get("", summary="查询学生列表")
|
||||
@student_router.get("", summary="分页查询学生列表")
|
||||
def get_students(
|
||||
# 三个查询条件都可以不传
|
||||
student_no: str | None = None,
|
||||
student_name: str | None = None,
|
||||
class_id: int | None = None,
|
||||
student_no: str | None = Query(default=None,description="按学号精确查询"),
|
||||
student_name: str | None = Query(default=None,description="按名字模糊查询"),
|
||||
class_id: int | None = Query(default=None,gt=0,description="按班级号精确查询"),
|
||||
# 获取本次请求使用的数据库连接
|
||||
db: Session = Depends(get_db),
|
||||
page:int = Query(default=1,ge=1,description="页码,从1开始"),
|
||||
page_size:int = Query(default=10,ge=1,le=100,description="每页条数,最多100条"),
|
||||
):
|
||||
# 调用 DAO 查询数据库
|
||||
students = student_dao.get_students(
|
||||
total, students = student_dao.get_students(
|
||||
db=db,
|
||||
student_no=student_no,
|
||||
student_name=student_name,
|
||||
class_id=class_id,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
data = [
|
||||
{
|
||||
"id": student.id,
|
||||
"student_no": student.student_no,
|
||||
"student_name": student.student_name,
|
||||
"class_id": student.class_id,
|
||||
"consultant_id": student.consultant_id,
|
||||
"native_place": student.native_place,
|
||||
"graduation_school": student.graduation_school,
|
||||
"major": student.major,
|
||||
"enrollment_date": student.enrollment_date,
|
||||
"graduation_date": student.graduation_date,
|
||||
"education": student.education,
|
||||
"age": student.age,
|
||||
"gender": student.gender,
|
||||
}
|
||||
for student in students
|
||||
]
|
||||
return {
|
||||
"code": 200,
|
||||
"detail": "查询成功",
|
||||
"total": len(students),
|
||||
"data": students,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"data": data,
|
||||
}
|
||||
|
||||
@student_router.get("/{id}", summary="查询学生详情")
|
||||
def get_student(id: int, db: Session = Depends(get_db)):
|
||||
def get_student(id: int = Path(gt=0),
|
||||
db: Session = Depends(get_db)):
|
||||
# 根据路径中的 ID 查询学生
|
||||
student = student_dao.get_student_by_id(id, db)
|
||||
|
||||
@@ -73,10 +105,26 @@ def get_student(id: int, db: Session = Depends(get_db)):
|
||||
# 404 表示请求的数据不存在
|
||||
raise HTTPException(status_code=404, detail="学生不存在")
|
||||
|
||||
result = {
|
||||
"id": student.id,
|
||||
"student_no": student.student_no,
|
||||
"student_name": student.student_name,
|
||||
"class_id": student.class_id,
|
||||
"consultant_id": student.consultant_id,
|
||||
"native_place": student.native_place,
|
||||
"graduation_school": student.graduation_school,
|
||||
"major": student.major,
|
||||
"enrollment_date": student.enrollment_date,
|
||||
"graduation_date": student.graduation_date,
|
||||
"education": student.education,
|
||||
"age": student.age,
|
||||
"gender": student.gender,
|
||||
}
|
||||
|
||||
return {
|
||||
"code": 200,
|
||||
"detail": "查询成功",
|
||||
"data": student,
|
||||
"data": result,
|
||||
}
|
||||
|
||||
@student_router.delete("/{id}", summary="逻辑删除学生")
|
||||
|
||||
+61
-40
@@ -15,47 +15,68 @@ def post_classes_dao( c , db ): # 定义函数,设置两个
|
||||
db.commit() # 提交事务:将数据真正持久化写入到数据库中
|
||||
return True # 返回 True,返回接口,表示操作成功
|
||||
|
||||
def update_classes_dao( class_id , db , updates ):
|
||||
try :
|
||||
r = db.query(Classes).filter(Classes.id ==class_id , Classes.is_deleted == 0 ).update(updates)
|
||||
except :
|
||||
db.rollback()
|
||||
return False
|
||||
else :
|
||||
db.commit()
|
||||
return r
|
||||
|
||||
# ————定义班级表"更新"信息的函数————
|
||||
def update_classes_dao( class_id , db , updates ): # 定义函数,设置三个形参class_id,db ,updates
|
||||
try : # 执行以下可能报错的代码
|
||||
db.query(Classes).filter(Classes.id ==class_id , Classes.is_deleted == 0 ).update(updates) # 将接口函数接收的更新数据更新到Classes模型对象,条件是未删除且前端输入的id和数据库id可以匹配上的
|
||||
except : # 捕获异常:
|
||||
db.rollback() # 如果中间出错,回滚事务,防止产生脏数据
|
||||
return False # 返回 False,返回接口,表示操作失败
|
||||
else : # 执行成功:
|
||||
db.commit() # 提交事务:将数据真正持久化写入到数据库中
|
||||
return True # 返回 True,返回接口,表示操作成功
|
||||
|
||||
|
||||
def get_classes_dao( class_id, class_no , class_name , page , page_size , db ):
|
||||
q = db.query( Classes ).filter( Classes.is_deleted == 0 )
|
||||
if class_id :
|
||||
q = q.filter( Classes.id == class_id )
|
||||
if class_no :
|
||||
q = q.filter( Classes.class_no == class_no )
|
||||
if class_name :
|
||||
q = q.filter( Classes.class_name == class_name )
|
||||
total = q.count()
|
||||
r = q.offset( ( page-1 ) * page_size ).limit( page_size ).all()
|
||||
return total,[ { 'class_id':i.id
|
||||
, 'class_no':i.class_no
|
||||
, 'class_name':i.class_name
|
||||
, 'start_date':i.start_date
|
||||
, 'end_date':i.end_date
|
||||
, 'created_at':i.created_at
|
||||
, 'update_at':i.update_at
|
||||
, 'remark':i.remark
|
||||
}
|
||||
for i in r
|
||||
]
|
||||
# ————定义班级表"查询"信息的函数————
|
||||
from sqlalchemy import func, and_ ,desc # 从sqlalchemy模块导入func聚合函数的类、and_函数,降序排序desc函数
|
||||
from models.student import Student # 从models包下的student模块导入Student表模型类
|
||||
|
||||
def get_classes_dao( class_id, class_no , class_name , page , page_size , db ): # 定义函数,设置六个形参class_id, class_no , class_name , page , page_size , db
|
||||
q = db.query( Classes.id.label('class_id') # 查询班级ID(别名class_id)
|
||||
, Classes.class_no # 班级编号
|
||||
, Classes.class_name # 班级名称
|
||||
, func.count(Student.id).label('student_count') # 统计班级未删除的学生人数(别名student_count)
|
||||
, Classes.start_date #开课时间
|
||||
, Classes.end_date #结课时间
|
||||
, Classes.created_at #创建时间
|
||||
, Classes.update_at #更新时间
|
||||
, Classes.remark #备注信息
|
||||
). \
|
||||
outerjoin(Student, and_(Classes.id == Student.class_id, Student.is_deleted == 0)). \
|
||||
filter( Classes.is_deleted == 0 ) # 左连接学生表,并指定连接条件(未删除的学生)
|
||||
if class_id : # 如果传入了班级id参数
|
||||
q = q.filter( Classes.id == class_id ) # 则追加id过滤条件
|
||||
if class_no : # 如果传入了班级no参数
|
||||
q = q.filter( Classes.class_no == class_no ) # 则追加no过滤条件
|
||||
if class_name : # 如果传入了班级name参数
|
||||
q = q.filter( Classes.class_name == class_name ) # 则追加name过滤条件
|
||||
q = q.group_by(Classes.id, Classes.class_no, Classes.class_name) # 按班级ID、编号、名称进行分组聚合
|
||||
q = q.order_by( desc('student_count') ) # 按学生人数(别名)进行降序排列
|
||||
total = q.count() # total变量接收满足当前所有过滤条件的数据总条数
|
||||
r = q.offset((page - 1) * page_size).limit(page_size).all() # 变量r用来接收查询取出结果列表,计算分页偏移量(从第几行开始查),设置分页限制条数
|
||||
return total, [ # 返回 total变量总条数 和 将查询结果列表转换为字典列表的数据
|
||||
{
|
||||
'class_id': i.class_id # 提取班级ID
|
||||
, 'class_no': i.class_no # 提取班级编号
|
||||
, 'class_name': i.class_name # 提取班级名称
|
||||
, 'student_count': i.student_count # 提取班级总人数
|
||||
, 'start_date':i.start_date # 提取开课日期
|
||||
, 'end_date':i.end_date # 提取结课日期
|
||||
, 'created_at':i.created_at # 提取创建时间
|
||||
, 'update_at':i.update_at # 提取更新时间
|
||||
, 'remark':i.remark # 提取备注信息
|
||||
}
|
||||
for i in r # 循环遍历查询出的每一行数据 i
|
||||
]
|
||||
|
||||
|
||||
def delete_classes_dao( class_id , db ):
|
||||
try :
|
||||
db.query( Classes ).filter( Classes.id == class_id , Classes.is_deleted == 0 ).update( {"is_deleted": 1} )
|
||||
except :
|
||||
db.rollback()
|
||||
return False
|
||||
else :
|
||||
db.commit()
|
||||
return True
|
||||
# ————定义班级表"删除"信息的函数————
|
||||
def delete_classes_dao( class_id , db ): # 定义函数,设置两个个形参class_id,db
|
||||
try : # 执行以下可能报错的代码
|
||||
db.query( Classes ).filter( Classes.id == class_id , Classes.is_deleted == 0 ).update( {"is_deleted": 1} ) # 将未删除且前端输入的id和数据库id可以匹配上的数据更新is_deleted字段为1,表示已逻辑删除
|
||||
except : # 捕获异常:
|
||||
db.rollback() # 如果中间出错,回滚事务,防止产生脏数据
|
||||
return False # 返回 False,返回接口,表示操作失败
|
||||
else : # 执行成功:
|
||||
db.commit() # 提交事务:更新is_deleted字段为1,表示已逻辑删除,前端无法查询到已逻辑删除的数据
|
||||
return True # 返回 True,返回接口,表示操作成功
|
||||
|
||||
+108
-51
@@ -1,39 +1,52 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from models.employment import Employment
|
||||
from schemas.employment import EmploymentCreate, EmploymentUpdate, EmploymentResponse
|
||||
from schemas.employment import EmploymentResponse
|
||||
|
||||
|
||||
def create_employment(db, obj_in):
|
||||
def create_employment(db, e):
|
||||
# obj_in是Pydantic对象(EmploymentCreate)
|
||||
"""新增就业信息:一个学生只能存在一条就业记录"""
|
||||
try:
|
||||
# obj_in.model_dump()把pydantic请求对象转为字典,解包传给Employment生成ORM对象
|
||||
db_obj = Employment(**obj_in.model_dump())
|
||||
# add:把对象加入数据库会话,此时还没写入数据库
|
||||
db_obj = Employment(**e.model_dump())
|
||||
db.add(db_obj)
|
||||
# commit:提交事务,真正写入mysql数据库
|
||||
db.commit()
|
||||
# refresh:从数据库刷新对象,拿到数据库自动生成的id、默认时间等字段
|
||||
db.refresh(db_obj)
|
||||
# model_validate:把sqlalchemy ORM对象解析进pydantic响应模型
|
||||
# model_dump:把pydantic模型转为普通python字典返回给上层api
|
||||
return EmploymentResponse.model_validate(db_obj).model_dump()
|
||||
|
||||
resp = EmploymentResponse(id=db_obj.id
|
||||
,student_id=db_obj.student_id
|
||||
,employment_status=db_obj.employment_status
|
||||
,employment_open_date=db_obj.employment_open_date
|
||||
,offer_date=db_obj.offer_date
|
||||
,company_name=db_obj.company_name
|
||||
,salary=db_obj.salary
|
||||
,remark=db_obj.remark
|
||||
,created_at=db_obj.created_at
|
||||
,updated_at=db_obj.updated_at)
|
||||
return resp.model_dump()
|
||||
|
||||
except Exception:
|
||||
# 发生任何异常,执行回滚,撤销本次会话中未提交的数据库改动
|
||||
db.rollback()
|
||||
# 异常情况返回None,上层api可以判断新增失败
|
||||
return None
|
||||
|
||||
|
||||
def get_employment_by_id(db, eid):
|
||||
"""根据主键id查询就业详情,过滤逻辑删除"""
|
||||
try:
|
||||
db_obj = db.query(Employment).filter(
|
||||
Employment.id == eid,
|
||||
Employment.is_deleted == 0
|
||||
).first()
|
||||
db_obj = db.query(Employment).filter(Employment.id == eid
|
||||
,Employment.is_deleted == 0).first()
|
||||
if not db_obj:
|
||||
return None
|
||||
return EmploymentResponse.model_validate(db_obj).model_dump()
|
||||
|
||||
resp = EmploymentResponse(id=db_obj.id
|
||||
,student_id=db_obj.student_id
|
||||
,employment_status=db_obj.employment_status
|
||||
,employment_open_date=db_obj.employment_open_date
|
||||
,offer_date=db_obj.offer_date
|
||||
,company_name=db_obj.company_name
|
||||
,salary=db_obj.salary
|
||||
,remark=db_obj.remark
|
||||
,created_at=db_obj.created_at
|
||||
,updated_at=db_obj.updated_at)
|
||||
return resp.model_dump()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@@ -41,75 +54,119 @@ def get_employment_by_id(db, eid):
|
||||
def get_employment_by_student_id(db, student_id):
|
||||
"""根据学生id查询就业信息,过滤逻辑删除"""
|
||||
try:
|
||||
db_obj = db.query(Employment).filter(
|
||||
Employment.student_id == student_id,
|
||||
Employment.is_deleted == 0
|
||||
).first()
|
||||
db_obj = db.query(Employment).filter(Employment.student_id == student_id
|
||||
,Employment.is_deleted == 0).first()
|
||||
if not db_obj:
|
||||
return None
|
||||
return EmploymentResponse.model_validate(db_obj).model_dump()
|
||||
|
||||
resp = EmploymentResponse(id=db_obj.id
|
||||
,student_id=db_obj.student_id
|
||||
,employment_status=db_obj.employment_status
|
||||
,employment_open_date=db_obj.employment_open_date
|
||||
,offer_date=db_obj.offer_date
|
||||
,company_name=db_obj.company_name
|
||||
,salary=db_obj.salary
|
||||
,remark=db_obj.remark
|
||||
,created_at=db_obj.created_at
|
||||
,updated_at=db_obj.updated_at)
|
||||
return resp.model_dump()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def get_employment_list(db, company_name=None, salary_min=None, salary_max=None, skip=0, limit=20):
|
||||
def get_employment_list(db, id=None,student_id=None,company_name=None, salary_min=None, salary_max=None, skip=0, limit=20):
|
||||
"""就业列表查询;支持公司名模糊、薪资范围筛选;只查询is_deleted=0"""
|
||||
try:
|
||||
query = db.query(Employment).filter(Employment.is_deleted == 0)
|
||||
if id is not None:
|
||||
query = query.filter(Employment.id >= id)
|
||||
if student_id is not None:
|
||||
query = query.filter(Employment.student_id >= student_id)
|
||||
if company_name:
|
||||
query = query.filter(Employment.company_name.like(f"%{company_name}%"))
|
||||
if salary_min is not None:
|
||||
query = query.filter(Employment.salary >= salary_min)
|
||||
if salary_max is not None:
|
||||
query = query.filter(Employment.salary <= salary_max)
|
||||
# count()统计满足条件总条数,用于分页total
|
||||
|
||||
total = query.count()
|
||||
# offset偏移量(跳过多少条),limit每页多少条,执行查询拿到结果列表
|
||||
records = query.offset(skip).limit(limit).all()
|
||||
# 列表推导式:循环每一条ORM记录,全部转为字典,得到字典列表
|
||||
dict_list = [EmploymentResponse.model_validate(item).model_dump() for item in records]
|
||||
# 返回字典列表 + 总条数
|
||||
|
||||
dict_list = []
|
||||
for item in records:
|
||||
resp = EmploymentResponse(id=item.id
|
||||
,student_id=item.student_id
|
||||
,employment_status=item.employment_status
|
||||
,employment_open_date=item.employment_open_date
|
||||
,offer_date=item.offer_date
|
||||
,company_name=item.company_name
|
||||
,salary=item.salary
|
||||
,remark=item.remark
|
||||
,created_at=item.created_at
|
||||
,updated_at=item.updated_at)
|
||||
dict_list.append(resp.model_dump())
|
||||
|
||||
return dict_list, total
|
||||
except Exception:
|
||||
# 异常返回空列表,总条数0
|
||||
return [], 0
|
||||
|
||||
|
||||
def update_employment(db, eid, obj_in):
|
||||
def update_employment(db, eid, e):
|
||||
"""修改就业信息,只更新传入的字段"""
|
||||
try:
|
||||
# 根据id查询未删除的记录
|
||||
db_obj_raw = db.query(Employment).filter(
|
||||
Employment.id == eid,
|
||||
Employment.is_deleted == 0
|
||||
).first()
|
||||
# 记录不存在直接返回None
|
||||
if db_obj_raw is None:
|
||||
x = db.query(Employment).filter(Employment.id == eid
|
||||
,Employment.is_deleted == 0).first()
|
||||
if x is None:
|
||||
return None
|
||||
# exclude_unset=True:只取出前端实际传过来的字段,不会带上没传的None字段
|
||||
update_dict = obj_in.model_dump(exclude_unset=True)
|
||||
for key, value in update_dict.items():
|
||||
setattr(db_obj_raw, key, value)
|
||||
|
||||
update_dict = e.model_dump(exclude_unset=True)
|
||||
db.query(Employment).filter(Employment.id == eid
|
||||
,Employment.is_deleted == 0).update(update_dict)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_obj_raw)
|
||||
return EmploymentResponse.model_validate(db_obj_raw).model_dump()
|
||||
db.refresh(x)
|
||||
|
||||
resp = EmploymentResponse(id=x.id
|
||||
,student_id=x.student_id
|
||||
,employment_status=x.employment_status
|
||||
,employment_open_date=x.employment_open_date
|
||||
,offer_date=x.offer_date
|
||||
,company_name=x.company_name
|
||||
,salary=x.salary
|
||||
,remark=x.remark
|
||||
,created_at=x.created_at
|
||||
,updated_at=x.updated_at)
|
||||
return resp.model_dump()
|
||||
|
||||
except Exception:
|
||||
db.rollback()
|
||||
return None
|
||||
return
|
||||
|
||||
|
||||
|
||||
def delete_employment_logic(db, eid):
|
||||
"""逻辑删除,只修改is_deleted=1,不做物理删除"""
|
||||
try:
|
||||
db_obj_raw = db.query(Employment).filter(
|
||||
Employment.id == eid,
|
||||
Employment.is_deleted == 0
|
||||
).first()
|
||||
if db_obj_raw is None:
|
||||
y = db.query(Employment).filter(Employment.id == eid
|
||||
,Employment.is_deleted == 0).first()
|
||||
if y is None:
|
||||
return False
|
||||
db_obj_raw.is_deleted = 1
|
||||
y.is_deleted = 1
|
||||
db.commit()
|
||||
return True
|
||||
except Exception:
|
||||
db.rollback()
|
||||
return False
|
||||
|
||||
def recover_employment_delete(db, eid):
|
||||
"""逻辑删除,只修改is_deleted=1,不做物理删除"""
|
||||
try:
|
||||
y = db.query(Employment).filter(Employment.id == eid).first()
|
||||
if y is None:
|
||||
return False
|
||||
y.is_deleted = 0
|
||||
db.commit()
|
||||
return True
|
||||
except Exception:
|
||||
db.rollback()
|
||||
return False
|
||||
+34
-14
@@ -1,4 +1,3 @@
|
||||
from sqlalchemy import DECIMAL
|
||||
from models.score import Score
|
||||
|
||||
def post_score_dao(data_dict, db):
|
||||
@@ -6,23 +5,27 @@ def post_score_dao(data_dict, db):
|
||||
try:
|
||||
obj = Score(**data_dict)
|
||||
db.add(obj)
|
||||
db.commit()
|
||||
except Exception as e:
|
||||
print("新增成绩异常:", e)
|
||||
db.rollback()
|
||||
return False
|
||||
else:
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
|
||||
def update_score_dao(score_id, db, updates):
|
||||
"""修改成绩,query.update方式"""
|
||||
try:
|
||||
db.query(Score).filter(
|
||||
cnt = db.query(Score).filter(
|
||||
Score.id == score_id,
|
||||
Score.is_deleted == 0
|
||||
).update(updates)
|
||||
except Exception:
|
||||
if cnt == 0:
|
||||
db.rollback()
|
||||
return False
|
||||
except Exception as e:
|
||||
print("修改成绩异常:", e)
|
||||
db.rollback()
|
||||
return False
|
||||
else:
|
||||
@@ -31,14 +34,25 @@ def update_score_dao(score_id, db, updates):
|
||||
|
||||
|
||||
def get_score_dao(score_id, student_id, exam_seq, page, page_size, db):
|
||||
"""分页查询成绩,多条件过滤,只查未删除"""
|
||||
"""分页查询成绩,多条件过滤,只查未删除
|
||||
规则:
|
||||
- score_id == 0 → 查所有学生成绩(仅分页,不加 id 过滤)
|
||||
- 三个筛选条件全为空(None) → 直接返回空,不查库
|
||||
- 其他情况 → 按传入条件过滤
|
||||
"""
|
||||
q = db.query(Score).filter(Score.is_deleted == 0)
|
||||
if score_id:
|
||||
q = q.filter(Score.id == score_id)
|
||||
if student_id:
|
||||
q = q.filter(Score.student_id == student_id)
|
||||
if exam_seq:
|
||||
q = q.filter(Score.exam_seq == exam_seq)
|
||||
|
||||
if score_id == 0:
|
||||
pass # score_id=0 → 查全部(分页)
|
||||
elif score_id is None and not student_id and not exam_seq:
|
||||
return 0, [] # 三个参数都没传 → 返回空
|
||||
else:
|
||||
if score_id:
|
||||
q = q.filter(Score.id == score_id)
|
||||
if student_id:
|
||||
q = q.filter(Score.student_id == student_id)
|
||||
if exam_seq:
|
||||
q = q.filter(Score.exam_seq == exam_seq)
|
||||
|
||||
total = q.count()
|
||||
rows = q.offset((page - 1) * page_size).limit(page_size).all()
|
||||
@@ -60,13 +74,19 @@ def get_score_dao(score_id, student_id, exam_seq, page, page_size, db):
|
||||
return total, res_list
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def delete_score_dao(score_id, db):
|
||||
"""逻辑删除,更新is_deleted=1"""
|
||||
try:
|
||||
db.query(Score).filter(
|
||||
cnt = db.query(Score).filter(
|
||||
Score.id == score_id,
|
||||
Score.is_deleted == 0
|
||||
).update({"is_deleted": 1})
|
||||
).update({"is_deleted": 1}) # ← 接住返回值
|
||||
if cnt == 0: # ← 关键:一行都没匹配到
|
||||
db.rollback()
|
||||
return False
|
||||
except Exception as err:
|
||||
print("删除成绩异常:", err)
|
||||
db.rollback()
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
from schemas.statistics import NoExist
|
||||
from sqlalchemy import func
|
||||
from time import time
|
||||
|
||||
#`GET /statistics/students/age-over-30`
|
||||
#查询所有超过 30 岁的学员信息
|
||||
|
||||
|
||||
+21
-8
@@ -1,9 +1,7 @@
|
||||
from schemas.student import *
|
||||
from core.database import get_db
|
||||
from models.student import *
|
||||
from models.student import Student
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
#新建学生
|
||||
def create_students(d: dict, db: Session):
|
||||
stu = Student(**d)
|
||||
|
||||
@@ -22,6 +20,7 @@ def create_students(d: dict, db: Session):
|
||||
print(f"插入学生失败: {e}")
|
||||
return None
|
||||
|
||||
#查询学生是否已经被逻辑删除
|
||||
def get_student_by_id(student_id: int, db: Session):
|
||||
# 同时判断 is_deleted,已经逻辑删除的学生不会被查到
|
||||
return db.query(Student).filter(
|
||||
@@ -29,6 +28,7 @@ def get_student_by_id(student_id: int, db: Session):
|
||||
Student.is_deleted == 0,
|
||||
).first()
|
||||
|
||||
#更新学生信息
|
||||
def update_student(student_id: int, data: dict, db: Session):
|
||||
# 第一步:先查询学生
|
||||
student = get_student_by_id(student_id, db)
|
||||
@@ -54,11 +54,14 @@ def update_student(student_id: int, data: dict, db: Session):
|
||||
print("修改学生失败:", e)
|
||||
return False
|
||||
|
||||
#允许条件输入的列表查询
|
||||
def get_students(
|
||||
db: Session,
|
||||
student_no: str | None = None,
|
||||
student_name: str | None = None,
|
||||
class_id: int | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
):
|
||||
# 第一步:只查询没有被删除的学生
|
||||
query = db.query(Student).filter(Student.is_deleted == 0)
|
||||
@@ -72,12 +75,22 @@ def get_students(
|
||||
# 姓名使用模糊查询,例如“张”可以查到“张三”
|
||||
query = query.filter(Student.student_name.like(f"%{student_name}%"))
|
||||
|
||||
if class_id:
|
||||
# 班级 ID 使用精确查询
|
||||
query = query.filter(Student.class_id == class_id)
|
||||
if class_id is not None:
|
||||
query = query.filter(Student.class_id == class_id)
|
||||
|
||||
# 第三步:执行查询并返回全部结果
|
||||
return query.all()
|
||||
# 分页之前统计符合条件的总条数
|
||||
total = query.count()
|
||||
|
||||
#默认按学生id排序
|
||||
students = (
|
||||
query
|
||||
.order_by(Student.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return total, students
|
||||
|
||||
#逻辑删除学生
|
||||
def delete_student(student_id: int, db: Session):
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,62 @@
|
||||
from openai import OpenAI
|
||||
from pathlib import Path
|
||||
from models.class_model import Classes
|
||||
from models.employment import Employment
|
||||
from models.student import Student
|
||||
from models.class_teacher import ClassTeachers
|
||||
from models.consultant import Consultant
|
||||
from models.score import Score
|
||||
from models.teacher import Teacher
|
||||
from sqlalchemy import func
|
||||
|
||||
def llm_func(input_user):
|
||||
|
||||
client = OpenAI(
|
||||
api_key="sk-2e7da09d2ef1432f96af95114824e6b5",
|
||||
base_url="https://api.deepseek.com"
|
||||
)
|
||||
|
||||
prom_path = Path(__file__).parent / "prom.txt" #拼接路径
|
||||
context = prom_path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
|
||||
# 2. 调用大模型
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="deepseek-flash",
|
||||
messages=[
|
||||
{
|
||||
"role": "system",
|
||||
"content": context
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": input_user
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
# 3. 获取AI回复
|
||||
code = response.choices[0].message.content
|
||||
print("====== LLM生成代码 ======")
|
||||
print(code)
|
||||
print("========================")
|
||||
|
||||
env = {
|
||||
"Student": Student,
|
||||
"Classes": Classes,
|
||||
"Employment": Employment,
|
||||
"ClassTeachers": ClassTeachers,
|
||||
"Consultant": Consultant,
|
||||
"Score": Score,
|
||||
"Teacher": Teacher,
|
||||
"func": func
|
||||
}
|
||||
|
||||
namespace={}
|
||||
exec(code, env,namespace)
|
||||
|
||||
execute_func = namespace["execute"]
|
||||
return execute_func,code
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
你是一个 Python + SQLAlchemy 动态代码生成器。
|
||||
|
||||
下面是当前学生管理系统所有 SQLAlchemy 数据库模型代码:
|
||||
|
||||
----------------
|
||||
{base_code}
|
||||
----------------
|
||||
|
||||
请根据数据库模型理解:
|
||||
- 有哪些数据表
|
||||
- 每个 ORM 模型的 Python 类名
|
||||
- 每个模型有哪些字段
|
||||
- 主键和外键关系
|
||||
- 模型之间应该如何进行 JOIN
|
||||
|
||||
用户需求:
|
||||
|
||||
{question}
|
||||
|
||||
你需要根据用户需求生成能够直接运行的 Python 函数。
|
||||
|
||||
回复必须严格遵守下面格式:
|
||||
|
||||
def execute(db):
|
||||
# 查询或数据库操作代码
|
||||
...
|
||||
return result
|
||||
|
||||
你已经获得完整的 SQLAlchemy ORM 模型代码。
|
||||
|
||||
必须直接使用模型代码中已经定义的 ORM 类和字段。
|
||||
|
||||
例如模型中存在 Student、Classes、Teacher、Employment,
|
||||
则直接使用这些类进行查询。
|
||||
|
||||
如果条件不够无法查询则返回条件不够无法查询并说明原因。
|
||||
|
||||
|
||||
规则:
|
||||
|
||||
1. 函数名称必须固定为 execute。
|
||||
2. 函数只能接收参数 db。
|
||||
3. db 是已经创建好的 SQLAlchemy Session。
|
||||
4. 使用现有 ORM Model 完成操作。
|
||||
5. 不要重新定义数据库模型。
|
||||
6. 不要创建数据库连接。
|
||||
7. 不要创建 Session。
|
||||
8. 不要生成 FastAPI 路由。
|
||||
9. 可以根据需求自由使用 query、filter、join、group_by、having、func、子查询等 SQLAlchemy 功能。
|
||||
10. 用户要求修改、增加或删除数据时可以调用 commit。
|
||||
11. execute 必须 return 最终结果。
|
||||
12. 尽量将查询结果转换为 dict、list、str、int、float 等容易 JSON 序列化的数据。
|
||||
13. 不要解释代码。
|
||||
14. 不要返回 Markdown。
|
||||
15. 不要使用 ```python。
|
||||
16. 不要使用 ```。
|
||||
17. 除 execute 函数源码之外,不要返回任何其他文字。
|
||||
|
||||
|
||||
|
||||
|
||||
禁止:
|
||||
1. 动态扫描 mapper
|
||||
2. 使用 mapperlib
|
||||
3. 使用 Base.registry 查找模型
|
||||
4. 根据字段名称猜测字段
|
||||
5. 根据表名猜测 ORM 类
|
||||
6. 动态寻找 relationship
|
||||
7. 使用 SQLAlchemy 内部 API
|
||||
|
||||
你必须根据提供的模型代码直接确定:
|
||||
- ORM 类
|
||||
- 字段
|
||||
- 外键关系
|
||||
- JOIN 条件
|
||||
|
||||
|
||||
|
||||
最终回复示例:
|
||||
|
||||
def execute(db):
|
||||
result = db.query(Student).all()
|
||||
return [
|
||||
{
|
||||
"id": item.id,
|
||||
"name": item.student_name
|
||||
}
|
||||
for item in result
|
||||
]
|
||||
|
||||
以下为建表语句,所有的查询操作都当围绕如下表进行
|
||||
|
||||
class Classes( Base ): # 在python里的名字
|
||||
__tablename__ = 'class_info_detail' # 在数据库中表的名字
|
||||
#————创建班级"主键"的字段名————
|
||||
id = Column( Integer # 声明字段的数据类型是"整数"
|
||||
, primary_key = True # 声明是"主键"
|
||||
, autoincrement = True # 声明是"自增主键"
|
||||
, nullable = False # 声明是"非空"
|
||||
)
|
||||
# ————创建班级"编号"的字段名————
|
||||
class_no = Column( String(50) # 声明字段的数据类型是"字符串,且最长为50个字符"
|
||||
, unique = True # 声明是"唯一约束"
|
||||
, nullable = False # 声明是"非空"
|
||||
)
|
||||
# ————创建"班级名称"的字段名————
|
||||
class_name = Column( String(100) # 声明字段的数据类型是"字符串,且最长为100个字符"
|
||||
, nullable = False # 声明是"非空"
|
||||
)
|
||||
# ————创建班级"开课时间"的字段名————
|
||||
start_date = Column( DATE # 声明是字段数据类型是日期
|
||||
, nullable = False # 开课时间必填
|
||||
)
|
||||
# ————创建班级"结课时间"的字段名————
|
||||
end_date = Column( DATE # 声明是字段数据类型是'日期'
|
||||
, nullable = True # 声明是"可为空"
|
||||
)
|
||||
# ————创建班级"创建时间"的字段名————
|
||||
created_at = Column( DATETIME # 声明是字段数据类型是"日期时间"
|
||||
, default=datetime.now # 声明是创建的默认值就是"当前时间"
|
||||
, server_default=text("CURRENT_TIMESTAMP")
|
||||
, nullable = False # 声明是"非空"
|
||||
)
|
||||
# ————创建班级"更新时间"的字段名————
|
||||
update_at = Column( DATETIME # 声明是字段数据类型是"日期时间"
|
||||
, default=datetime.now #声明是第一次更新的时间就是第一次创建的时间一致
|
||||
, onupdate=datetime.now # 声明"最后修改的时间"
|
||||
, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
|
||||
, nullable = False # 声明是"非空"
|
||||
)
|
||||
# ————创建班级"备注信息"的字段名————
|
||||
remark = Column( String(255) # 声明是字段数据类型是"字符串"
|
||||
, nullable = True # 声明是"可以为空"
|
||||
)
|
||||
# ————创建班级"逻辑删除"的字段名————
|
||||
is_deleted = Column( TINYINT # 逻辑删除标记
|
||||
, default = 0 # 声明默认值是"0,未删除"
|
||||
, server_default = text("0")
|
||||
, nullable = False # 声明是"非空"
|
||||
)
|
||||
|
||||
#班级老师关系表 class_teachers_info_detail 中间表 ORM 模型完整定义
|
||||
#字段包括id,class_id,teacher_id,role,created_at,updated_at,is_deleted
|
||||
class ClassTeachers(Base):
|
||||
__tablename__ = "class_teachers_info_detail"
|
||||
id = Column(
|
||||
Integer
|
||||
,primary_key=True
|
||||
,autoincrement=True
|
||||
,comment='关系')
|
||||
class_id = Column(
|
||||
Integer
|
||||
,ForeignKey('class_info_detail.id')
|
||||
,nullable=False
|
||||
,comment='关联 class_id'
|
||||
)
|
||||
teacher_id = Column(
|
||||
Integer
|
||||
,ForeignKey("teacher_info_detail.id")
|
||||
,nullable=False
|
||||
,comment='关联 teacher_id'
|
||||
)
|
||||
role = Column(
|
||||
VARCHAR(30)
|
||||
,nullable=False
|
||||
,comment='老师在班级中的角色:head_teacher班主任 / lecturer授课老师 / assistant助教'
|
||||
)
|
||||
created_at = Column(
|
||||
DateTime
|
||||
,nullable=False
|
||||
,default=datetime.now()
|
||||
,comment='创建时间'
|
||||
)
|
||||
updated_at = Column(
|
||||
DateTime
|
||||
,nullable=False
|
||||
,default=datetime.now()
|
||||
,comment='更新时间'
|
||||
)
|
||||
is_deleted = Column(
|
||||
TINYINT
|
||||
,nullable=False
|
||||
,default=0
|
||||
,comment='逻辑删除'
|
||||
)
|
||||
|
||||
class Consultant(Base):
|
||||
__tablename__ = "consultant_info_detail"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, comment="主键")
|
||||
consultant_no = Column(String(50), unique=True, nullable=False, comment="顾问编号")
|
||||
consultant_name = Column(String(50), nullable=False, comment="顾问姓名")
|
||||
phone = Column(String(20), nullable=True, comment="联系电话")
|
||||
email = Column(String(100), nullable=True, comment="邮箱")
|
||||
remark = Column(String(255), nullable=True, comment="备注")
|
||||
|
||||
created_at = Column(DateTime, default=datetime.now, server_default=text("CURRENT_TIMESTAMP"), nullable=False, comment="创建时间")
|
||||
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"), nullable=False, comment="更新时间")
|
||||
is_deleted = Column(TINYINT, default=0, server_default=text("0"), nullable=False, comment="逻辑删除:0正常,1删除")
|
||||
|
||||
|
||||
class Employment(Base):
|
||||
__tablename__ = "employment_info_detail" # 实际数据库的表名字
|
||||
id = Column(Integer, primary_key=True # 主键
|
||||
, autoincrement=True # 声明是自增主键
|
||||
,comment="就业信息主键id")
|
||||
student_id = Column(Integer, ForeignKey("student_info_detail.id") # 外键 -> students.id
|
||||
, nullable=False # 不允许为null
|
||||
,comment="关联学生id")
|
||||
employment_status = Column(String(50)
|
||||
, default="not_started"
|
||||
,comment="就业状态:not_started/job_hunting/offered/employed")
|
||||
employment_open_date = Column(Date
|
||||
,comment="就业开放时间")
|
||||
offer_date = Column(Date
|
||||
,comment="offer下发时间")
|
||||
company_name = Column(String(100)
|
||||
, comment="就业公司名称")
|
||||
salary = Column(DECIMAL(10, 2) # 高精度浮点数薪资,最多 10 位数字,小数占 2 位
|
||||
, comment="就业薪资")
|
||||
remark = Column(String(255)
|
||||
,default=None
|
||||
, comment="备注信息")
|
||||
created_at = Column(DateTime
|
||||
, default=datetime.now
|
||||
, comment="创建时间")
|
||||
updated_at = Column(DateTime
|
||||
, default=datetime.now
|
||||
, onupdate=datetime.now
|
||||
,comment="更新时间")
|
||||
is_deleted = Column(SmallInteger
|
||||
,default=0
|
||||
,comment="逻辑删除:0正常,1删除")
|
||||
|
||||
class Score(Base):
|
||||
__tablename__ = "score_info_detail"
|
||||
id = Column(Integer
|
||||
, primary_key=True
|
||||
,autoincrement=True
|
||||
,comment="成绩表序号,自增主键"
|
||||
)
|
||||
student_id = Column(Integer
|
||||
,ForeignKey("student_info_detail.id")
|
||||
,nullable=False
|
||||
,comment="学生学号"
|
||||
)
|
||||
score = Column(DECIMAL(4,1)
|
||||
,CheckConstraint("score between 0 and 100")
|
||||
)
|
||||
exam_seq= Column(Integer
|
||||
, nullable=False
|
||||
,comment="考试序次")
|
||||
__table_args__ = (
|
||||
UniqueConstraint("student_id"
|
||||
, "exam_seq"
|
||||
, name="uk_student_exam_seq"),
|
||||
)#学生id和学生姓名应为联合唯一,即一个学生一次考试只能有一个分数
|
||||
exam_date=Column(Date
|
||||
,default=date.today
|
||||
,comment="考试日期"
|
||||
)
|
||||
created_at=Column(DateTime
|
||||
,default=datetime.now
|
||||
,comment="创建时间"
|
||||
)
|
||||
updated_at=Column(DateTime
|
||||
,default=datetime.now
|
||||
,onupdate=datetime.now
|
||||
,comment="更新时间"
|
||||
)
|
||||
remark=Column(String(225)
|
||||
,comment="备注说明"
|
||||
)
|
||||
is_deleted=Column(Integer
|
||||
,default=0
|
||||
,comment="逻辑删除标记:未删除0,已删除1"
|
||||
)
|
||||
|
||||
class Student(Base):
|
||||
__tablename__ = 'student_info_detail'
|
||||
id = Column(Integer
|
||||
, primary_key=True
|
||||
, autoincrement=True
|
||||
, comment = '学生编号,自增主键'
|
||||
)
|
||||
student_no = Column(VARCHAR(50)
|
||||
,nullable = True
|
||||
,unique = True)
|
||||
student_name = Column(VARCHAR(50))
|
||||
class_id = Column(Integer
|
||||
,ForeignKey('class_info_detail.id')
|
||||
)#外键约束 班级表的主键id,存在这个班级,学生表才可以输入
|
||||
consultant_id = Column(Integer
|
||||
, ForeignKey('consultant_info_detail.id')
|
||||
,nullable = True
|
||||
)#外键约束 顾问表的主键id,存在这个顾问,才可以写入,允许为空
|
||||
native_place = Column(VARCHAR(100)
|
||||
,nullable = True)
|
||||
graduation_school = Column(VARCHAR(100)
|
||||
,nullable = True)
|
||||
major = Column(VARCHAR(100)
|
||||
,nullable = True)
|
||||
enrollment_date = Column(Date
|
||||
,nullable = False)#入学时间必填
|
||||
graduation_date = Column(Date,
|
||||
nullable = True)#毕业时间可以为空
|
||||
education = Column(VARCHAR(50)
|
||||
,nullable = True)#学历可以为空
|
||||
age = Column(Integer
|
||||
,nullable = False)
|
||||
gender = Column(VARCHAR(10)
|
||||
,nullable = False)
|
||||
create_at = Column(DATETIME
|
||||
,default = datetime.now)
|
||||
update_at = Column(DATETIME
|
||||
,default = datetime.now
|
||||
,onupdate = datetime.now)
|
||||
is_deleted = Column(Integer
|
||||
,default = 0)#逻辑删除,默认为0,为1则表示已删除
|
||||
|
||||
class Teacher(Base):
|
||||
__tablename__ = 'teacher_info_detail'
|
||||
id = Column(
|
||||
Integer
|
||||
, primary_key=True
|
||||
,autoincrement=True
|
||||
,comment='老师主键')
|
||||
teacher_no = Column(
|
||||
VARCHAR(50)
|
||||
,nullable=False
|
||||
,unique=True
|
||||
,comment='老师编号'
|
||||
)
|
||||
teacher_name = Column(
|
||||
VARCHAR(50)
|
||||
,nullable=False
|
||||
,comment='老师名字'
|
||||
)
|
||||
phone = Column(
|
||||
VARCHAR(20)
|
||||
,nullable=True
|
||||
,comment='老师电话'
|
||||
)
|
||||
email = Column(
|
||||
VARCHAR(100)
|
||||
,nullable=True
|
||||
,comment='邮箱'
|
||||
)
|
||||
remark = Column(
|
||||
VARCHAR(2550)
|
||||
,nullable=True
|
||||
,comment='备注'
|
||||
)
|
||||
created_at = Column(
|
||||
DateTime
|
||||
,nullable=False
|
||||
,default=datetime.now
|
||||
,comment='创建时间'
|
||||
)
|
||||
updated_at = Column(
|
||||
DateTime
|
||||
,nullable=False
|
||||
,default=datetime.now
|
||||
,comment='更新时间'
|
||||
)
|
||||
is_deleted = Column(
|
||||
TINYINT
|
||||
,nullable=False
|
||||
,default=0
|
||||
,comment='逻辑删除'
|
||||
)'''
|
||||
@@ -5,9 +5,11 @@ from api.statistics import statistics_router
|
||||
import uvicorn
|
||||
from api.student import student_router
|
||||
from api.teacher import router as teacher_router,class_teacher_router
|
||||
from api.magic import magic_router
|
||||
|
||||
app = FastAPI()
|
||||
app = FastAPI(title='学生管理系统')
|
||||
app.middleware("http")(log_middleware)
|
||||
app.include_router(magic_router)
|
||||
|
||||
#-------------朱婷婷--------------
|
||||
from api.class_api import classes_router
|
||||
@@ -23,13 +25,16 @@ from api import consultant
|
||||
app.include_router(consultant.router)
|
||||
#-------------张昕浩---------------
|
||||
app.include_router(example_router)
|
||||
app.include_router(magic_router)
|
||||
app.include_router(statistics_router, prefix="/statistics")
|
||||
|
||||
#-------------曾凯---------------
|
||||
|
||||
from api.score import scores_router
|
||||
app.include_router(scores_router, tags=['成绩接口'])
|
||||
#-------------南方宇---------------
|
||||
|
||||
from api.employment import employment_router
|
||||
app.include_router(employment_router, prefix="/employment")
|
||||
#-----------主程序----------------
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(app, host="0.0.0.0", port=23333)
|
||||
uvicorn.run(app, host="0.0.0.0", port=23333)
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
from sqlalchemy import *
|
||||
from sqlalchemy.orm import declarative_base,sessionmaker
|
||||
from sqlalchemy import * #导入sqlalchemy全部常用类
|
||||
from sqlalchemy.orm import declarative_base,sessionmaker #造会话工厂 SessionLocal,管数据库增删改查会话
|
||||
from datetime import datetime
|
||||
from core.database import Base, engine
|
||||
from core.database import Base #保证所有模型共用同一个Base,表才能正常生成
|
||||
|
||||
# 为了符合三范式,就业表只保存 student_id,不保存学生姓名和班级名称。查询返回时通过关联 students 和 classes 带出学生姓名、班级名称。
|
||||
|
||||
class Employment(Base):
|
||||
__tablename__ = "employment_info_detail" # 实际数据库的表名字
|
||||
id = Column(Integer, primary_key=True # 主键
|
||||
, autoincrement=True # 声明是自增主键
|
||||
__tablename__ = "employment_info_detail" # 映射的真实MySQL数据库表名
|
||||
id = Column(Integer, primary_key=True # 主键
|
||||
, autoincrement=True # 开启自增,插入数据不需要手动传id,数据库自动生成id
|
||||
,comment="就业信息主键id")
|
||||
student_id = Column(Integer, ForeignKey("student_info_detail.id") # 外键 -> students.id
|
||||
, nullable=False # 不允许为null
|
||||
, nullable=False # 不允许为null,每一条就业记录必须绑定一个学生
|
||||
,comment="关联学生id")
|
||||
employment_status = Column(String(50)
|
||||
, default="not_started"
|
||||
|
||||
@@ -3,3 +3,5 @@ uvicorn==0.40.0
|
||||
SQLAlchemy==2.0.49
|
||||
PyMySQL==1.1.2
|
||||
pydantic==2.13.3
|
||||
openai==2.30.0
|
||||
python-dotenv==1.2.2
|
||||
|
||||
@@ -6,11 +6,11 @@ from datetime import datetime,date # 导入datetime模块下的datetime,da
|
||||
|
||||
# ————定义"创建班级"的"请求体"模型————
|
||||
class ClassCreate( BaseModel ): # "创建"班级信息的请求体模型
|
||||
class_no: str # 班级编号",不可为空
|
||||
class_name: str # 班级名字",不可为空
|
||||
start_date : date|None = None # 班级开课日期",可以为空,默认为空
|
||||
end_date : date|None = None # 班级结课日期",可以为空,默认为空
|
||||
remark : str|None = None # 班级备注",可以为空,默认为空
|
||||
class_no: str # 班级编号,不可为空
|
||||
class_name: str # 班级名字,不可为空
|
||||
start_date : date # 班级开课日期,不可为空
|
||||
end_date : date|None = None # 班级结课日期,可以为空,默认为空
|
||||
remark : str|None = None # 班级备注,可以为空,默认为空
|
||||
|
||||
# ————定义"更新班级"的"请求体"模型————
|
||||
class ClassUpdate( BaseModel ): # "更新"班级信息的请求体模型
|
||||
@@ -25,4 +25,4 @@ class ClassResponse( BaseModel ): # 班级信息的响应体模型
|
||||
code:int = 200 # 状态码,默认200
|
||||
detail:str = '执行成功' # 提示信息
|
||||
total:int = 0 # 数据总条数,默认为0
|
||||
data:str|dict|list|tuple # 返回的数据
|
||||
data:str|dict|list|tuple = '' # 返回的数据,默认为空字符串
|
||||
@@ -5,8 +5,8 @@ from decimal import Decimal
|
||||
|
||||
class EmploymentCreate(BaseModel):
|
||||
"""新增就业信息 请求体 Schema"""
|
||||
student_id: int = Field(..., description="关联学生ID,必填")
|
||||
employment_status: str | None = Field(None, description="就业状态:not_started/job_hunting/offered/employed")
|
||||
student_id: int = Field(..., description="关联学生ID,必填")# description:在Swagger页面展示字段说明文字
|
||||
employment_status: str | None = Field(None, description="就业状态,选填")
|
||||
employment_open_date: date | None = Field(None, description="就业开放时间,选填")
|
||||
offer_date: date | None = Field(None, description="offer下发时间,选填")
|
||||
company_name: str | None = Field(None, max_length=100, description="就业公司名称,选填")
|
||||
|
||||
+16
-14
@@ -1,7 +1,8 @@
|
||||
from pydantic import BaseModel
|
||||
from datetime import date
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from typing import Literal
|
||||
|
||||
#新建学生请求体
|
||||
class StudentCreate(BaseModel):
|
||||
student_no: str | None = Field(default=None, min_length=1, max_length=50)
|
||||
student_name: str = Field(min_length=1, max_length=50)
|
||||
@@ -14,7 +15,7 @@ class StudentCreate(BaseModel):
|
||||
graduation_date: date | None = None
|
||||
education: str | None = Field(default=None, max_length=50)
|
||||
age: int = Field(ge=0, le=150)
|
||||
gender: str = Field(min_length=1, max_length=10)
|
||||
gender: Literal["男", "女"]
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_dates(self):
|
||||
@@ -23,18 +24,19 @@ class StudentCreate(BaseModel):
|
||||
raise ValueError("毕业日期不能早于入学日期")
|
||||
return self
|
||||
|
||||
#更新学生请求体
|
||||
class StudentUpdate(BaseModel):
|
||||
# 全部设为可选,前端只传需要修改的字段
|
||||
student_no: str | None = None
|
||||
student_name: str | None = None
|
||||
class_id: int | None = None
|
||||
consultant_id: int | None = None
|
||||
native_place: str | None = None
|
||||
graduation_school: str | None = None
|
||||
major: str | None = None
|
||||
enrollment_date: date | None = None
|
||||
graduation_date: date | None = None
|
||||
education: str | None = None
|
||||
age: int | None = None
|
||||
gender: str | None = None
|
||||
student_no: str | None = Field(default=None, min_length=1, max_length=50)
|
||||
student_name: str | None = Field(default=None, min_length=1, max_length=50)
|
||||
class_id: int | None = Field(default=None, gt=0)
|
||||
consultant_id: int | None = Field(default=None, gt=0)
|
||||
native_place: str | None = Field(default=None, max_length=100)
|
||||
graduation_school: str | None = Field(default=None, max_length=100)
|
||||
major: str | None = Field(default=None, max_length=100)
|
||||
enrollment_date: date | None = None
|
||||
graduation_date: date | None = None
|
||||
education: str | None = Field(default=None, max_length=50)
|
||||
age: int | None = Field(default=None, ge=0, le=150)
|
||||
gender: Literal["男", "女"] | None = None
|
||||
|
||||
|
||||
Reference in New Issue
Block a user