You need to enable JavaScript to run this app. 如何使用Flask实现分步功能演示页面(带查看详情/下一个交互按钮)
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Flask实现分步功能演示页面(带查看详情/下一个交互按钮)

问题排查

你现有代码的核心问题如下:

  • 没有持久化存储当前浏览的示例位置,每次触发请求都会重新初始化示例遍历逻辑,永远只会返回第一个示例
  • 路由函数里的for循环逻辑错误,第一次迭代就会触发return终止函数执行,永远不会进入后续示例的遍历
  • 模板存在语法错误,(% endif %} 属于无效Jinja2语法,正确写法为 {% endif %}
  • 缺少点击Yes后展示的Next按钮对应的交互逻辑
修正实现代码

后端代码(*.py)

from flask import Flask, render_template, request, session, redirect

app = Flask(__name__)
# 必须配置SECRET_KEY才能使用session存储索引
app.config['SECRET_KEY'] = '替换为你自定义的随机字符串'

# 示例列表统一全局定义,不要每次请求都重复初始化
examples = [
    # 格式:[输入内容, 输出内容, 推导过程],可按自己的需求调整结构
    ["第一个示例输入", "第一个示例输出", "第一个示例的推导说明"],
    ["第二个示例输入", "第二个示例输出", "第二个示例的推导说明"],
    # 补充你自己的所有示例即可
]

@app.route('/demo', methods = ["GET", "POST"])
def demo():
    # 初始化当前示例索引,默认从第一个开始
    if 'current_index' not in session:
        session['current_index'] = 0
    
    current_index = session['current_index']
    # 所有示例遍历完成的提示,可自定义跳转逻辑
    if current_index >= len(examples):
        return "所有示例已展示完毕"
    
    answer = False
    extra_info = None

    if request.method == "POST":
        if 'yes' in request.form:
            # 点击Yes,展示推导过程,当前索引不变
            answer = True
            extra_info = examples[current_index][2]
        elif 'no' in request.form or 'next' in request.form:
            # 点击No/Next,索引+1跳转到下一个示例
            session['current_index'] = current_index + 1
            return redirect('/demo')
    
    current_example = {
        "input": examples[current_index][0],
        "output": examples[current_index][1]
    }
    return render_template('demo.html', example=current_example, answer=answer, extra_info=extra_info)

前端模板代码(demo.html)

<!-- 展示当前示例基础内容 -->
<div>
  <p>示例输入:{{ example.input }}</p>
  <p>示例输出:{{ example.output }}</p>
</div>

{% if not answer %}
<!-- 未点击Yes时展示提问和两个选择按钮 -->
<p>Do you want to see how the answer was reached?</p>
<form method="post">
  <input type="submit" name="yes" value="Sure!">
  <input type="submit" name="no" value="No, thanks">
</form>
{% else %}
<!-- 点击Yes后展示推导过程和Next按钮 -->
<div>
  <p>推导过程:{{ extra_info }}</p>
  <form method="post">
    <input type="submit" name="next" value="Next">
  </form>
</div>
{% endif %}
补充说明
  • 示例列表的结构可以根据你自己的实际业务调整,只要对应修改代码中取值的位置即可
  • session自带用户隔离机制,支持多用户同时访问互不干扰
  • 示例全部遍历完成后的逻辑可以自定义,比如重置索引重新开始,或者跳转到其他页面

内容的提问来源于stack exchange,提问作者Ramblin Wreck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 11:51:02