代码之家  ›  专栏  ›  技术社区  ›  William

在Python中如何正确处理API超时

  •  0
  • William  · 技术社区  · 3 年前

    出身背景 -
    我正在写一篇文章 .py 调用API的脚本,将响应保存为 .json 在将响应保存到 .xlsx 文件

    问题 -
    我调用的API非常不可靠,尤其是因为它是一个 GET 用c.6000行数据进行响应,如以下空数据库中的间歇性超时错误所示 .json 文件(应包含响应):

    enter image description here

    调用API的函数 -

    def api_call():
            key, secret = ini_reader()
            date = dt.datetime.today().strftime("%Y-%m-%d")
            url = "https://myfirm.vendor_api.com/api/v1/portfolio/views/304078/results?portfolio_id=1&portfolio_type=firm&output_type=json&start_date="+date+"&end_date="+date+"&addepar_firm=381"
            print("-------------------------------------\n","API URL constructed for:", date, "\n-------------------------------------")
            response = requests.get(url, auth = HTTPBasicAuth(key, secret), headers={"Vendor-Firm":"461"})
            api_response = json.loads(response.text)
        return api_response
    

    目标及;提议的解决方案 -
    我希望我的脚本继续调用API,直到成功(成功=无错误)。我能想到的唯一真正的解决办法是实施 while loop 在我的脚本的函数中,它进行API调用。

    我陷入困境的地方,是如何定义要满足的条件,以便脚本结束,并且不会陷入无限循环?

    0 回复  |  直到 3 年前
        1
  •  0
  •   William    3 年前

    我发现了以下几点-

    1. 尽管我的API响应时断时续地给我一个 Error: 400: Bad Request - API request timeout exceeded. API响应仍在写入一个 .JSON 而响应仍然保存在名为 api_response 我正试着 pd.json_normalize 使用。
    2. 名为 def unpack_response(): (负责对API响应进行解包和规范化的部分代码引发了 KeyError 尝试运行时,这是由于 api_回应 不包含任何内容的变量。
    3. 我最终通过实施 while True 使用 def unpack_response(): 利用了 api_回应 可变内容。

    作用于 虽然是真的 -

    def unpack_response():
        api_response = response_writer()
    
        while True:
            try:
                df = pd.json_normalize(api_response['data']['attributes']['total']['children'])
                df.drop(columns=['grouping', 'entity_id'], inplace=True)
                df.columns = df.columns.str.replace(r'columns.', '')
                column_name_mapper = {column['key']: column['display_name'] for column in api_response['meta']['columns']}
                df.rename(columns=column_name_mapper, inplace=True)
            except KeyError:
                        print("-----------------------------------\n","API TIMEOUT ERROR: TRYING AGAIN...", "-----------------------------------\n")
                        api_response = reponse_writer()
            break