背景- 我正在嘗試創建一個函式,該函式api_response在條件為真時繼續呼叫 API(回應 = )。當條件為 False 時,函式應改為回傳api_response。
函式- 這是我當前形式的函式。我把自己完全弄糊涂了,因此寫了一些筆記,以便您可以“嘗試”并了解我的思維程序:
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 一次然后就死了。任何人都可以正確地執行正確的回圈嗎?
uj5u.com熱心網友回復:
多虧了一個有用的用戶評論,我發現該try陳述句沒有測驗任何內容并且會無限回圈,相反,我習慣于while True啟動和無限回圈,并在使用try陳述句測驗條件 ( if "meta not in api_response)之前捕獲 API 回應。如果該條件為真,則回圈將繼續呼叫 API 獲取資料并從 API 列印一條訊息(獲取資料,例如percent_complete),并向用戶列印一條關于 API 回應進度的訊息。
最后,一次elif "meta in api_response:(意味著 API 回應現在正在回傳資料),然后 Ireturn 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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/387452.html
