从bash到GO服务器的REST后查询工作,但对于Python失败



我有一个go server,它对接收到的json进行解组。当我使用curl时,它可以工作,但在python的情况下失败。

Go服务器解组代码:

type Data struct {
Namespace   string `json:"namespace"`
ContainerId string `json:"containerId"`
}
func notify(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var data Data
err := decoder.Decode(&data)
if err != nil {
glog.Errorf("Failed to decode the request json %s n", err.Error())
return
}
...
}

如果我做卷曲命令,它可以毫无怨言地工作:

curl -i -H "Accept: application/json" -H "Content-Type:application/json" -X POST --data '{"namespace": "default", "containerId": "2f7c58d399f2dc35fa1be2abea19301c8e74973ddd72f55a778babf01db5ac26"}' http://mysvc:8080/notify

但如果我对Python做同样的事情,它会抱怨:

jsonPrep['containerId'] = "2f7c58d399f2dc35fa1be2abea19301c8e74973ddd72f55a778babf01db5ac26"
jsonPrep['namespace'] = "default" 
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
r = requests.post('http://mysvc:8080/notify', json=json.dumps(jsonPrep), headers=headers)

go server抱怨:

E1026 15:49:48.974117       1 main.go:59] Failed to decode the request json json: cannot unmarshal string into Go value of type main.Data

当我在python中执行curl与rest查询时,我看不出有什么不同。

有人能帮我确定问题吗?

requests.post()json参数用于传递尚未调用json.dumps()的值。requestsjson参数本身上调用json.dumps(),因此因为您正在传递json=json.dumps(jsonPrep),所以jsonPrep最终将被JSONified两次,这不是您想要的。

使用data:

requests.post(..., data=json.dumps(jsonPrep), ...)

或者去掉json.dumps():

requests.post(..., json=jsonPrep, ...)

最新更新