1

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?

2 Answers 2

1

Seems like you could just adjust your try/except to look like this:

try:
    request_return = requests.get(path, timeout=30)
    if request_return.status_code == 200:
        break
except ConnectionError as e:
    pass

If you prefer, you can use request_return.status_code == requests.codes.ok as well.

If you're set on handling the request as an exception (for whatever reason), raise_for_status() returns an HTTPError, so you can amend your try/except like this:

try:
    request_return = requests.get(path, timeout=30)
    request_return.raise_for_status()
    break
except ConnectionError as e:
    pass
except HTTPError as e:
    pass
Sign up to request clarification or add additional context in comments.

Comments

1

You can test the status code and leave the loop only on a 200 like:

Code:

if request_return.status_code == 200:
    break

Probably should limit the number of retries:

import requests

def get_data(path):
    # Keep trying until the connection attempt is successful
    retries = 5
    while retries > 0:
        # Attempt a request
        try:
            request_return = requests.get(path, timeout=3)
            if request_return.status_code == 200:
                break
        # Handle a connection error
        except ConnectionError as e:
            pass
        retries -= 1

    if retries == 0:
        """ raise an error here """

    # Return the data
    return request_return.json()

get_data('https://stackoverflow.com/rep')

Comments

Your Answer

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.