2014-12-06 62 views
0

我有一段非常簡單的代碼可以處理Python請求0.x,但是當我更新到2.x時,它不再有效。Python請求0.x代碼端口爲2.x

的代碼將返回我包含在顏色中'field1'

import time 
import requests 


# Read the thingspeak feed to get the current colour 
while True: 
    cheerlights = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json').json['field1'] 
    print(cheerlights) 
time.sleep(16) 

當我跑這不是我得到這個錯誤:

回溯(最近通話最後一個): 文件「cheelightsJsonHELP.py 」,第7行,在 cheerlights = requests.get( 'http://api.thingspeak.com/channels/1417/field/1/last.json ')上傳.json [' field1的 '] 類型錯誤: 'instancemethod' 對象沒有屬性' 的GetItem'

我已閱讀從0.x遷移到2.x的文檔,但不幸的是,這不是我的強大領域,任何人都可以提供幫助嗎?

回答

3

response.json()現在是方法,在過去它是一個屬性;添加()叫它:

response = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json') 
cheerlights = response.json()['field1'] 

演示:

>>> import requests 
>>> response = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json') 
>>> response.json()['field1'] 
'orange' 
+0

非常感謝你的幫助,這完美地工作! – 2014-12-08 23:04:23