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

使用Flask将HTML表单数据传递至Python时遇问题求排查

Flask表单数据传递问题的修复方案

我帮你梳理下代码里的几个核心问题,咱们一步步把它改好:

问题点拆解

  • 表单提交地址错误:你的HTML表单里action="smssend.py"是不对的——Flask是通过路由来处理请求的,应该把action指向你定义的/form路由,这样提交表单时才会触发对应的Flask视图函数。
  • GET请求直接读取表单会报错:你的/form路由同时支持GET和POST方法,但GET请求是没有表单数据的,直接request.form['your_name']会抛出KeyError异常。必须先判断请求方法是POST时,再读取表单数据。
  • 视图函数缺少返回值:你的form()函数没有return任何内容,处理完请求后Flask不知道要返回什么,会触发500内部服务器错误。

修正后的代码

Python代码

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

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('home.html')

@app.route('/form', methods=['GET', 'POST'])
def form():
    # 仅在POST请求时处理表单数据
    if request.method == 'POST':
        your_name = request.form['your_name']
        customer_number = request.form['customer_number']
        msg = request.form['msg']
        
        # 这里可以添加你的短信发送逻辑
        print(f"收到表单数据:姓名{your_name},客户号码{customer_number},消息内容:{msg}")
        
        # 处理完成后重定向到首页,避免刷新页面重复提交
        return redirect(url_for('index'))
    # GET请求时返回表单页面(你的表单在home.html里,所以直接渲染它)
    return render_template('home.html')

if __name__ == '__main__':
    app.run(debug=True)  # 开启debug模式,开发时能看到详细错误信息

HTML表单代码

<form action="/form" method="post">
    <label for="msg">Message</label>
    <textarea id="msg" name="msg" rows="5" cols="50">
    </textarea>
    <br>
    <label for="your_name">Your Name:</label>
    <input type="text" name="your_name" id="your_name" required />
    <br>
    <label for="customer_number">Customers Number:</label>
    <input type="text" name="customer_number" id="customer_number" required />
    <br>
    <input type="submit">
</form>

额外优化说明

  • 加了debug=True,开发时出错能看到详细的错误堆栈,方便排查问题。
  • 表单里加了required属性,让浏览器先做简单的非空验证(后端也可以再加一层验证逻辑更安全)。
  • 处理完POST请求后用redirect重定向,避免用户刷新页面时重复提交表单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:17:22