Flask测验项目跳转异常:点击按钮跳转至/result而非/test求助
Flask测验网站页面跳转异常修复方案
问题根源
- 起始页面表单直接提交到
/test,导致test函数接收到无答案数据的POST请求,触发错误的答案保存逻辑,进而因查询不到下一题直接跳转到结果页。 index函数重定向时错误指定_method='POST',导致进入test的POST分支而非显示题目的GET分支。check_answer函数中参数传递格式错误,导致数据库查询失败。save_answers函数未检查请求参数是否存在,无数据时会将session['last_question']设为None,引发后续查询异常。
修复步骤
1. 修正start.html表单提交目标
将表单提交到index路由,让index处理测验选择逻辑:
<!-- start.html 中form标签修改 --> <form method="post" action="{{ url_for('index') }}">
2. 修正index函数的重定向逻辑
去掉_method='POST',直接重定向到test的GET请求,确保进入显示题目的分支:
# quiz.py中index函数的POST分支修改 def index(): if request.method == 'GET': start_quiz(-1) return quiz_form() else: quest_id = request.form.get('quiz') start_quiz(quest_id) return redirect(url_for('test')) # 移除_method='POST'
3. 修复save_answers函数的参数检查
添加参数存在性判断,避免无数据时修改session:
# quiz.py中save_answers函数修改 def save_answers(): answer = request.form.get('ans_text') quest_id = request.form.get('q_id') # 仅当参数存在时才执行保存逻辑 if answer and quest_id: session['last_question'] = quest_id session['total'] += 1 if check_answer(quest_id, answer): session['answers'] += 1
4. 修复check_answer函数的参数传递
将字符串参数改为列表格式,符合sqlite3的参数传递要求:
# db_scripts.py中check_answer函数修改 def check_answer(q_id, ans_text): query = ''' SELECT question.answer FROM quiz_content, question WHERE quiz_content.id = ? AND quiz_content.question_id = question.id ''' open() cursor.execute(query, [q_id]) # 改为列表格式,替代原str(q_id) result = cursor.fetchone() close() if result is None: return False else: return result[0] == ans_text
验证修复
完成上述修改后:
- 选择测验提交后,会通过
index初始化session,然后跳转到/test显示第一个题目 - 提交答案时,
test的POST分支会正确保存答案并加载下一题 - 所有题目完成后才会跳转到结果页
内容的提问来源于stack exchange,提问作者Nurdaulet Bolatov
相关产品推荐
相关产品推荐

