TypeError:“响应"对象没有属性"__getitem__" [英] TypeError: 'Response' object has no attribute '__getitem__'

查看:149
本文介绍了TypeError:“响应"对象没有属性"__getitem__"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字典中的响应对象获取值,但是我一直遇到这个错误,我以为您__getitem__更常用于类中的索引编制吗?

I am trying to get a value from a response object in a dictionary, but I keep running into this error, am I wrong in thinking you __getitem__ is more commonly used for indexing in classes?

这是代码:

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'])

推荐答案

响应对象不是字典,不能在其上使用索引.

The response object is not a dictionary, you cannot use indexing on it.

如果API返回 JSON响应,则需要使用 response.json()方法将其解码为Python对象:

If the API returns a JSON response, you need to use the response.json() method to decode it to a Python object:

data = response.json()
print("respone is: ", data['result'])

请注意,您也不必编码请求JSON数据.您可以在此处使用request.post()方法的json参数;这还会为您设置Content-Type标头:

Note that you don't have to encode the request JSON data either; you could just use the json argument to the request.post() method here; this also sets the Content-Type header for you:

response = requests.post(url, json=payload, auth=auth)

最后但并非最不重要的一点是,如果API使用JSONRPC作为协议,则可以使用 项目为您代理方法调用:

Last but not least, if the API uses JSONRPC as the protocol, you could use the jsonrpc-requests project to proxy method calls for you:

from jsonrpc_requests import Server

url = "http://public.coindaddy.io:4000/api/"
server = Server(url, auth=('rpc', '1234'))

result = server.get_running_info()

这篇关于TypeError:“响应"对象没有属性"__getitem__"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆