Python请求0.x代码端口到2.x

2024-09-28 23:38:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段非常简单的代码处理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行,在 欢呼声=请求。获取('http://api.thingspeak.com/channels/1417/field/1/last.json').json['field1'] TypeError:“instancemethod”对象没有属性“getitem

我已经阅读了有关从0.x迁移到2.x的文档,但不幸的是,这不是我的一个重点领域,有人能帮忙吗?你知道吗


Tags: the代码importcomapijsonhttpfield
1条回答
网友
1楼 · 发布于 2024-09-28 23:38:11

^{}现在是一个方法,过去它是一个属性;添加()来调用它:

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'

相关问题 更多 >