Python Flask request.args 与 request.form
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23326368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask request.args vs request.form
提问by apardes
My understanding is that request.args
in Flask contains the URL encoded parameters from a GET
request while request.form
contains POST
data. What I'm having a hard time grasping is why when sending a POST
request, trying to access the data with request.form
returns a 400
error but when I try to access it with request.args
it seems to work fine.
我的理解是request.args
在 Flask 中包含来自GET
请求的 URL 编码参数,而request.form
包含POST
数据。我很难理解为什么在发送POST
请求时,尝试访问数据并request.form
返回400
错误,但是当我尝试访问它时,request.args
它似乎工作正常。
I have tried sending the request with both Postman
and curl
and the results are identical.
我试过用Postman
和发送请求,curl
结果是一样的。
curl -X POST -d {"name":"Joe"} http://127.0.0.1:8080/testpoint --header "Content-Type:application/json"
Code:
代码:
@app.route('/testpoint', methods = ['POST'])
def testpoint():
name = request.args.get('name', '')
return jsonify(name = name)
回答by iurisilvio
Your json data in curl is wrong, so Flask does not parse data to form.
你在 curl 中的 json 数据是错误的,所以 Flask 没有解析数据形成。
Send data like this: '{"name":"Joe"}'
像这样发送数据: '{"name":"Joe"}'
curl -X POST -d '{"name":"Joe"}' http://example.com:8080/testpoint --header "Content-Type:application/json"
回答by Martijn Pieters
You are POST-ing JSON, neither request.args
nor request.form
will work.
您正在发布 JSON,既request.args
不会也request.form
不会工作。
request.form
works only if you POST data with the right content types; form datais either POSTed with the application/x-www-form-urlencoded
or multipart/form-data
encodings.
request.form
仅当您使用正确的内容类型POST 数据时才有效;表单数据使用application/x-www-form-urlencoded
或multipart/form-data
编码发布。
When you use application/json
, you are no longer POSTing form data. Use request.get_json()
to access JSON POST data instead:
当您使用 时application/json
,您不再发布表单数据。使用request.get_json()
访问JSON POST数据,而不是:
@app.route('/testpoint', methods = ['POST'])
def testpoint():
name = request.get_json().get('name', '')
return jsonify(name = name)
As you state, request.args
only ever contains values included in the request query string, the optional part of a URL after the ?
question mark. Since it's part of the URL, it is independent from the POST request body.
正如您所说,request.args
只包含请求查询字符串中包含的值,即?
问号后 URL 的可选部分。由于它是 URL 的一部分,因此它独立于 POST 请求正文。