Skip to content

Instantly share code, notes, and snippets.

@onyxfish
Created May 7, 2014 19:04
Show Gist options
  • Save onyxfish/a29032754f08477a2c25 to your computer and use it in GitHub Desktop.
Save onyxfish/a29032754f08477a2c25 to your computer and use it in GitHub Desktop.
First working google analytics example
#!/usr/bin/python
# -*- coding: utf-8 -*-
import argparse
import httplib2
import os
import sys
from apiclient import discovery
from apiclient.errors import HttpError
from oauth2client import client
from oauth2client.clientsecrets import InvalidClientSecretsError
from oauth2client.file import Storage
from oauth2client import tools
CLIENT_SECRETS = os.path.expanduser('~/.google_analytics_secrets.json')
DAT = os.path.expanduser('~/.google_analytics_auth.dat')
SERVICE_NAME = 'analytics'
SERVICE_VERSION = 'v3'
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'
NPR_ORG_LIVE_ID = '53470309'
def authorize(storage):
"""
Authorize with OAuth2.
"""
parent_parsers = [tools.argparser]
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=parent_parsers)
flags = parser.parse_args(sys.argv[1:])
try:
flow = client.flow_from_clientsecrets(
CLIENT_SECRETS,
scope=SCOPE
)
except InvalidClientSecretsError:
print 'Client secrets not found at %s' % CLIENT_SECRETS
return tools.run_flow(flow, storage, flags)
def get_service():
"""
Get a service we want to access.
"""
storage = Storage(DAT)
credentials = storage.get()
if not credentials or credentials.invalid:
credentials = authorize(storage)
http = credentials.authorize(http=httplib2.Http())
return discovery.build(SERVICE_NAME, SERVICE_VERSION, http=http)
def main():
"""
Query some things.
"""
service = get_service()
try:
results = query(service)
print_results(results)
except TypeError, error:
print ('There was an error in constructing your query : %s' % error)
except HttpError, error:
print ('Arg, there was an API error : %s : %s' % (error.resp.status, error._get_reason()))
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the application to re-authorize')
def query(service):
q = service.data().ga().get(
ids='ga:' + NPR_ORG_LIVE_ID,
start_date='2014-04-01',
end_date='2014-04-28',
metrics='ga:pageviews',
dimensions='ga:pagePath',
sort='-ga:pageviews',
start_index='1',
max_results='25'
)
return q.execute()
def print_results(results):
output = []
for header in results.get('columnHeaders'):
output.append('%30s' % header.get('name'))
print ''.join(output)
if results.get('rows', []):
for row in results.get('rows'):
output = []
for cell in row:
output.append('%30s' % cell)
print ''.join(output)
else:
print 'No Rows Found'
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment