Python要求0.x代码端口为2.x.

时间:2014-12-06 22:35:03

标签: python python-requests

我有一段非常简单的代码使用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行,in     cheerlights = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json')。json ['field1'] TypeError:'instancemethod'对象没有属性' getitem '

我已经阅读了有关从0.x迁移到2.x的文档,但不幸的是,这不是我的强大领域,有人可以帮忙吗?

1 个答案:

答案 0 :(得分: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'