Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python request loop, retry if status code not 200

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?

like image 300
JWW Avatar asked Apr 30 '26 06:04

JWW


2 Answers

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()
like image 173
Calslock Avatar answered May 01 '26 20:05

Calslock


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
like image 40
Sandro Meireles Avatar answered May 01 '26 20:05

Sandro Meireles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!