简体   繁体   中英

Google Analytics Python API call resulting in UnboundLocalError

I have a python script that calls the google analytics api once for everyday that I'm trying to get data for. However, on some calls I'm apparently receiving nothing. That or I'm handling errors incorrectly. Here is the function that I'm using to call the api.

    def run_query(hour_in_dim, start_date, sessions_writer, connection_error_count, pageToken=None):
        # Try to run api request for one day. Wait 10 seconds if "service is currently unavailable."
        try:
            traffic_results = get_api_query(analytics, start_date, start_date, pageToken)
        except HttpError as err:
            if err.resp.status in [503]:
                print("Sleeping, api service temporarily unavailable.")
                time.sleep(10)
                run_query(hour_in_dim, start_date, sessions_writer, connection_error_count, pageToken)
            else:
                raise
        except ConnectionResetError:
            connection_error_count += 1
            time.sleep(10)
            if connection_error_count > 2:
                raise
            else:
                run_query(hour_in_dim, start_date, sessions_writer, connection_error_count, pageToken)


        # TODO: solve random occurances of "UnboundLocalError: local variable 'traffic_results' referenced before assignment"
        dimensions_ga = traffic_results['reports'][0]['columnHeader']['dimensions']
        rows = traffic_results['reports'][0]['data']['rows']

The Unbound Local Error is coming from the second line from the bottom where I call traffic results and try to assign it to the dimensions_ga variable.

I believe the problem is that I was using recursion instead of a loop. I used the sample code provided here:

https://developers.google.com/analytics/devguides/reporting/core/v3/errors

also changing "except HttpError, error:" to "except HttpError as error" for python 3.

Not sure the best way to test this, as error is not manually reproducible..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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