我的理解是 Flask 中的 request.args
包含来自 GET
请求的 URL 编码参数,而 request.form
包含 POST
数据。我很难理解的是为什么在发送 POST
请求时,尝试使用 request.form
访问数据会返回 400
错误,但是当我尝试使用 request.args
访问它时,它似乎工作正常。
我尝试使用 Postman
和 curl
发送请求,结果相同。
curl -X POST -d {"name":"Joe"} http://127.0.0.1:8080/testpoint --header "Content-Type:application/json"
代码:
@app.route('/testpoint', methods = ['POST'])
def testpoint():
name = request.args.get('name', '')
return jsonify(name = name)
最佳答案
您正在发布 JSON,request.args
和 request.form
都不起作用。
request.form
仅在您使用正确的内容类型发布数据时才起作用; 表单数据 使用 application/x-www-form-urlencoded
or multipart/form-data
发布编码。
当您使用 application/json
时,您不再是 POST 表单数据。使用request.get_json()
改为访问 JSON POST 数据:
@app.route('/testpoint', methods = ['POST'])
def testpoint():
name = request.get_json().get('name', '')
return jsonify(name = name)
正如您所说,request.args
只包含请求查询字符串中包含的值,即 ?
问号之后的 URL 的可选部分。由于它是 URL 的一部分,因此它独立于 POST 请求正文。
关于python - 将 JSON 发送到 Flask,request.args 与 request.form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23326368/