繁体   English   中英

无法从 flask api 获得评论

[英]Fail to get comment from flask api

在尝试获取添加的评论的文本时,我在 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

您的 HTML 表单配置不正确。

  1. 您正在发送 GET 请求,而您的 flask 仅接受 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 ,因此可以将游览 curl 简化如下:

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

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

添加到@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读取请求数据

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM