我试图从字典中的响应对象获取值,但我一直遇到这个错误,我认为你错了吗__getitem__
更常用于类中的索引?
这是代码:
import json
import requests
from requests.auth import HTTPBasicAuth
url = "http://public.coindaddy.io:4000/api/"
headers = {'content-type': 'application/json'}
auth = HTTPBasicAuth('rpc', '1234')
payload = {
"method": "get_running_info",
"params": {},
"jsonrpc": "2.0",
"id": 0,
}
response = requests.post(url, data=json.dumps(payload), headers=headers, auth=auth)
print("respone is: ", response['result'])
响应对象不是字典,您不能对其使用索引。
如果 API 返回一个JSON 响应,你需要使用response.json() method将其解码为 Python 对象:
data = response.json()
print("respone is: ", data['result'])
请注意,您也不必对请求 JSON 数据进行编码;你可以使用json
论证request.post()
方法在这里;这还为您设置 Content-Type 标头:
response = requests.post(url, json=payload, auth=auth)
最后但并非最不重要的一点是,如果 API 使用 JSONRPC 作为协议,您可以使用jsonrpc-requests project为您代理方法调用:
from jsonrpc_requests import Server
url = "http://public.coindaddy.io:4000/api/"
server = Server(url, auth=('rpc', '1234'))
result = server.get_running_info()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)