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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:45:20  来源:igfitidea点击:

Flask request.args vs request.form

pythonrestcurlpostflask

提问by apardes

My understanding is that request.argsin Flask contains the URL encoded parameters from a GETrequest while request.formcontains POSTdata. What I'm having a hard time grasping is why when sending a POSTrequest, trying to access the data with request.formreturns a 400error but when I try to access it with request.argsit 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 Postmanand curland 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.argsnor request.formwill work.

您正在发布 JSON,既request.args不会也request.form不会工作。

request.formworks only if you POST data with the right content types; form datais either POSTed with the application/x-www-form-urlencodedor multipart/form-dataencodings.

request.form仅当您使用正确的内容类型POST 数据时才有效;表单数据使用application/x-www-form-urlencodedmultipart/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.argsonly 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 请求正文。