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

Flask同视图处理GET/POST时如何传递表单提交的参数值?

问题根因
  • 你的表单method属性设置为GET,点击提交默认只会触发GET请求,不会进入POST分支。如果你是通过其他入口触发的POST请求,没有主动携带stage参数的话自然无法取值。
  • 你当前代码仅从request.args(URL查询参数)取值,POST请求的表单格式参数存在request.form中,JSON格式参数存在request.json中,这两种场景下request.args都无法拿到参数。
解决方案

方案1:调整表单提交方式为POST(推荐)

直接修改表单的提交方式,同时兼容多场景参数取值即可:

修改后表单代码

<form method="POST" action="{{ url_for('model3') }}">
    <div> Choose a Model:
        <select class="form-select" aria-label="Default select example" name="stage">
          <option value="Post Flowering" {% if thing=='Post Flowering' %} selected {% endif %}>Post Flowering</option>
          <option value="Filling" {% if thing=='Filling' %} selected {% endif %}>Filling</option>
          <option value="Filling Ripening" {% if thing=='Filling Ripening' %} selected {% endif %} >Filling-Ripening</option>
          <option value="Ripening" {% if thing=='Ripening' %} selected {% endif %}>Ripening</option>
        </select>
        <input type="submit" value="Submit">
    </div>
</form>

修改后路由代码

@app.route('/WheatDetect', methods=['POST', 'GET'])
def model3():
    # 兼容GET参数、POST表单参数、POST JSON参数三种场景
    stage = request.args.get('stage') 
    if not stage and request.method == 'POST':
        stage = request.form.get('stage')
        if not stage and request.is_json:
            stage = request.get_json().get('stage')
    print("stage in get-->", stage if request.method == 'GET' else '非GET请求不打印')
    if request.method == 'POST':
        print("stage in post-->", stage)
        # 此处填写你的POST业务逻辑

方案2:保留原表单GET提交逻辑,跨请求共享参数

如果你需要保留表单用GET提交的逻辑,后续POST请求要复用之前选择的stage值,可以用session存储参数:

from flask import session

# 配置session密钥,必须配置否则session无法使用
app.secret_key = '自定义任意字符串作为密钥'

@app.route('/WheatDetect', methods=['POST', 'GET'])
def model3():
    stage = request.args.get('stage')
    # GET请求拿到参数就存入session
    if stage:
        session['stage'] = stage
    print("stage in get-->",stage)
    if request.method == 'POST':
        # POST请求优先从session取值
        stage = session.get('stage')
        print("stage in post-->", stage)
        # 此处填写你的POST业务逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:18:00