Flask加载页跳转问题求助:提交表单后无法跳转至结果页
Flask加载页面自动跳转问题解决办法
核心问题
你当前代码的致命错误是:在process_form函数开头就执行了return render_template('loading_page.html'),函数遇到return语句会直接终止,后面启动绘图线程、返回结果页的代码完全没机会运行,自然没法跳转到results.html。
解决方案步骤
要实现“加载页显示→后台绘图→自动跳转结果页”的流程,需要结合后端线程处理任务+前端轮询检查状态:
- 移除提前的return,让后端启动绘图线程后返回加载页
- 后端新增一个接口,供前端查询绘图任务是否完成
- 加载页用JavaScript定时轮询状态接口,任务完成后自动跳转
修改后的完整代码
1. app.py 修改
from flask import Flask, render_template, request, jsonify import threading import time import matplotlib.pyplot as plt app = Flask(__name__) # 用全局变量存储任务状态(仅适合单用户测试,多用户需改用数据库/缓存) task_status = {'completed': False} @app.route('/') def home(): return render_template('home.html') @app.route('/process_form', methods=['POST']) def process_form(): key_pressed = request.form['key_pressed'] # 重置任务状态 task_status['completed'] = False task_status['key'] = key_pressed def generate_plot(): # 模拟耗时任务 time.sleep(3) # 生成绘图 x1 = [1, 2, 3, 4, 5] y1 = [2, 4, 6, 8, 10] plt.plot(x1, y1) plt.xlabel('X-as') plt.ylabel('Y-as') plt.title(f'Gegenereerde plot voor {key_pressed}') plt.savefig('static/plot.png') plt.close() # 关闭绘图释放资源 # 标记任务完成 task_status['completed'] = True # 启动后台线程执行绘图 thread = threading.Thread(target=generate_plot) thread.start() # 返回加载页 return render_template('loading_page.html') @app.route('/check_status') def check_status(): return jsonify(task_status) @app.route('/results') def results(): key_pressed = task_status.get('key', '') return render_template('results.html', key_pressed=key_pressed) if __name__ == '__main__': app.run(debug=True)
2. loading_page.html 编写
<!DOCTYPE html> <html> <head> <title>Loading...</title> <script> // 每隔1秒检查一次任务状态 const checkInterval = setInterval(() => { fetch('/check_status') .then(response => response.json()) .then(data => { if (data.completed) { // 任务完成,跳转到结果页 clearInterval(checkInterval); window.location.href = '/results'; } }); }, 1000); </script> </head> <body> <h1>Bezig met genereren van de plot...</h1> <p>Even geduld aub, dit duurt enkele seconden.</p> </body> </html>
3. results.html 编写
<!DOCTYPE html> <html> <head> <title>Resultaten</title> </head> <body> <h1>Resultaat voor key: {{ key_pressed }}</h1> <img src="{{ url_for('static', filename='plot.png') }}" alt="Gegenereerde plot"> </body> </html>
关键说明
- 全局变量
task_status仅适合本地测试,若要部署到多用户环境,建议改用数据库(如SQLite)或Redis来存储任务状态 - 绘图后必须调用
plt.close(),避免Matplotlib内存泄漏 - 前端轮询的间隔可以根据实际任务耗时调整,比如改成2000毫秒(2秒)
内容的提问来源于stack exchange,提问作者Datafan
相关产品推荐
相关产品推荐

