简体   繁体   English

使用 python 的 for 循环 API 响应中的错误处理

[英]error handling in for-loop API response with python

Can anyone please help with error handling & for loop in my GA reporting API python script?任何人都可以在我的 GA 报告 API python 脚本中帮助处理错误和 for 循环吗?

What I would like it to do is attempt requesting data from the API an n number of times (5 times), if there is an error while pulling the data (generally "Service Unavailable"), log it ( log_progress function), but keep trying for n number of times;我想做的是尝试从 API 请求数据n次(5 次),如果在提取数据时出现错误(通常是“服务不可用”),记录它( log_progress函数),但保持尝试n次; eventually, if the number of attempts reaches the maximum amount and the API is still returning an error, run a send_email function (which will notify me that some data was not downloaded) and move on with the code to the next item (there is a wider for loop in the script which loops through different GA views/days).最终,如果尝试次数达到最大数量并且 API 仍然返回错误,请运行send_email function(它会通知我一些数据未下载)并继续使用代码到下一个项目(有脚本中更宽的 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

Unfortunately tesing this script is made more complicated by the randomness of GA errors which rarely seem to happen while I'm running the script manually.不幸的是,由于 GA 错误的随机性,测试这个脚本变得更加复杂,当我手动运行脚本时,这种错误似乎很少发生。

One way of doing so is by creating a while loop and assume failure from the start.这样做的一种方法是创建一个while循环并从一开始就假设失败。 Only when the attempt number hits your maximum, you can evoke the send_email() module in the except block.只有当尝试次数达到最大值时,您才能在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()

In this scenario, if there was no success after 5 attempts the program will stop trying and will continue executing the rest of the logic.在这种情况下,如果尝试 5 次后仍未成功,程序将停止尝试并继续执行逻辑的 rest。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM