如何在Flask中获取HTML按钮传递的动态变量?
问题分析与解决办法
核心问题
你的代码没执行打印的原因有两个:
- 表单默认使用
GET方法提交,而Flask代码只在POST请求分支里处理,导致这段逻辑根本没触发 - 日志里的
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提交(更规范的表单处理方式)
- 修改HTML表单,指定
method="POST":
<form method="POST"> <th><Button class="btn btn-dark" name="invoice_no" value="{{ i.invoice_no }}">Select Invoice</Button></th> </form>
- 确保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
相关产品推荐
相关产品推荐

