简体   繁体   中英

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?

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM