Python循环,直到请求响应代码为200

时间:2019-05-09 18:54:55

标签: python python-requests

我正在尝试发出python请求,并在响应状态代码为200时继续执行脚本。否则,请一直循环浏览直到获得200。

尝试以下陈述不确定我在这里缺少什么。条件不会退出循环。

尝试1:

while True:
    if (offense_response.status_code == 404):
        time.sleep(5)
        logging.info("Status code is 404, entering sleep for 5 seconds")
        offense_response = requests.get(qradar_offense_url, headers=q_headers, verify=False)
        continue
    if (offense_response.status_code == 200):
        logging.info("Status code is 200, exiting loop")
        exit()

尝试2:

while (offense_response.status_code != 200):
    if (offense_response.status_code == 404):
        logging.info("Status code is 404, entering sleep for 5 seconds")
        time.sleep(5)
        offense_response = requests.get(qradar_offense_url, headers=q_headers, verify=False)
    else: 
        logging.info("Status code is 200, exiting loop")

尝试3:

while True:
    if (offense_response.status_code != 200):
        time.sleep(5)
        logging.info("Checking Response Status Code again")
        offense_response = requests.get(qradar_offense_url, headers=q_headers, verify=False)
        if (offense_response.status_code == 200):
            break

1 个答案:

答案 0 :(得分:0)

你能试试这个吗?

status = True
while status:
    if (offense_response.status_code != 200):
        #check the the status and assign to offense_response.status_code
        logging.info("Status code is not 200, entering sleep for 5 seconds")
        time.sleep(5)
    else:
        logging.info("status code is 200, hence exiting")
        status = False