【问题标题】:error handling in for-loop API response with python使用python的for循环API响应中的错误处理
【发布时间】:2020-08-10 08:17:19
【问题描述】:

谁能帮助我的 GA 报告 API python 脚本中的错误处理和 for 循环?

如果在提取数据时出错(通常是“服务不可用”),我希望它尝试从 API 请求数据 n 次(5 次) ,记录它(log_progress 函数),但继续尝试 n 次;最终,如果尝试次数达到最大值并且 API 仍然返回错误,请运行 send_email 函数(它会通知我一些数据未下载)并继续执行代码以下一项(脚本中有一个更宽的 for 循环,循环不同的 GA 视图/天)。

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 错误的随机性,在我手动运行脚本时似乎很少发生这种随机性,这使得测试该脚本变得更加复杂。

【问题讨论】:

  • 为什么在 except 块中 log_progess 之后有一个 passpass 被视为空语句并被解释器忽略。由于您已经在 except HttpError as error: 中有代码,因此您不需要 pass 那里

标签: python for-loop exception error-handling google-analytics-api


【解决方案1】:

这样做的一种方法是创建一个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 次后仍未成功,程序将停止尝试并继续执行其余的逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 2016-03-31
    相关资源
    最近更新 更多