I'm retrieving data from a URL using reqests.get(). My device is connected by wifi. Occasionally, there is no internet access and my appliaction fails with the following error:
OSError: [Errno 101] Network is unreachable
During handling of the above exception, another exception occurred:
....
During handling of the above exception, another exception occurred:
...
During handling of the above exception, another exception occurred:
My requests.get() code is surrounded by the a try block:
try:
response = requests.get(url, timeout=10)
except requests.Timeout as e:
print(e)
return 0
if response.status_code == 200:
my_data = response.json()
# do some stuff
return my_data
else:
return 0
How do I alter the try block so that it returns 0 if the response status code is not 200, and also returns 0 if there is no network access?
1 Answer 1
All exceptions explicitly raised by requests inherit from requests.exceptions.RequestException. Therefore, you can simply use response.raise_for_status() and handle all exceptions in a try-except block.
import requests
def _get(url):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as exc:
return 0
1 Comment
raise_for_status method itself just checks the status_code and raises an exception if the code is >= 400. Use it when you want the exception to bubble up. If you're just going to handle that exception and return 0, that's a pointless indirection.
exceptclause