python - 使用 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”。有什么想法可以实现这一目标吗?谢谢
解决方案
欢迎来到 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 值是任意的,它也可能取决于您期望答案返回的速度(基于时间)。
推荐阅读
- c++ - EtherCard 库初始化不适用于二维数组
- javascript - 如何修复警告“预计在箭头函数数组回调返回中返回一个值”
- javascript - Discord.js guildMemberUpdate 事件
- javascript - 使用 React 和 Draft.js 从自定义 ComponentBlock 中的 EditorBlock 检索字符串
- android - 如何在 res/navigation/nav_graph.xml 禁用 Android 导航
- sql-server - ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效
- php - 在 WooCommerce 我的帐户自定义菜单项内容中定义用户变量
- kotlin - 对密封类的抽象中间子类进行不必要/损坏的检查,在详尽时需要
- html - CSS 样式问题:类是一起设计的,但看起来却大不相同
- ios - Swift 5 - 在 JSON 数组的自定义 CollectionviewCell 中设置 TextLabel