You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask路由跳转异常:Stay与Deal按钮均跳转至deal路由

问题原因与修复方案

核心问题

你的代码中存在两个独立的if request.method == "POST"判断块,当表单以POST方式提交时:

  • 若第一个块未匹配到Stay按钮的提交,会继续执行第二个POST判断块;
  • 若前端表单存在参数提交异常(比如点击Stay时同时携带了Deal参数),也会导致逻辑走偏,最终两个操作都跳转到deal路由。

同时需要确认前端按钮的name属性是否与后端判断一致:触发"Stay"的按钮name必须是Stay,触发"Deal"的按钮name必须是Deal。

修复后的代码

将两个POST请求的判断合并到同一个if块中,用elif区分不同按钮操作,避免重复判断请求方法:

@app.route('/', methods=['POST', 'GET'])
def home():
    if request.method == "POST":
        # 判断是否点击Stay按钮
        if request.form.get("Stay"):
            return redirect(url_for('home'))
        # 判断是否点击Deal按钮
        elif request.form.get("Deal"):
            return redirect(url_for('deal'))
    # GET请求或未匹配到按钮时渲染首页
    return render_template("index.html", year=year)


@app.route('/deal', methods=['POST'])
def deal():
    if len(main.player_hand) == 0:
        main.start()
        main.get_current_score(main.player_hand)
        return render_template("index.html", year=year, player=main.player_hand, dealer=main.dealer_hand[1:],
                               score_d=main.get_dealer_starting_value(main.dealer_hand),
                               score_p=main.get_current_score(main.player_hand))

额外检查项

确保前端表单按钮的name属性设置正确,示例代码:

<form method="POST" action="/">
    <button type="submit" name="Stay">Stay</button>
    <button type="submit" name="Deal">Deal</button>
</form>

若通过JS提交表单,需保证只携带对应按钮的参数,避免同时提交两个按钮的标识。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:56:06