ImNotLeet
ImNotLeet

Reputation: 391

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

I attempted to research this issue prior to making an account and posting. My research was inconclusive largely because I am new to Python.

Problem: I am trying to match a if statement to ensure that a server is up and running prior to running my main code.

Solution sets that didn't work:
1) I tried the below if statement
2) I tried piping the variable to look for leading/ending spaces.
3) I tried a response.split
4) I tried a response[:3] to match the first 3 characters and got the above error

What the script will do: The elastisearch server returns "< Response [200] >" if it is up and running.

Code:

Import requests    
es_server = "IP:PORT"
response = requests.get("http://" + es_server)
if response == '<Response [200]>':
 print "yep"

I get unicode errors if I try response.text()

Upvotes: 4

Views: 2033

Answers (1)

tobias_k
tobias_k

Reputation: 82929

The result of requests.get is not a string but a Response object holding all sorts of information. <Response [200]> is just the string representation of that object, but it is not equal to the object itself. See here for some documentation.

If you want to test the status code of the response, you should check like this:

if response.status_code == 200:
    print "yep"

Upvotes: 2

Related Questions