TypeError: 'Response' object has no attribute '__getitem__'

后端 未结 2 1830
闹比i
闹比i 2021-01-04 21:34

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 u

2条回答
  •  旧时难觅i
    2021-01-04 21:54

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

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

    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)
    

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

提交回复
热议问题