Created
September 27, 2018 23:08
-
-
Save dat-boris/3ad2ea89062cc162546b74e021faa8d5 to your computer and use it in GitHub Desktop.
Get GA data via service account
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| from __future__ import print_function | |
| import os | |
| import sys | |
| from googleapiclient.errors import HttpError | |
| from googleapiclient import discovery | |
| from oauth2client.service_account import ServiceAccountCredentials | |
| from dateutil.parser import parse | |
| import datetime | |
| def main(): | |
| # Authenticate and construct service. | |
| # service, flags = sample_tools.init( | |
| # argv, 'analytics', 'v3', __doc__, __file__, parents=[argparser], | |
| # scope='https://www.googleapis.com/auth/analytics.readonly') | |
| # https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-py | |
| credentials = ServiceAccountCredentials.from_json_keyfile_name( | |
| # scope='https://www.googleapis.com/auth/analytics.readonly' | |
| os.getenv("HOME") + '/ga-service-account.json', | |
| ) | |
| # 'ga:13634188' | |
| table_id, real_time = | |
| # Build the service object. | |
| service = discovery.build('analytics', 'v3', credentials=credentials) | |
| if sys.argv[1] == 'realtime': | |
| results = service.data().realtime().get( | |
| ids=table_id, | |
| metrics='rt:pageviews', | |
| dimensions='rt:minutesAgo' | |
| ).execute() | |
| else: | |
| date_fmt = '%Y-%m-%d' | |
| current_date = datetime.datetime.now() | |
| results = service.data().ga().get( | |
| ids=table_id, | |
| start_date=current_date.strftime(date_fmt), | |
| end_date=current_date.strftime(date_fmt), | |
| metrics='ga:visits', | |
| dimensions='ga:hour,ga:minute', | |
| # sort='-ga:visits', | |
| sort='ga:hour,ga:minute', | |
| # filters='ga:medium==organic', | |
| start_index='1', | |
| max_results=60*24).execute() | |
| for row in results.get('rows'): | |
| print('\t'.join(row)) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment