你怎么能当功能中断函数内部返回良好的数据?

问题描述 投票:1回答:1

我从一个Web API(使用python)收集的数据和我使用的是循环都要经过数千调用的API。功能运行良好,但我的电脑去睡觉和互联网连接丢失。我在数据存储为dictionarys的列表,同时调用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个回答
2
投票

刚刚/包装在一个try /除外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)
© www.soinside.com 2019 - 2024. All rights reserved.