From e1d10605c954f1c0f3f16443ac3d65ff5164f932 Mon Sep 17 00:00:00 2001 From: yuliang_guo Date: Sat, 31 Jan 2026 11:21:39 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20ExamService.start=5Fexam=E8=BF=94?= =?UTF-8?q?=E5=9B=9EID=E9=81=BF=E5=85=8D=E6=87=92=E5=8A=A0=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改start_exam返回exam.id而不是整个Exam对象, 彻底避免SQLAlchemy异步会话的懒加载问题 --- backend/app/api/v1/exam.py | 4 ++-- backend/app/services/exam_service.py | 10 ++++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/backend/app/api/v1/exam.py b/backend/app/api/v1/exam.py index dd17673..442b6d3 100644 --- a/backend/app/api/v1/exam.py +++ b/backend/app/api/v1/exam.py @@ -66,7 +66,7 @@ async def start_exam( user_id = current_user.id username = current_user.username - exam = await ExamService.start_exam( + exam_id = await ExamService.start_exam( db=db, user_id=user_id, course_id=request.course_id, @@ -96,7 +96,7 @@ async def start_exam( ) ) - return ResponseModel(code=200, data=StartExamResponse(exam_id=exam.id), message="考试开始") + return ResponseModel(code=200, data=StartExamResponse(exam_id=exam_id), message="考试开始") @router.post("/submit", response_model=ResponseModel[SubmitExamResponse]) diff --git a/backend/app/services/exam_service.py b/backend/app/services/exam_service.py index e682cf8..53a783e 100644 --- a/backend/app/services/exam_service.py +++ b/backend/app/services/exam_service.py @@ -20,7 +20,7 @@ class ExamService: @staticmethod async def start_exam( db: AsyncSession, user_id: int, course_id: int, question_count: int = 10 - ) -> Exam: + ) -> int: """ 开始考试 @@ -31,7 +31,7 @@ class ExamService: question_count: 题目数量 Returns: - Exam: 考试实例 + int: 考试ID """ # 检查课程是否存在 course = await db.get(Course, course_id) @@ -93,8 +93,10 @@ class ExamService: db.add(exam) await db.commit() await db.refresh(exam) - - return exam + + # 返回exam.id而不是整个对象,避免懒加载问题 + exam_id = exam.id + return exam_id @staticmethod async def submit_exam(