2015-12-29 119 views
2

我想發佈HTTP請求。我設法讓代碼工作,但我掙扎着返回一些結果。響應'對象不可以訂閱Python http post請求

結果看起來是這樣的

{ 
    "requestId" : "8317cgs1e1-36hd42-43h6be-br34r2-c70a6ege3fs5sbh", 
    "numberOfRequests" : 1893 
} 

我想獲得的RequestID,但我不斷收到錯誤響應」對象未標化的

import json 
import requests 

workingFile = 'D:\\test.json' 

with open(workingFile, 'r') as fh: 
    data = json.load(fh) 

url = 'http://jsontest' 
username = 'user' 
password = 'password123' 

requestpost = requests.post(url, json=data, auth=(username, password)) 

print(requestpost["requestId"]) 

回答

7

response對象包含更多信息不僅僅是有效載荷。要獲取POST請求返回的JSON數據,您必須按in the example所述訪問response.json()

requestpost = requests.post(url, json=data, auth=(username, password)) 
response_data = requestpost.json() 
print(response_data["requestId"]) 
1

您應該將響應轉換成字典:

requestpost = requests.post(url, json=data, auth=(username, password)) 
res = requestpost.json() 
print(res["requestId"])