尝试循环 API 调用直到满足条件

Trying to loop an API call until condition is met

背景 - 我正在尝试创建一个在条件为真时继续调用 API(响应 = api_response)的函数。当条件为 False 时,函数应该改为 return api_response.

函数 - 这是我当前形式的函数。我自己完全糊涂了,所以写了一些笔记,这样你就可以'try'了解我的思路:

def api_call():
#   Getting required variables by calling other functions
    key, secret, url = ini_reader()
    endpoint_url = endpoint_initializer()
    
#   In these 3x lines of code I'm trying to ensure the API is called.
    while True:
        response = requests.get(url = endpoint_url, auth = HTTPBasicAuth(key, secret), headers = {"My-firm": "482"})
        api_response = json.loads(response.text)

#       I am now trying to take the returned 'api_response' and see if a condition is met / trying extract certain key pair values,
#       which tell me the data isn't available. If the condition is met (keys are in the response / data isn't available), I am expecting
#       the API to continue being called again and the loop continues to iterate until the condition is not met, at which point I am expecting to simply have 'api_response' returned.  
    try:
            id_value = "id"
            res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
            id_value = "".join(res1)
            percent_value = "percent_complete"
            res2 = (tuple(api_response["data"]["attributes"].get("percent_complete", '') for key, val in api_response.items()))
            print(f' Your data requested, associated with ID: {id_value} is {res2} complete!')
            time.sleep(5)
#       If the above condition isn't met, then return 'api_response', which includes the data.
        except:
            return api_response
api_call()

问题 - 目前,我似乎无法让我的循环正常运行,因为它调用了一次 API 然后就死掉了。谁能用正确的循环来纠正我的错误?

多亏了有用的用户评论,我发现 try 语句没有测试任何东西并且会无限循环,相反,我使用 while True 开始无限循环,并捕获 API 响应,在使用 try 语句测试条件 (if "meta not in api_response) 之前。如果该条件为真,则循环将继续调用 API 获取数据并从 API 打印一条消息(获取 percent_complete 等数据)并向用户打印一条消息关于 API 响应进度。

最后,一旦elif "meta in api_response:(意味着API响应现在正在返回数据),然后我return api_respone,准备好被另一个函数使用。

功能齐全-

def api_call():

    key, secret, url = ini_reader()
    endpoint_url = endpoint_initializer()
    
    date = dt.datetime.today().strftime("%Y-%m-%d")
    print("-------------------------------------\n","API URL constructed for:", date, "\n-------------------------------------")
    print("-------------------------------------------------------------\n","Endpoint:", endpoint_url, "\n-------------------------------------------------------------")

    while True:
        response = requests.get(url = endpoint_url, auth = HTTPBasicAuth(key, secret), headers = {"Vendor-firm": "443"})
        api_response = json.loads(response.text)
        if "meta" not in api_response:
            id_value = "id"
            res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
            id_value = "".join(res1)
            percent_value = "percent_complete"
            res2 = (tuple(api_response["data"]["attributes"].get("percent_complete", '') for key, val in api_response.items()))
            print(f' Your data requested, associated with ID: {id_value} is {res2} complete!')
            time.sleep(5)
        elif "meta" in api_response:
            return api_response
api_call()