From 50c511d825c89b331e28076e8fc9f0ef43e4e28c Mon Sep 17 00:00:00 2001 From: yuliang_guo Date: Sat, 31 Jan 2026 11:20:09 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E8=80=83=E8=AF=95API?= =?UTF-8?q?=E7=9A=84SQLAlchemy=E6=87=92=E5=8A=A0=E8=BD=BD=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在访问current_user属性前先提取到局部变量,避免MissingGreenlet错误 --- backend/app/api/v1/exam.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/backend/app/api/v1/exam.py b/backend/app/api/v1/exam.py index 18b3f9c..dd17673 100644 --- a/backend/app/api/v1/exam.py +++ b/backend/app/api/v1/exam.py @@ -62,9 +62,13 @@ async def start_exam( current_user: User = Depends(get_current_user), ): """开始考试""" + # 先提取用户信息,避免后续懒加载问题 + user_id = current_user.id + username = current_user.username + exam = await ExamService.start_exam( db=db, - user_id=current_user.id, + user_id=user_id, course_id=request.course_id, question_count=request.count, ) @@ -82,9 +86,9 @@ async def start_exam( SystemLogCreate( level="INFO", type="api", - message=f"用户 {current_user.username} 开始考试(课程ID: {request.course_id})", - user_id=current_user.id, - user=current_user.username, + message=f"用户 {username} 开始考试(课程ID: {request.course_id})", + user_id=user_id, + user=username, ip=http_request.client.host if http_request.client else None, path="/api/v1/exams/start", method="POST", @@ -103,8 +107,12 @@ async def submit_exam( current_user: User = Depends(get_current_user), ): """提交考试答案""" + # 先提取用户信息,避免后续懒加载问题 + user_id = current_user.id + username = current_user.username + result = await ExamService.submit_exam( - db=db, user_id=current_user.id, exam_id=request.exam_id, answers=request.answers + db=db, user_id=user_id, exam_id=request.exam_id, answers=request.answers ) # 获取考试记录以获取course_id @@ -126,9 +134,9 @@ async def submit_exam( SystemLogCreate( level="INFO", type="api", - message=f"用户 {current_user.username} 提交考试(考试ID: {request.exam_id},得分: {result.get('score', 0)})", - user_id=current_user.id, - user=current_user.username, + message=f"用户 {username} 提交考试(考试ID: {request.exam_id},得分: {result.get('score', 0)})", + user_id=user_id, + user=username, ip=http_request.client.host if http_request.client else None, path="/api/v1/exams/submit", method="POST",