【问题标题】:Flask request as json [duplicate]烧瓶请求作为json [重复]
【发布时间】:2021-06-07 11:53:30
【问题描述】:

我有 1 个小程序。我正在通过 CURL X POST 发送 json 请求,应该会得到答案。 客户端代码是:

curl -XPOST -d'{"animal":"cow", "sound":"moooo", "count": "3"}' 192.168.88.88:5000/test

服务器代码是:

import json
from flask import Flask, request, jsonify

app = Flask(__name)

@app.route("/test", methods=['POST'])
def json_example():
  content = request.get_json(silent=True)
  animal = content["animal"]
  sound = content["sound"]
  count = str(content["count"])
  i=0
  res=''
  while i<int(count):
    temp = animal + "says " + sound +"\n"
    res = temp +res
    i = i + 1
  return res

app.run(host='0.0.0.0', port = 5000)

如果我在邮递员处运行请求并指示这是 json 类型 - 那么一切正常,但如果我通过 curl 运行它 - 有错误(无类型对象不可下标) 请建议,如何更正服务器上的代码并指出所有响应都是 json 类型。

谢谢

【问题讨论】:

  • request.get_json(...) 为您的情况返回 None。您应该在致电get_json() 之前询问if request.is_json。

标签: python json python-3.x flask


【解决方案1】:

您必须在 curl 请求中指定 -H "Content-Type: application/json"。或者,如果您没有为请求指定标头类型,您可以使用request.form.values:

curl -H "Content-Type: application/json"  -XPOST -d'{"animal":"cow", "sound":"moooo", "count": "3"}' 192.168.88.88:5000/test

对于您的curl 请求,request.mimetype 给出的mimetype 是'application/x-www-form-urlencoded'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-24
    • 2016-04-21
    • 2014-07-23
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    相关资源
    最近更新 更多