为了账号安全,请及时绑定邮箱和手机立即绑定

无法从烧瓶 api 获得评论

无法从烧瓶 api 获得评论

SMILET 2022-06-28 10:57:56
尝试获取添加评论的文本时,我在 flask.request.form 中使用以下 curl 命令获取关键错误。我尝试打印出 flask.request.form 但它是空的。如何解决?curl 命令添加新评论:curl -ib cookies.txt   --header 'Content-Type: application/json'   --request POST   --data '{"text":"Comment sent from curl"}'  http://localhost:8000/api/v1/p/3/comments/错误:werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.KeyError: 'text'我的评论对象:  <form id="comment-form">  <input type="text" value=""/>  </form>我的 flask.api python 文件将返回新的评论字典:@app.route('/api/v1/p/<int:postid>/comments/', methods=["POST"])def add_comment(postid):     db = model.get_db()    owner = flask.session["username"]    query = "INSERT INTO comments(commentid, owner, postid, text, created) VALUES(NULL, ?, ?, ?, DATETIME('now'))"    db.execute(query, (owner, postid, flask.request.form["text"]))    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
查看完整描述

2 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

添加到@Harshal 的答案中,使用 curl 时,您似乎在错误地访问请求数据。由于请求的 Content-Type 设置为application/json,因此您需要使用flask.request.json-更多详细信息来访问请求数据

或者您可以curl像下面这样更新命令,

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

在这种情况下,curl 将自动使用Content-Type application/x-www-form-urlencoded,您的应用程序将能够使用flask.request.form


查看完整回答
反对 回复 2022-06-28
?
翻翻过去那场雪

TA贡献2065条经验 获得超14个赞

您的 HTML 表单配置不正确。

  1. 您正在发送一个 GET 请求,而您的烧瓶只接受 POST。

  2. flask.request.form["text"]要求输入名为 text 的输入,但您的文本框没有任何名称。

  3. 没有提交按钮。

您可以通过以下方式修复它:

<form id="comment-form" method="post">

    <input type="text" value="" name="text" />

    <input type="submit" />

</form>

如果您了解更多有关响应代码的信息,您可能会更容易调试:https ://developer.mozilla.org/en-US/docs/Web/HTTP/Status 。


由于您正在使用request.form,因此可以像这样简化 tour curl:


curl --form "text=some_text_here" http://localhost:8000/api/v1/p/3/comments/

希望这可以帮助。祝你好运。


查看完整回答
反对 回复 2022-06-28
  • 2 回答
  • 0 关注
  • 222 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号