-1

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?

jonrsharpe
123k31 gold badges278 silver badges488 bronze badges
asked Dec 4 at 19:40
2
  • 1
    Why would you want to return 0 in this case? Just let the exception unhandled. Python is not C ... Commented Dec 5 at 2:55
  • Just add another except clause Commented Dec 5 at 9:38

1 Answer 1

0

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 
answered Dec 4 at 19:57
Sign up to request clarification or add additional context in comments.

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.