【发布时间】: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
标签: python api while-loop