【问题标题】:TypeError: 'Response' object has no attribute '__getitem__'TypeError:“响应”对象没有属性“__getitem__”
【发布时间】:2015-12-16 09:47:49
【问题描述】:

我试图从字典中的响应对象中获取一个值,但我一直遇到这个错误,我认为你 __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'])

【问题讨论】:

    标签: python json python-requests json-rpc


    【解决方案1】:

    响应对象不是字典,不能对它使用索引。

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

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

    请注意,您也不必对请求 JSON 数据进行编码;你可以在这里使用request.post() 方法的json 参数;这也为您设置了 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()
    

    【讨论】:

    • 如果我可以 +2,我真的很感激这个答案。
    【解决方案2】:

    只需像这样更改您的源代码:

     response = requests.post(url, json=json.dumps(payload), headers=headers,   auth=auth).json()
    
     print("respone is: ", response['result'].encode('utf-8'))
    

    确实不能单独索引响应对象,而是为此目的您需要在json format 中返回信息(以便解析响应信息),您可以使用json() 和 为了获得正确的字符串,您必须使用 utf-8 对其进行编码(否则您的输出将类似于 -u'LikeThis)

    【讨论】:

    • 你也应该像其他人一样添加解释。
    • 不错,今天遇到了这个错误,稍后我会添加更好的解释。
    猜你喜欢
    • 1970-01-01
    • 2012-12-04
    • 2012-10-15
    • 2014-01-16
    • 2017-02-27
    • 2018-01-28
    • 2014-06-10
    • 2012-10-16
    • 2015-11-04
    相关资源
    最近更新 更多