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

查看:29
本文介绍了类型错误:“响应"对象没有属性“__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 数据进行编码;您可以在此处将 json 参数用于 request.post() 方法;这也为您设置了 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 作为协议,您可以使用 jsonrpc-requests project 为你代理方法调用:

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()

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

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