亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 bash 到 GO 服務器的 REST post 查詢有效但對于 Python 失敗

從 bash 到 GO 服務器的 REST post 查詢有效但對于 Python 失敗

Go
12345678_0001 2023-05-02 10:13:52
我有解go server組json它收到它。當我使用 時它有效,curl但在 . 的情況下失敗python。去服務器解組代碼: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 命令,它會毫無怨言地工作: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當我curl在python.誰能幫我找出問題所在?
查看完整描述

1 回答

?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

json的參數用于requests.post()傳遞尚未調用json.dumps()它的值。 requests調用json.dumps()參數json本身,所以因為你正在傳遞json=json.dumps(jsonPrep),jsonPrep最終會被 JSONified 兩次,這不是你想要的。

要么使用data

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

或擺脫json.dumps()

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


查看完整回答
反對 回復 2023-05-02
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號