python 的 for-loop API 响应中的错误处理

error handling in for-loop API response with python

任何人都可以帮助我的 GA 报告 API python 脚本中的错误处理和 for 循环吗?

我想要它做的是尝试从 API 请求数据 n 次(5 次),如果在拉动时出现错误数据(通常是“服务不可用”),记录它(log_progress 函数),但继续尝试 n 次;最终,如果尝试次数达到最大值并且 API 仍然返回错误,运行 一个 send_email 函数(它将通知我发现有些数据没有下载)并继续使用代码到下一个项目(脚本中有一个更宽的 for 循环,循环遍历不同的 GA views/days)。

for n in range(0, 5):
        try: #GA API request
            api_request = {
                'viewId': viewId,
                'dateRanges': {
                    'startDate': datetime.strftime(datetime.now() - timedelta(days = i),'%Y-%m-%d'),
                    'endDate': datetime.strftime(datetime.now() - timedelta(days = i),'%Y-%m-%d')
                },
                'dimensions': [{'name': 'ga:date'},{'name': 'ga:countryIsoCode'}],
                'metrics': [{'expression': 'ga:sessions'}],
                "samplingLevel":  "LARGE",                 
                "pageSize": 100000                                          }

            response = api_client.reports().batchGet(
                body={
                    'reportRequests': api_request
                }).execute()

        except HttpError as error:       
           log_progress('errorLog.txt' , error.resp.reason + " - code will try again")
           pass

不幸的是,由于 GA 错误的随机性,测试此脚本变得更加复杂,这在我手动 运行 手动编写脚本时似乎很少发生。

这样做的一种方法是创建一个 while 循环并从一开始就假设失败。只有当尝试次数达到最大值时,您才能在except块中唤起send_email()模块。

success = False
max_attempts = 5
attempts = 0

while not success and attempts < max_attempts:
    attempts += 1
    try: #GA API request
        api_request = {
            'viewId': viewId,
            'dateRanges': {
                'startDate': datetime.strftime(datetime.now() - timedelta(days = i),'%Y-%m-%d'),
                'endDate': datetime.strftime(datetime.now() - timedelta(days = i),'%Y-%m-%d')
            },
            'dimensions': [{'name': 'ga:date'},{'name': 'ga:countryIsoCode'}],
            'metrics': [{'expression': 'ga:sessions'}],
            "samplingLevel":  "LARGE",                 
            "pageSize": 100000                                          }

        response = api_client.reports().batchGet(
            body={
                'reportRequests': api_request
            }).execute()

        success = True

    except HttpError as error:       
        log_progress('errorLog.txt' , error.resp.reason + " - code will try again")
        if attempts == max_attempts:
            sent_email()

在这种情况下,如果在 5 次尝试后仍未成功,程序将停止尝试并继续执行其余逻辑。