Flask表单无法获取输入文本:打字测速应用故障排查求助
解决Flask无法获取输入框内容的问题
问题根源
你的HTML代码把「开始按钮」「输入框」「停止按钮」分别放在了三个独立的<form>标签里。当点击Stop按钮提交表单时,只有该表单内的按钮数据会被发送到后端,输入框所在的表单并没有被提交,因此Flask的request.form中无法获取到users_text的值,最终导致user_text为None,执行split()时触发NoneType错误。
解决方案
1. 修复HTML表单结构
将所有交互元素(开始按钮、输入框、停止按钮)放入同一个<form>中,这样点击任意按钮提交时,输入框的内容会一同被发送到后端。
修改后的HTML代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="../static/style.css"> </head> <body> <h1>Test Out Your Typing Speed</h1> <div class="box"> <h3 id="instructions">Press the Start Button and then type in the field below. Then, press the Stop Button. </h3> </div> <div class="box"> <form method="post" action="/"> <button type="submit" id="Start_Button" name="button" value="Start_Button">Start</button> <div class="box"> <input type="text" id="user_type_box" name="users_text" placeholder="Type here"> </div> <div class="box"> <button type="submit" id="Stop_Button" name="button" value="Stop_Button">Stop</button> </div> </form> </div> <h3>Typing Speed: {{speed}}</h3> <h3>Accuracy: {{accuracy}}</h3> </html>
2. 修复Python代码的潜在问题
除了表单问题,原代码还有几个需要优化的点:未初始化t0、未处理输入为空的情况、字符比较时可能出现索引越界。
修改后的Python代码:
from flask import Flask, request, render_template import time app = Flask(__name__) test_text = "Hello. The year is 2024." speed = 0 accuracy = 0 t0 = 0 # 初始化计时起始值 @app.route('/', methods =["GET", "POST"]) def home(): global t0, speed, accuracy if request.method == "POST": if request.form['button'] == 'Start_Button': t0 = time.time() # 开始计时时重置结果 speed = 0 accuracy = 0 elif request.form['button'] == 'Stop_Button': if t0 == 0: # 防止未点击开始就触发停止 speed = 0 accuracy = 0 else: t = time.time() - t0 # 兜底处理输入为空的情况,去除首尾空格 user_text = request.form.get('users_text', '').strip() if user_text: word_count = len(user_text.split()) # 保留两位小数,让结果更直观 speed = round(word_count / t, 2) # 取两个文本的最短长度比较,避免索引越界 min_length = min(len(user_text), len(test_text)) correct_chars = 0 for i in range(min_length): if test_text[i] == user_text[i]: correct_chars += 1 accuracy = round(100 * (correct_chars / len(user_text)), 2) else: speed = 0 accuracy = 0 return render_template('index.html', speed=speed, accuracy=accuracy) if __name__ == "__main__": app.run(debug=True)
关键修改说明
- 合并表单后,点击Stop按钮时输入框内容会被正常提交,Flask可以通过
request.form.get('users_text')获取到值 - 增加
t0初始化和判断,避免未开始计时就计算结果的错误 - 处理输入为空的情况,防止
split()和除法运算报错 - 字符比较时取最短文本长度,避免索引越界
- 对速度和准确率做四舍五入,提升显示友好度
内容的提问来源于stack exchange,提问作者Seeingstars
相关产品推荐
相关产品推荐

