I am using requests to get some data from a server, which is done in a while loop. However, every now and then, one of two errors occur. The first is that the status_code of the return from the request is not equal to 200, and this prints out an error message. The second is that a ConnectionError exception is raised.
If I receive either error, I want to keep attempting to get the data. However, I'm not sure how to do this for both types of error.
I know how to handle the ConnectionError exception, for example:
def get_data(self, path):
# Keep trying until the connection attempt is successful
while True:
# Attempt a request
try:
request_return = requests.get(path, timeout=30)
break
# Handle a connection error
except ConnectionError as e:
pass
# Return the data
return request_return.json()
But how can I also handle the status_code in a similar manner? Is it something to do with the raise_for_status() method?