2016-04-25 221 views
0

獲得價值我有一個數據類此方法:無法從蟒蛇字典

def submit_request(self, method, path, body=None, header=None): 
    conn = httplib.HTTPSConnection(self.host) 
    conn.request(method, path, body, self.headers) 
    resp = conn.getresponse() 
    return resp.status, resp.read() 

裏面我是用搶的每個請求的響應。對於我正在處理的當前響應,我無法獲取特定的值。

通常我會去

status, resp = submit_request("GET", "/path/to/...", body) 
info = json.loads(resp) 
value = info["value"] 

,我會被設置爲使用相應的值從字典。但正如我將在下面展示的那樣,我無法爲此案件做到這一點。

>>> print resp 
[{"deviceId":28,"displayName":"test-device","status":"Pending_Authorized"}] 

如果我填寫Flash這種反應我能做到

>>> resp[0]['deviceId'] 
28 

但代碼中做它不工作(我只是得到resp[0][)。我一直收到

TypeError: string indices must be integers, not str 

任何跡象表明爲什麼會發生這種情況?

下面是相關代碼:

def test_get_device_list(self): 
    ''' 
    GET /Device/List 
    ''' 
    status_code, resp = self.api.submit_request("GET", "/Device/List") 
    log.log_info("GET /Device/List: HTTP - %s" % str(status_code)) 
    log.log_info("GET /Device/List: Response - %s" % str(resp)) 
    self.assertEqual(status_code, 200) 

    #GET /Device/{DeviceID} 
    device_id = self.api.parse_header(resp, "deviceId") 
    status_get, resp_get = self.api.submit_request("GET", "/Device/%s" % str(device_id)) 
    log.log_info("GET /Device/{DeviceID}: HTTP - %s" % str(status_get)) 
    log.log_info("GET /Device/{DeviceID}: Response - %s" % str(resp_get)) 
    self.assertEqual(status_get, 200) 

,並從支持數據類

def submit_request(self, method, path, body=None, header=None): 
    conn = httplib.HTTPSConnection(self.host) 
    conn.request(method, path, body, self.headers) 
    resp = conn.getresponse() 
    return resp.status, resp.read() 

def parse_header(self, resp, arg): 
    info = json.loads(resp) 
    parse = info["%s" % str(arg)] 
    return parse 

以下是完整的錯誤:

ERROR: test_get_device_list (__main__.TestAPI) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "API.py", line 207, in test_get_device_list 
    device_id = self.api.parse_header(str(resp), "deviceId") 
    File "/home/zach/Desktop/Automation/data.py", line 47, in parse_header 
    parse = info["%s" % str(arg)] 
TypeError: list indices must be integers, not str 

我試圖找到一種方法,從響應中獲取上面的'deviceId'。我正在用parse_header()方法做出不同的響應,但對於此響應它不起作用。

+0

您正在將響應對象(它看起來是包含單個對象的數組)加載到變量info中,然後嘗試訪問該數組的「value」屬性。數組不具有「value」屬性。 – Hamms

+0

所以...爲什麼你沒有在'resp'字符串上使用'json.loads'? – user2357112

+0

@ user2357112我得到了相同的TypeError – user3239567

回答

0

您試圖在此處使用字符串訪問您的列表,您是否嘗試訪問此處的第一個項目以在調用密鑰之前訪問您的字典?

parse = info[0].get(arg) 
+0

啊,我明白了。謝謝! – user3239567

+0

你敢打賭,你的項目很棒! –