Skip to content

Instantly share code, notes, and snippets.

@fabiobatalha
Last active November 14, 2017 13:19
Show Gist options
  • Save fabiobatalha/65afde2efa3e676221de54b41a0ed8bb to your computer and use it in GitHub Desktop.
Save fabiobatalha/65afde2efa3e676221de54b41a0ed8bb to your computer and use it in GitHub Desktop.
Google Analytics Usage Sample
#!/usr/bin/python
from __future__ import print_function
import argparse
import sys
from googleapiclient.errors import HttpError
from googleapiclient import sample_tools
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
SCOPE = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'scielo-metrics-f0d36c524725.json'
def get_service(api_name, api_version, scope, key_file_location):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scope: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account JSON key file.
Returns:
A service that is connected to the specified API.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
key_file_location, scopes=scope)
# Build the service object.
service = build(api_name, api_version, credentials=credentials)
return service
def get_profile_by_name(service, profile_name):
accounts = service.management().accounts().list().execute()
for item in accounts.get('items', []):
if item.get('name', '') != profile_name:
continue
account = item.get('id', None)
# Get a list of all the properties for the first account.
properties = service.management().webproperties().list(accountId=account).execute()
property = properties.get('items', [{}])[0].get('id', None)
profiles = service.management().profiles().list(accountId=account, webPropertyId=property).execute()
profile = profiles.get('items', [{}])[0].get('id', None)
return profile
service = get_service('analytics', 'v3', SCOPE, KEY_FILE_LOCATION)
profile = get_profile_by_name(service, 'www.scielo.br')
ids = 'ga:%s' % profile
metrics = "ga:visits"
dimensions = "ga:source"
filters = "ga:pagePath=~sci_arttext|sci_abstract;ga:pagePath=~0004-27302"
start_date = "2017-09-01"
end_date = "2017-09-30"
query = {
"ids": ids,
"start_date": start_date,
"end_date": end_date,
"metrics": metrics,
"dimensions": dimensions
}
if filters:
query['filters'] = filters
response = service.data().ga().get(**query).execute()
print("profile: %s" % profile)
print("metrics: %s" % metrics)
print("dimensions: %s" % dimensions)
print("filters: %s" % filters)
total = sum([int(i[1]) for i in response.get('rows', [])])
print(total)
for item in sorted(response.get('rows', []), key=lambda x: int(x[1]), reverse=True):
print(item[0], item[1], (100 * float(item[1]) / float(total)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment