如何在 Flask 中获取 POSTed JSON?

新手上路,请多包涵

我正在尝试使用 Flask 构建一个简单的 API,我现在想在其中读取一些 POSTed JSON。我使用 Postman Chrome 扩展程序执行 POST,我 POST 的 JSON 很简单 {"text":"lalala"} 。我尝试使用以下方法读取 JSON:

 @app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    print content
    return uuid

在浏览器上,它正确返回我放入 GET 中的 UUID,但在控制台上,它只打印出 None (我希望它打印出 {"text":"lalala"} 。有人知道吗如何从 Flask 方法中获取发布的 JSON?

原文由 kramer65 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 424
2 个回答

首先, .json 属性是委托给 request.get_json() 方法 的属性,它记录了为什么你在这里看到 None

You need to set the request content type to application/json for the .json property and .get_json() method (with no arguments) to work as either will produce None 否则。请参阅 Flask Request 文档

如果 mimetype 指示 JSON( application/json ,请参阅 is_json() ),这将包含解析的 JSON 数据,否则它将是 None

您可以告诉 request.get_json() 通过传递 force=True 关键字参数来跳过内容类型要求。

请注意,如果此时出现 _异常_(可能导致 400 Bad Request 响应),则您的 JSON 数据 无效。它在某种程度上是畸形的;你可能想用 JSON 验证器检查它。

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 4.0 许可协议

作为参考,以下是如何从 Python 客户端发送 json 的完整代码:

 import requests
res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"})
if res.ok:
    print(res.json())

“json=”输入将自动设置内容类型,如此处所述: How to POST JSON data with Python Requests?

上面的客户端将使用此服务器端代码:

 from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    print(content['mytext'])
    return jsonify({"uuid":uuid})

if __name__ == '__main__':
    app.run(host= '0.0.0.0',debug=True)

原文由 Luke 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题