3

I do a loop of requests and unfortunately sometimes there happens a server timeout. Thats why I want to check the status code first and if it is not 200 I want to go back and repeat the last request until the status code is 200. An example of the code looks like this:

for i in range(0, len(table)):
        var = table.iloc[i]
        url = 'http://example.request.com/var/'
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()
        else:
            "go back to response"

I am appending the response data of every i, so I would like to go back as long as the response code is 200 and then go on with the next i in the loop. Is there any easy solution?

2
  • 1
    Also: url = "http://example.request.com/{0:}/".format(var). Commented Sep 14, 2019 at 14:37
  • You might want to check that you actually get a timeout, either locally or remotely, before hammering the server... Commented Sep 14, 2019 at 14:50

2 Answers 2

8

I believe you want to do something like this:

for i in range(0, len(table)):
        var = table.iloc[i]
        url = 'http://example.request.com/var/'
        response = requests.get(url)
        while response.status_code != 200:
            response = requests.get(url)     
        data = response.json()
Sign up to request clarification or add additional context in comments.

1 Comment

A more robust solution to the same problem can be found here: stackoverflow.com/a/35636367/195964
2

I made a small example, used an infinite loop and used break to demonstrate when the status code is = 200

while True:
    url = 'https://stackoverflow.com/'

    response = requests.get(url)

    if response.status_code == 200:
        # found code
        print('found exemple')
        break

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.