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

Flask API获取评论失败:request.form空值及KeyError修复

修复Flask API的KeyError问题:JSON与表单数据不匹配

这个问题的根源很明确:你用curl发送的是JSON格式的请求,但你的Flask代码却在尝试从request.form里取数据——这俩完全不兼容!

为什么会报错?

flask.request.form专门用来处理application/x-www-form-urlencoded类型的表单数据(也就是前端form默认提交的格式),而你的curl请求设置了Content-Type: application/json,发送的是JSON字符串,Flask不会把JSON数据放到request.form里,所以request.form是空的,自然会抛出KeyError: 'text'。

两种修复方案,按需选择

方案1:修改curl命令,发送表单格式数据

如果你只是想测试前端表单的提交逻辑,不用改代码,把curl命令改成发送表单格式即可:

curl -ib cookies.txt --request POST --data 'text=Comment sent from curl' http://localhost:8000/api/v1/p/3/comments/

去掉--header 'Content-Type: application/json',用key=value的格式传递数据,这样request.form["text"]就能正常拿到值了。

方案2:修改Flask代码,支持JSON请求(推荐)

如果你的API需要支持JSON格式(现在大多数REST API都这么做),同时还要兼容前端表单提交,修改代码如下:

@app.route('/api/v1/p/<int:postid>/comments/', methods=["POST"])
def add_comment(postid):
    db = model.get_db()
    owner = flask.session["username"]
    
    # 先尝试解析JSON,失败就用表单数据,兼顾两种请求格式
    request_data = flask.request.get_json() or flask.request.form
    
    # 校验text字段是否存在
    if not request_data or 'text' not in request_data:
        return flask.jsonify({"error": "请求缺少'text'字段"}), 400
    
    query = "INSERT INTO comments(commentid, owner, postid, text, created) VALUES(NULL, ?, ?, ?, DATETIME('now'))"
    db.execute(query, (owner, postid, request_data["text"]))
    db.commit()  # 重要!之前的代码没写commit,数据不会真正保存到数据库
    
    last_id = db.execute("SELECT last_insert_rowid()").fetchone()["last_insert_rowid()"]
    get_newest_comment_query = "SELECT * FROM comments WHERE commentid = ?"
    comment = db.execute(get_newest_comment_query, (last_id,)).fetchone()
    
    print('get comment: ', comment)
    return flask.jsonify(comment), 201

这里做了三个关键改进:

  1. 用request.get_json()获取JSON数据,同时用or request.form兼容传统表单提交
  2. 增加了字段校验,避免因为缺少text字段抛出无意义的KeyError
  3. 加上了db.commit(),解决之前代码插入数据后不保存的隐藏问题

这样修改后,你的原curl JSON请求和前端表单提交都能正常工作了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:52:57