尝试循环 API 调用直到满足条件
Posted
技术标签:
【中文标题】尝试循环 API 调用直到满足条件【英文标题】:Trying to loop an API call until condition is met 【发布时间】:2022-01-20 20:40:06 【问题描述】:背景 - 我正在尝试创建一个在条件为真时继续调用 API(响应 = api_response
)的函数。当条件为 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 一次然后死掉。任何人都可以让我正确,并实施正确的循环吗?
【问题讨论】:
你为什么使用try / except
? try
子句中的语句永远不会失败
你启发我重新审视这个问题,并很快解决。谢谢@gimix
【参考方案1】:
感谢有用的用户评论,我发现 try
语句没有测试任何东西,会无限循环,相反,我使用 while True
启动无限循环,并在使用 @ 之前捕获 API 响应987654323@ 语句来测试条件 (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()
【讨论】:
以上是关于尝试循环 API 调用直到满足条件的主要内容,如果未能解决你的问题,请参考以下文章
python 循环为循环的类,它递归调用一个函数直到满足条件,然后移动到下一个函数并调用