print(response)
if(response=="<Response [200]>"):
print("true")
else:
print("false")
getting response as '<Response [200]>'
getting false
require True as output
The builtin function print will automatically apply str() to any object that is not already str. So what gets printed is actually str(response), which is a string representation of response, kinda like a summary. Comparing the human-readable str summary of any object to the object itself will only return true if that object was already a str. That is not the case here, as you're dealing with requests.Response object.
For your purposes, use .status_code to check:
Example:
import requests
response = requests.get('https://stackoverflow.com/questions/60733985/compare-response-200-and-i-require-true-as-answer')
print(response)
if(response.status_code==200):
print("true")
else:
print("false")
Output:
<Response [200]>
true
Related
response = input("Do you want some food? (Y/N): ")
if response == "Y":
print("Come! There is pizza for you")
elif response == "N":
print("Alright, let us do Sisha instead.")
elif response == range(999):
print("The required response is Y/N.")
else:
print("I do not understand the prompt")
Q1: How to give feedback when user input numbers instead of string?
A1: I take a look in python documentation but it seems that range cannot be used in if statement?
I try to modify the code by stating
deret_angka = int or float
for n in deret_angka:
print("The required response is Y/N.")
and third ifs condition to:
elif response == deret_angka:
print("The required response is Y/N.")
But got TypeError: 'type' object is not iterable
Q2: How to give Y & N value even if its lower case y/n?
A2: I tried to put "Y" or "y" but it doesn't work and just passed to next if condition.
It's pretty simple, you can give feedback in many ways in python.
Let's say the user typed a number so we can try to convert the type of the input and see if it raises an error like that:
response = input("Do you want some food? (Y/N): ")
try:
float(response)
int(response)
except ValueError: #it a string or a bool
print("The required response is Y/N.")
If you want to check on a number in a specific range you can do it like that:
if response in [range(999)]:
pass
You can't check just range(999) because it is an object. You need to convert this object to a list to loop over it.
To check lower case you can do it in some ways:
response = input("Do you want some food? (Y/N): ")
if response in ['Y', 'y']:
pass
elif response in ['N', 'n']:
pass
#or like that:
if response.lower = 'y': # Just convert the input to lower
pass
if response.upper = 'N': # You can also do this vice versa and convert to upper and check.
pass
I wrote the following code but the problem is that I recieved an error (AttributeError: 'bytes' object has no attribute 'hexdigest')
the error syntax doesn't work
import requests
import hashlib
def request_api_data (query_char):
url = 'https://api.pwnedpasswords.com/range/'+ query_char
res = requests.get(url)
if res.status_code != 200:
print('it is an error')
#raise RuntimeError(f'Error fetching: {res.status_code}, check api and try again')
return res
request_api_data('123')
def pwned_api_check(password):
sha1password= hashlib.sha1(password.encode('utf-8').hexdigest().upper())
print (sha1password)
#return sha1password
pwned_api_check('123')
Why does this error occur and how do I fix it??
You need to add a parenthesis after hashlib.sha1(password.encode('utf-8'), so hexdigest().upper() is called on it.
The following code works for me:
hashlib.sha1(password.encode('utf-8')).hexdigest().upper()
I was taking the same class as you and got the same error. The parenthesis are in the wrong place.
sha1password = hashlib.sha1(password.encode('utf-8')).hexdigest().upper()
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
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
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.
I how to use it but I noticed that if I don't use read then it can spit out different thing.
It can spit out <_io.TextIOWrapper name='story.txt' mode='r' encoding='UTF-8'>
when using text files.
It can also return <http.client.HTTPResponse object at 0x76521550>
when using urlopen from urllib.
What do those things mean and what does .read() actually do?
Those are "file-like objects" that have a .read() method and you are seeing the repr() of the object, which is a description string. When you call .read() it reads the complete contents from the object, usually as a byte or Unicode string.
A small, custom example:
class Demo:
def __repr__(self):
return '<My Custom Description>'
def read(self):
return 'some stuff'
x = Demo()
print(x)
print(x.read())
Output:
<My Custom Description>
some stuff
I have meet a problem, when I develop a web use python3+flask, when name has no in put, I am confused, the result is True in print
name = request.args.get('name')
if name is not None:
print('True')
else:
print('False')
I refer to python documents, "A is not B" means A and B is not same object.
And I make the following test:
print(name) #None
print(type(name)) #<class "str">
print(type(None)) #<class "NoneType">
I found the answer, but when I use the following format
if name:
print('True')
else:
print('False')
it prints True and print(name) I get None
I have to write like the following:
if name != str(None):
print('True')
else:
print('False')
I feel it a little uncomfortable when use it like this, how I can compare it in a elegant way.
Getting a string "None" as part of a request commonly happens when you return a None value as part of a previous response.
Example:
# given a variable that is passed to a jinja template as None
# instead of as an empty string
name = None
Will result in a link with "None" as a string.
<a href="/some/link?name={{ name }}>click here</a>
Instead of trying to handle for a string "None" in any given request where you expect a string, you should output the original variable as an empty string:
name = None
...
# convert Nones to empty strings right before sending to jinja
if not name:
name = ''
print(True if "None" not in name else False)
I think that's more elegant way of printing out in your case.