簡體   English   中英

嘗試循環 API 調用直到滿足條件

[英]Trying to loop an API call until condition is met

背景- 我正在嘗試創建一個 function 在條件為真時繼續調用 API (響應 = api_response )。 當條件為 False 時, function 應改為返回api_response

Function - 這是我當前形式的 function。 我完全迷惑了自己,因此寫了一些筆記,所以你可以“嘗試”並理解我的思維過程:

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()

問題- 目前,我似乎無法正確地將我的循環轉到 function,因為它調用 API 一次然后死掉。 誰能把我說得對,用正確的循環來實施?

感謝一個有用的用戶評論,我發現try語句沒有測試任何東西並且會無限循環,相反,我使用while True啟動和無限循環,並在使用try語句測試條件之前捕獲了 API 響應( if "meta not in api_response )。如果該條件為真,則循環將繼續調用 API 獲取數據並從percent_complete打印一條消息(獲取諸如 percent_complete 之類的數據),並在 ZDB9742387AZ 響應中向用戶打印一條消息進步。

最后,一旦elif "meta in api_response: (意思是 API 響應現在正在返回數據),然后我return api_respone ,准備被另一個 function 使用。

完整的 function -

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM