在Flask中发布json时出现“400错误请求”

r1zk6ea1  于 2022-12-20  发布在  其他
关注(0)|答案(3)|浏览(347)

我的申请很简单,

#@csrt.exempt
@app.route('/preorders/json', methods=['POST'])
def json_create_preorders():
    #print request
    print 'test'
    #print request.json
    print request.mimetype
    print request.json
    print 'aaa',request.get_json(force=True)
    print request.json['product_id']
    if not request.json or not 'product_id' in request.json or not 'customer_name' in request.json or not 'customer_phone' in request.json:
        abort(400)
    preorder=Preorder(request.json['customer_name'],request.json['customer_phone'],request.json['product_id'])
    db.session.add(preorder)
    db.session.commit()
    return jsonify({'status':'success'}), 201

使用curl发布json,

curl -i -H "Content-Type: application/json" -X POST -d '{"product_id":"111", "customer_name"="xiaokun", "customer_phone"="1231"}' http://xxxx/preorders/json

从服务器检查,'test'和'request.mimetype'被打印出来。然后是一个400响应。有人能帮忙看一下吗?

nkoocmlb

nkoocmlb1#

试试这个

-d '{"product_id":"111", "customer_name":"xiaokun", "customer_phone":"1231"}'
    • 完整语法**
curl -X POST -H "application/json" -d '{"key":"val"}' URL
r9f1avp5

r9f1avp52#

如果你是windows系统,你需要修改json格式。

示例:'{"token":"asdfas"}'替换为"{\"Hello\":\"Karl\"}"

hof1towb

hof1towb3#

现在回答可能已经太晚了,但是我不得不说Flask的json检查非常严格!
以下是我的数据:

{
  "id":1,
  "name":"test1",
  "attr2":"data2",
}

它可以在所有的json验证器中传递,但是Flask认为它是无效的,并给予一个令人费解的BAD REQUEST 400响应。
“错误”是最后一个逗号!一切正常,当我把它改为:

{
  "id":1,
  "name":"test1",
  "attr2":"data2"
}

相关问题