这是烧瓶代码:
from flask import Flask, request
import json
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def refresh():
params = {
'thing1': request.values.get('thing1'),
'thing2': request.values.get('thing2')
}
return json.dumps(params)
这是cURL
:
$ curl -XGET 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}'
> {"thing1": "1", "thing2": null}
$ curl -XGET 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}'
> {"thing1": "1", "thing2": null}
The docs http://flask.pocoo.org/docs/0.12/api/#incoming-request-data看起来非常清楚这应该有效:
form
包含来自 POST 或 PUT 请求的已解析表单数据的 MultiDict。
请记住,文件上传不会在这里结束,但是
相反,在文件属性中。
args
包含查询字符串解析内容的 MultiDict。 (这
URL 中问号后面的部分)。
values
具有 form 和 args 内容的 CombinedMultiDict。
有什么想法我做错了吗?
更新:尝试其中一个答案的建议,替换掉return
line:
Using return json.dumps(json.load(request.body.decode("utf-8") ))
产生错误AttributeError: 'Request' object has no attribute 'body'
Using return json.dumps(json.load(request.json))
产生错误AttributeError: 'NoneType' object has no attribute 'read'
Using POST
使用原始代码似乎没有效果:
$ curl -XPOST 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}'
{"thing1": "1", "thing2": null}
设置内容类型并使用POST
用原来的代码也没有明显效果:
$ curl -XPOST -H "Content-Type: application/json" 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}'
{"thing1": "1", "thing2": null}
尽管我去验证了内容类型是否已正确设置:
...
print(request.headers)
...
Host: 127.0.0.1:5000
User-Agent: curl/7.54.0
Accept: */*
Content-Type: application/json
Content-Length: 12