无法从烧瓶api获得评论

问题描述 投票:1回答:2

[尝试获取添加的注释的文本时,我使用以下curl命令在flask.request.form中得到了关键错误。我尝试打印出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'

我的评论obj:

  <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
python html rest flask
2个回答
0
投票

[添加到@Harshal的答案中,使用curl时,您好像访问了错误的请求数据。由于请求的内容类型设置为application/json,因此您需要使用flask.request.json-more details

访问请求数据

或者您可以如下更新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读取请求数据>


0
投票

您的HTML表单未正确配置。

© www.soinside.com 2019 - 2024. All rights reserved.