0

I have a rest api which return True, False and "". Which i receive this in my requests.content I get the type as byte. I convert them to string and then try to compare. But the last else block executes leaving behind the first and second.

import requests
headers = {'Accept': '*/*'}
response = requests.get('http://{IP}/status', headers=headers)
status = response.content
status = str(status)
print(status)
# status returns "True", "False", ""
if (status == "True"):
    print ('Admin approved this request')
elif (status == "False"):
    print ('Admin disapproved this request')
else:
    print ('No response from admin')

Getting :- 'No response from admin' In all the cases

2 Answers 2

1

Double check the format of your response. If it's in something like JSON, you'll likely need to access the actual response ("True", "False", "") as a key/value pair.

Also, you can simply use response.text to get a string using UTF-8 encoding, instead of converting response.content to a string. https://realpython.com/python-requests/#content

Sign up to request clarification or add additional context in comments.

Comments

1

response.content is an object of type bytes.

Try calling decode() on response.content instead of casting to a str type.

For example if the content of the response is encoded in utf-8 then decode using utf-8:

status = response.content.decode('utf-8')

When casting a bytes object to a str type, the resulting string will be prefixed with "b'".

This is why the last else block in the code you've supplied always executes. The variable status will always be prefixed with "b'" (ie. "b'True'", "b'False'" or "b''") and the equality comparisons will always evaluate to False.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.