我正在尝试使用 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 许可协议
首先,
.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 produceNone
否则。请参阅 FlaskRequest
文档:您可以告诉
request.get_json()
通过传递force=True
关键字参数来跳过内容类型要求。请注意,如果此时出现 _异常_(可能导致 400 Bad Request 响应),则您的 JSON 数据 无效。它在某种程度上是畸形的;你可能想用 JSON 验证器检查它。