【问题标题】:How can you return good data from inside a function if the function breaks?如果函数中断,如何从函数内部返回好的数据?
【发布时间】:2019-02-05 02:43:34
【问题描述】:

我正在从 web api(使用 python)收集数据,并且我正在使用循环来处理对 api 的数千次调用。该功能运行良好,但我的电脑进入睡眠状态并且互联网连接丢失。我在调用 api 时将数据存储为字典列表。我的问题是:当函数失败时,由于我的列表在函数内部,我什至无法获得它在失败之前进行的数百次成功调用。如何添加错误处理或其他方法,以便如果它在某个时候失败,比如在 500 次调用之后,我仍然可以获得 499 条数据?

如果我在不将代码放入函数的情况下运行代码,我的列表在代码中断之前仍然可行,但我觉得将其放入函数“更正确”

#this is how the function is set up in pseudo-code:
def api_call(x):
    my_info = []
    for i in x:
        dictionary = {}
        url=f'http://www.api.com/{x}'
        dictionary['data'] = json['data']
        my_info.append(dictionary)
    return my_info

another_variable = api_call(x)

【问题讨论】:

    标签: python function error-handling


    【解决方案1】:

    只需将其包装在 try/except/finally 块中。 finally 总是在离开 try 语句之前执行。 finally 块所做的解释是here

    def api_call(x):
        my_info = []
        try:
            for i in x:
                dictionary = {}
                url=f'http://www.api.com/{x}'
                dictionary['data'] = json['data']
                my_info.append(dictionary)
        except Exception as e:
            print('Oopsie')  # Can log the error here if you need to 
        finally:
            return my_info
    
    another_variable = api_call(x)
    

    【讨论】:

      猜你喜欢
      • 2023-02-23
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 1970-01-01
      相关资源
      最近更新 更多