python - 将 JSON 发送到 Flask,request.args 与 request.form

标签 python json rest flask post

我的理解是 Flask 中的 request.args 包含来自 GET 请求的 URL 编码参数,而 request.form 包含 POST 数据。我很难理解的是为什么在发送 POST 请求时,尝试使用 request.form 访问数据会返回 400错误,但是当我尝试使用 request.args 访问它时,它似乎工作正常。

我尝试使用 Postmancurl 发送请求,结果相同。

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.argsrequest.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/

相关文章:

json - 如何查看带有Elastic Search的所有结果的JSON文件?

WCF Restful 帖子

python - 如何使用 MSVC-14.0 为 x64 构建 boost 1_59_0

python - 从 flask 中的文件存储对象中提取文件

python - 正则表达式没有得到所有数字

java - Hibernate 一对多到 JSON 给出 : 500 internal server error

java - Jersey REST 中的 InputStream 只返回一个字节

python gevent : unexpected output in KeyboardInterrupt

javascript - JSON.parse() 对比。 .json()

java.lang.NullPointerException-Android 中的错误