简体   繁体   English

Python请求循环,如果状态码不是200,则重试

[英]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: 这就是为什么我要首先检查状态代码,如果不是200的原因,我想返回并重复上一个请求,直到状态代码为200。代码示例如下所示:

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. 我将附加每个i的响应数据,因此我想返回,只要响应代码为200,然后继续循环中的下一个i。 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 我举了一个小例子,使用无限循环并使用break来演示状态代码何时= 200

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

    response = requests.get(url)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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