你无意间发送了错误的Content Type。
默认情况下,
curl的-d标志将发送
content-type的POST数据
application/x-www-form-urlenpred。由于你没有以期望的格式(key = value)发送数据,因此它将完全删除数据。对于JSON数据,你需要发送内容类型设置为
application/json如下的HTTP请求:
curl -XPOST -H "Content-Type: application/json" 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}'另外,flask的
request.form字段仅包含POST表单数据,而不包含其他内容类型。你可以使用
request.data或更方便地使用解析的JSON数据访问原始POST请求主体
request.get_json。
下面是示例的固定版本:
from flask import Flask, requestimport jsonapp = Flask(__name__)@app.route('/', methods=['GET', 'POST'])def refresh(): params = { 'thing1': request.values.get('thing1'), 'thing2': request.get_json().get('thing2') } return json.dumps(params)app.run()更新:我之前打错了
request.body实际上应该是
request.data。事实证明
request.json它已被弃用,
request.get_json现在应改为使用。原始帖子已更新。



