I've got this code and in the second link it should raise an exception 404.
The thing is I do get the message the way I coded it for but also I get the traceback message like something is not right with my code.
It is a function called "get_headers_if" and the input are either response_url or response_url_2.
import requests
import json
def get_headers_if(response):
if response.status_code==200:
headers=response.headers
print("The headers for this URL:", response.url, "are: ",headers)
else:
raise Exception("Unexpected response (%s: %s)." % (response.status_code, response.reason))
response_url=requests.get("http://wikipedia.org")
response_url_2=requests.get("http://google.com/thehearthisflat")
get_headers_if(response_url)
get_headers_if(response_url_2)
CodePudding user response:
You can raise for status and do exception handling. Requests library by default provides an option to check for status codes and raise exception. You can modify what to print on exception in the exception print statement.
import requests
def get_headers_if(response):
try:
response.raise_for_status()
headers=response.headers
print("The headers for this URL:", response.url, "are: ",headers)
except requests.exceptions.HTTPError as err:
print("Unexpected response (%s)." % err)
response_url=requests.get("http://wikipedia.org")
response_url_2=requests.get("http://google.com/thehearthisflat")
get_headers_if(response_url)
get_headers_if(response_url_2)
For more details: https://github.com/psf/requests/blob/b0e025ade7ed30ed53ab61f542779af7e024932e/requests/models.py#L937