无法从烧瓶 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


SMILET
浏览 223回答 2
2回答

慕少森

添加到@Harshal 的答案中,使用 curl 时,您似乎在错误地访问请求数据。由于请求的 Content-Type 设置为application/json,因此您需要使用flask.request.json-更多详细信息来访问请求数据或者您可以curl像下面这样更新命令,curl&nbsp;-ib&nbsp;cookies.txt&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;--request&nbsp;POST&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;--data-urlencode&nbsp;"text=Comment&nbsp;sent&nbsp;from&nbsp;curl"&nbsp;&nbsp; &nbsp;&nbsp;http://localhost:8000/api/v1/p/3/comments/在这种情况下,curl 将自动使用Content-Type application/x-www-form-urlencoded,您的应用程序将能够使用flask.request.form

翻翻过去那场雪

您的 HTML 表单配置不正确。您正在发送一个 GET 请求,而您的烧瓶只接受 POST。flask.request.form["text"]要求输入名为 text 的输入,但您的文本框没有任何名称。没有提交按钮。您可以通过以下方式修复它:<form id="comment-form" method="post">&nbsp; &nbsp; <input type="text" value="" name="text" />&nbsp; &nbsp; <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/希望这可以帮助。祝你好运。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python