我试图从字典中的响应对象中获取一个值,但我一直遇到这个错误,我认为你 __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 , 你需要使用 response.json()
method将其解码为 Python 对象:
data = response.json()
print("respone is: ", data['result'])
请注意,您也不必对请求的 JSON 数据进行编码;你可以在这里使用 json
参数到 request.post()
方法;这也为您设置了 Content-Type header :
response = requests.post(url, json=payload, auth=auth)
最后但同样重要的是,如果 API 使用 JSONRPC 作为协议(protocol),您可以使用 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()
关于python - 类型错误 : 'Response' object has no attribute '__getitem__' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32665659/