2016-03-11 22 views
0

將字符串變量作爲字符串值存儲在字典中的最佳方式是什麼?將字符串變量作爲字符串值存儲在字典中的最佳方式是什麼?

下面我試圖將名爲authToken一個字符串變量,並把它放到header字典,所以我可以使用請求模塊

if currentTime >= authExpTime: 
     getAuthToken() 
else: 
     header = {'Content-Type':'application/json','Authorization':'OAUTH2 access_token=authToken'} 
     print header 
     for i in metricsCollected: 
       callURL = apiURL + i + "?samepletime=" 
       print callURL 
       apiResponse = requests.get(apiURL, headers=header) 
       apiResponse.json() 
+0

看來你問的是如何獲得authToken的值到'授權'鍵值的字符串中。這是你問的嗎? – hlongmore

+0

我不太明白你在這裏問什麼。你能詳細說明一下嗎? – That1Guy

+0

@hlongmore這就是它:) – Graeme

回答

3

有很多方法可以做到這一點。有些比其他更加pythonic。我可能會這樣做的方式是:

header = { 
    'Content-Type': 'application/json', 
    'Authorization': 'OAUTH2 access_token=%s' % (authToken) 
} 
+0

我認爲這比我的回答更好,因爲它避免了字符串操作中'+ ='的混淆/效率低下。 – jDo

1

喜歡這麼叫吧?

if currentTime >= authExpTime: 
     getAuthToken() 
else: 
     header = {'Content-Type':'application/json','Authorization':'OAUTH2 access_token='} 
     header["Authorization"] += authToken 
     print header 
     for i in metricsCollected: 
       callURL = apiURL + i + "?samepletime=" 
       print callURL 
       apiResponse = requests.get(apiURL, headers=header) 
       apiResponse.json() 
+0

謝謝大家!非常感謝;) – Graeme

相關問題