Last active
August 29, 2015 14:08
-
-
Save chriskief/e07db1c574a8613b495b to your computer and use it in GitHub Desktop.
This file contains 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
import httplib2 | |
from googleapiclient.discovery import build | |
from googleapiclient.http import HttpError | |
from oauth2client.client import SignedJwtAssertionCredentials | |
def get_metrics(): | |
# load the service account key | |
# this key is managed here - https://console.developers.google.com/project | |
filename = 'YOUR-KEY-FILE.p12' | |
f = file(filename, 'rb') | |
key = f.read() | |
f.close() | |
# create the credentials | |
credentials = SignedJwtAssertionCredentials('[email protected]', key, scope='https://www.googleapis.com/auth/analytics.readonly') | |
# authorize the http instance with these credentials | |
http = httplib2.Http() | |
http = credentials.authorize(http) | |
# construct a resource object for interacting with an api | |
service = build('analytics', 'v3', http=http) | |
# build the query | |
# your profile id can be found by heading to google analytics, selecting your profile, clicking the admin button, | |
# and then clicking view settings under the view column, the id is labelled 'View ID' | |
# you can see the available metrics here: | |
# https://developers.google.com/analytics/devguides/reporting/core/dimsmets | |
api_query = service.data().ga().get( | |
ids='ga:YOUR_PROFILE_ID_NOT_UA', | |
metrics='ga:users, ga:sessions, ga:avgSessionDuration, ga:pageviews, ga:pageviewsPerSession, ga:percentNewSessions, ga:bounceRate', | |
start_date='2014-01-01', | |
end_date='2015-01-01' | |
) | |
# default value | |
metrics = None | |
# run it | |
try: | |
result = api_query.execute() | |
values = result['rows'][0] | |
# covert the average session to minutes and seconds | |
minutes, seconds = divmod(int(float(values[2])), 60) | |
# the order below is the same as the order the metrics were listed above | |
metrics = { | |
'users': values[0], | |
'sessions': values[1], | |
'avg_session': '%d:%02d' % (minutes, seconds), | |
'pageviews': values[3], | |
'pages_session': '%.2f' % float(values[4]), | |
'new_sessions': '%.2f' % float(values[5]) + '%', | |
'returning_sessions': '%.2f' % (100 - float(values[5])) + '%', | |
'bounce_rate': '%.2f' % float(values[6]) + '%' | |
} | |
# handle errors in constructing a query | |
except TypeError, error: | |
print ('There was an error in constructing your query : %s' % error) | |
# handle api service errors | |
except HttpError, error: | |
print ('There was an API error : %s : %s' % (error.resp.status, error._get_reason())) | |
return metrics |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment