flask:request.json始终不返回任何值,尽管发送了有效的json

2024-10-03 09:20:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在服务器端有这个代码

from flask import Flask, request, jsonify

app=Flask(__name__)

@app.route("/pingtest")
def pingtest():
    return "Pong!"

@app.route("/registrar_alumno", methods=["POST"])
def registrar_alumno():
    print(request.json)
    return jsonify(request.json)

app.run(debug=True,port=4000)

在客户机上我有这个代码

import requests

r=requests.post("http://127.0.0.1:4000/registrar_alumno",
    data={"test":"hello there"})
print(r.text)

我希望在两侧获得{“test”:“hello there”},但我在服务器上有这样一个:

(asistencias) PS C:\Users\Alumno\Desktop\Proyectos\py\gestion_academica\asistencias> python .\server.py [...] (irrelevants messages that server always shows)

None #...(this should be print(request.json) instruction)

127.0.0.1 - - [15/Mar/2020 16:22:45] "←[37mPOST /registrar_alumno HTTP/1.1←[0m" 200 -

这个在客户机上

(asistencias) PS C:\Users\Alumno\Desktop\Proyectos\py\gestion_academica\asistencias> python .\testclient.py

None

我不知道这是怎么回事,我希望有人能帮我找到错误


Tags: 代码pyimportjsonappflaskrequestdef
1条回答
网友
1楼 · 发布于 2024-10-03 09:20:27

之所以会发生这种情况,是因为在客户端请求中使用了data参数和字典,该字典发送表单编码数据,导致request.json返回None

使用json参数发送JSON:

import requests

r=requests.post("http://127.0.0.1:4000/registrar_alumno", json={"test":"hello there"})

这将把数据序列化为JSON,并将Content-Type头更改为application/json

请参阅more complicated POST requests上的请求文档

相关问题 更多 >