首页 > 解决方案 > 使用 while 循环检查状态是否更改

问题描述

编程新手。我正在创建一个脚本,在其中发布 API 搜索并获取进度状态。状态可以是“COMPLETED”、“EXECUTE”、“WAITING”。我正在努力如何继续检查状态。以下是我的尝试:

for searches in search
 ............ # for loop to perform another task
 def check_status():
            check_search = requests.get("https:example.com/search") #Getting the search status
            check_results = check_search.json() 
            check_results_str = json.dumps(check_results, indent=2)
            searchresp = json.loads(check_results_str)
            search_status = searchresp['status'] # Extracting the Status key from the JSON response
            print(search_status)


            while search_status != "COMPLETED": # Checking if the search status is completed
                print ("Search Not yet completed,searching again..") 
                sleep(3)
                check_status() # Attempting to call check_status function again to get the status

该脚本正在工作,直到获得搜索状态,当它到达 while 循环时,for 循环中断并且脚本完成。我还尝试缩进 check_status() 以与 while 循环对齐。通过这种方式执行程序,但是脚本永远不会再次运行 get API 搜索来获取搜索状态。我希望再次调用 check_status 函数,直到 search_status 为“COMPLETED”。有什么想法可以实现这一目标吗?谢谢

标签: pythonapiwhile-loop

解决方案


欢迎来到 SO 社区。

您应该限制重试次数以了解 API 是否返回 COMPLETED 状态

def check_status():
    check_search = requests.get("https:example.com/search") #Getting the search status
    check_results = check_search.json() 
    check_results_str = json.dumps(check_results, indent=2)
    searchresp = json.loads(check_results_str)
    search_status = searchresp['status'] # Extracting the Status key from the JSON response
    print(search_status)


    if search_status != "COMPLETED": # Checking if the search status is completed
        return False
    else:
        return True


RETRIES=100

for i in range (0,RETRIES):
    APIStatus=check_status()
    if(APIStatus):
        break

然后,您可以保留哪些请求失败的日志,以便您可以尝试了解它们失败的原因或用于将来的审计日志记录。

我选择的 Retries 值是任意的,它也可能取决于您期望答案返回的速度(基于时间)。


推荐阅读