在另一个函数的循环中调用一个函数

Calling a function in a loop of another function

背景 - 我有一个函数需要来自另一个函数 (api_response = api_call()) 的 API 响应 (api_response)。 Code Block #1 继续迭代,直到 meta 在响应中。一旦 metaapi_response 中,那么 Code Block #2 将 return api_response.

问题 - 虽然我的代码正在为 meta 测试 api_response,但我还没有找到一种方法来包括连续调用其他函数(api_response = api_call() 在我的 while loop 中,这将允许确定 meta 何时仍在 api_response.

函数-

def unpack_response():
    # Code Block # 1
    api_response = api_call()
    while "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!')
    # Code Block # 2
    if "meta" in api_response:
        return api_response
unpack_response()

问题 - 关于我如何将 api_response 集成到我的循环中,以便每次循环迭代都会调用它,有人有任何指示吗?

不确定我是否理解正确。 你可以这样做吗?

def unpack_response():
    # Code Block # 1
    while True:
        api_response = api_call()
        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 = (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 {percent_value} complete!')
            time.sleep(5)
        # Code Block #2
        else:
            print(api_response)
            break

这里有几个选项。如果你有python 3.8+,你可以使用walrus operator (:=)直接把api_call放在循环的条件中:

def unpack_response():
    while "meta" not in (api_response := api_call()):
        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!')
    return api_response

一个更传统但同样惯用的方法是 运行 永远循环并 break 当达到正确的条件时:

def unpack_response():
    while True:
        api_response = api_call()
        if "meta" in api_response:
            return 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!')

在这两种情况下,您都可以考虑放慢拨打 API 睡眠或类似电话的速度。