【发布时间】:2021-05-23 18:43:14
【问题描述】:
我有一个案例,我必须不断检查 GET 调用的响应,直到我在 api 响应中看到 status 为 success。从active 到success 的状态大约需要 20 到 50 分钟。只有当我看到此状态时,我才能执行其他操作。
如何在 python 中实现这一点?
我试过这个polling python 库。但这并没有多大帮助。
这是我的代码。但这不是我想要的。有没有其他方法可以做到这一点?
try:
while True:
response = requests.get(f'{os.environ["BASE_URL"]}/syncs/076532', headers=headers)
json_res = response.json()
if json_res.get('status') != 'success':
logging.info("Polling started.......")
logging.info("Waiting.......")
time.sleep(120)
print("Got status as success. Proceeding......")
sys.exit()
except KeyboardInterrupt:
logging.info("exiting")
sys.exit()
提前致谢
【问题讨论】:
-
它应该做什么不做什么?你可以有几个 except 块来处理不同的异常(例如没有 JSON 响应或超时)
-
哦,当您成功阅读时,您想
break或return然后继续您的while循环(这样会发出 new 请求每次迭代,而不是目前只有一个..这可以通过continue在睡眠后修复)..看看文档break and continue Statements, and else Clauses on Loops
标签: python rest python-requests polling