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

如何在Flask中获取HTML按钮传递的动态变量?

问题分析与解决办法

核心问题

你的代码没执行打印的原因有两个:

  1. 表单默认使用GET方法提交,而Flask代码只在POST请求分支里处理,导致这段逻辑根本没触发
  2. 日志里的invoice_no=3是URL查询参数,不是POST表单数据,request.form.get()无法获取GET参数

解决方案

方案1:修改Flask代码处理GET请求

直接从URL查询参数中获取值,适配当前的请求方式:

if request.method == "GET":
    # 从GET查询参数中获取invoice_no
    invoice = request.args.get('invoice_no')
    if invoice:
        print(invoice)
        print("print test")

如果需要同时兼容GET和POST请求,可以这样写:

# 优先取POST表单数据,没有则取GET查询参数
invoice = request.form.get('invoice_no') or request.args.get('invoice_no')
if invoice:
    print(invoice)
    print("print test")

方案2:修改表单为POST提交(更规范的表单处理方式)

  1. 修改HTML表单,指定method="POST":
<form method="POST">
    <th><Button class="btn btn-dark" name="invoice_no" value="{{ i.invoice_no }}">Select Invoice</Button></th>
</form>
  1. 确保Flask路由允许POST方法,在路由装饰器中添加methods=['GET', 'POST']:
@app.route('/transactions', methods=['GET', 'POST'])
def transactions():
    if request.method == "POST":
        invoice = request.form.get('invoice_no')
        if invoice:
            print(invoice)
            print("print test")
    # 其他页面渲染逻辑
    return render_template('your_template.html', ...)

额外注意

如果使用POST请求,生产环境建议开启Flask的CSRF保护(比如通过Flask-WTF扩展),避免安全问题。测试环境可以暂时忽略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:57:32