Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(31)

Unified Diff: samples/analytics/management_v3_reference.py

Issue 5494058: Adding py sample for google analytics core reporting api (Closed)
Patch Set: more typo fixes Created 12 years ago
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « samples/analytics/hello_analytics_api_v3.py ('k') | samples/analytics/sample_utils.py » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: samples/analytics/management_v3_reference.py
===================================================================
old mode 100644
new mode 100755
--- a/samples/analytics/management_v3_reference.py
+++ b/samples/analytics/management_v3_reference.py
@@ -1,7 +1,7 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
-# Copyright 2011 Google Inc. All Rights Reserved.
+# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -32,79 +32,55 @@
API Python Getting Started guide here:
http://code.google.com/apis/analytics/docs/mgmt/v3/mgmtPython.html
-Usage:
+Before You Begin:
-Before you begin, you should register your application as an installed
-application to get your own Project / OAUth2 Client ID / Secret:
-https://code.google.com/apis/console
+Update the client_secrets.json file
-Learn more about registering your Analytics Application here:
-http://code.google.com/apis/analytics/docs/mgmt/v3/mgmtPython.html#authorize
+ You must update the clients_secrets.json file with a client id, client
+ secret, and the redirect uri. You get these values by creating a new project
+ in the Google APIs console and registering for OAuth2.0 for installed
+ applications: https://code.google.com/apis/console
- $ python analytics.py
+ Learn more about registering your analytics application here:
+ http://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html
+
+Sample Usage:
+
+ $ python management_v3_reference.py
Also you can also get help on all the command-line flags the program
understands by running:
- $ python analytics.py --help
+ $ python management_v3_reference.py --help
"""
-__author__ = 'api.nickm@ (Nick Mihailovski)'
+__author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
import sys
+import sample_utils
-from apiclient.discovery import build
from apiclient.errors import HttpError
-
-import gflags
-import httplib2
-
from oauth2client.client import AccessTokenRefreshError
-from oauth2client.client import OAuth2WebServerFlow
-from oauth2client.file import Storage
-from oauth2client.tools import run
-
-FLAGS = gflags.FLAGS
-
-
-# Remember to get your own client_id / client_secret in the
-# Google API developer console: https://code.google.com/apis/console
-FLOW = OAuth2WebServerFlow(
- client_id='INSERT_YOUR_CLIENT_ID_HERE',
- client_secret='INSERT_YOUR_CLIENT_SECRET_HERE',
- scope='https://www.googleapis.com/auth/analytics.readonly',
- user_agent='analytics-api-v3-awesomeness')
-
-TOKEN_FILE_NAME = 'analytics.dat'
def main(argv):
- # Let the gflags module process the command-line arguments
- try:
- argv = FLAGS(argv)
- except gflags.FlagsError, e:
- print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
- sys.exit(1)
+ sample_utils.process_flags(argv)
- # Manage re-using tokens.
- storage = Storage(TOKEN_FILE_NAME)
- credentials = storage.get()
- if not credentials or credentials.invalid:
- # Get a new token.
- credentials = run(FLOW, storage)
+ # Authenticate and construct service.
+ service = sample_utils.initialize_service()
- # Build an authorized service object.
- http = httplib2.Http()
- http = credentials.authorize(http)
- service = build('analytics', 'v3', http=http)
-
- # Traverse the Management hiearchy and print results.
+ # Traverse the Management hiearchy and print results or handle errors.
try:
traverse_hiearchy(service)
+ except TypeError, error:
+ # Handle errors in constructing a query.
+ print ('There was an error in constructing your query : %s' % error)
+
except HttpError, error:
- print ('Arg, there was an API error : %s %s : %s' %
- (error.resp.status, error.resp.reason, error._get_reason()))
+ # Handle API errors.
+ print ('Arg, there was an API error : %s : %s' %
+ (error.resp.status, error._get_reason()))
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run'
@@ -126,18 +102,16 @@
HttpError: If an error occured when accessing the API.
AccessTokenRefreshError: If the current token was invalid.
"""
- view = View()
accounts = service.management().accounts().list().execute()
-
- view.print_accounts(accounts)
+ print_accounts(accounts)
if accounts.get('items'):
firstAccountId = accounts.get('items')[0].get('id')
webproperties = service.management().webproperties().list(
accountId=firstAccountId).execute()
- view.print_webproperties(webproperties)
+ print_webproperties(webproperties)
if webproperties.get('items'):
firstWebpropertyId = webproperties.get('items')[0].get('id')
@@ -145,7 +119,7 @@
accountId=firstAccountId,
webPropertyId=firstWebpropertyId).execute()
- view.print_profiles(profiles)
+ print_profiles(profiles)
if profiles.get('items'):
firstProfileId = profiles.get('items')[0].get('id')
@@ -154,226 +128,285 @@
webPropertyId=firstWebpropertyId,
profileId=firstProfileId).execute()
- view.print_goals(goals)
+ print_goals(goals)
- view.print_segments(service.management().segments().list().execute())
+ print_segments(service.management().segments().list().execute())
-class View(object):
- """Utility class to print various Management API collections."""
+def print_accounts(accounts_response):
+ """Prints all the account info in the Accounts Collection.
- def print_accounts(self, accounts_list):
- """Prints all the account info in the Accounts Collection."""
+ Args:
+ accounts_response: The response object returned from querying the Accounts
+ collection.
+ """
- print '------ Account Collection -------'
- self.print_pagination_info(accounts_list)
+ print '------ Account Collection -------'
+ print_pagination_info(accounts_response)
+ print
+
+ for account in accounts_response.get('items', []):
+ print 'Account ID = %s' % account.get('id')
+ print 'Kind = %s' % account.get('kind')
+ print 'Self Link = %s' % account.get('selfLink')
+ print 'Account Name = %s' % account.get('name')
+ print 'Created = %s' % account.get('created')
+ print 'Updated = %s' % account.get('updated')
+
+ child_link = account.get('childLink')
+ print 'Child link href = %s' % child_link.get('href')
+ print 'Child link type = %s' % child_link.get('type')
+ print
+ else:
+ print 'No accounts found.\n'
+
+
+def print_webproperties(webproperties_response):
+ """Prints all the web property info in the WebProperties collection.
+
+ Args:
+ webproperties_response: The response object returned from querying the
+ Webproperties collection.
+ """
+
+ print '------ Web Properties Collection -------'
+ print_pagination_info(webproperties_response)
+ print
+
+ for webproperty in webproperties_response.get('items', []):
+ print 'Kind = %s' % webproperty.get('kind')
+ print 'Account ID = %s' % webproperty.get('accountId')
+ print 'Web Property ID = %s' % webproperty.get('id')
+ print ('Internal Web Property ID = %s' %
+ webproperty.get('internalWebPropertyId'))
+
+ print 'Website URL = %s' % webproperty.get('websiteUrl')
+ print 'Created = %s' % webproperty.get('created')
+ print 'Updated = %s' % webproperty.get('updated')
+
+ print 'Self Link = %s' % webproperty.get('selfLink')
+ parent_link = webproperty.get('parentLink')
+ print 'Parent link href = %s' % parent_link.get('href')
+ print 'Parent link type = %s' % parent_link.get('type')
+ child_link = webproperty.get('childLink')
+ print 'Child link href = %s' % child_link.get('href')
+ print 'Child link type = %s' % child_link.get('type')
+ print
+ else:
+ print 'No webproperties found.\n'
+
+
+def print_profiles(profiles_response):
+ """Prints all the profile info in the Profiles Collection.
+
+ Args:
+ profiles_response: The response object returned from querying the
+ Profiles collection.
+ """
+
+ print '------ Profiles Collection -------'
+ print_pagination_info(profiles_response)
+ print
+
+ for profile in profiles_response.get('items', []):
+ print 'Kind = %s' % profile.get('kind')
+ print 'Account ID = %s' % profile.get('accountId')
+ print 'Web Property ID = %s' % profile.get('webPropertyId')
+ print ('Internal Web Property ID = %s' %
+ profile.get('internalWebPropertyId'))
+ print 'Profile ID = %s' % profile.get('id')
+ print 'Profile Name = %s' % profile.get('name')
+
+ print 'Currency = %s' % profile.get('currency')
+ print 'Timezone = %s' % profile.get('timezone')
+ print 'Default Page = %s' % profile.get('defaultPage')
+
+ print ('Exclude Query Parameters = %s' %
+ profile.get('excludeQueryParameters'))
+ print ('Site Search Category Parameters = %s' %
+ profile.get('siteSearchCategoryParameters'))
+ print ('Site Search Query Parameters = %s' %
+ profile.get('siteSearchQueryParameters'))
+
+ print 'Created = %s' % profile.get('created')
+ print 'Updated = %s' % profile.get('updated')
+
+ print 'Self Link = %s' % profile.get('selfLink')
+ parent_link = profile.get('parentLink')
+ print 'Parent link href = %s' % parent_link.get('href')
+ print 'Parent link type = %s' % parent_link.get('type')
+ child_link = profile.get('childLink')
+ print 'Child link href = %s' % child_link.get('href')
+ print 'Child link type = %s' % child_link.get('type')
+ print
+ else:
+ print 'No profiles found.\n'
+
+
+def print_goals(goals_response):
+ """Prints all the goal info in the Goals collection.
+
+ Args:
+ goals_response: The response object returned from querying the Goals
+ collection
+ """
+
+ print '------ Goals Collection -------'
+ print_pagination_info(goals_response)
+ print
+
+ for goal in goals_response.get('items', []):
+ print 'Goal ID = %s' % goal.get('id')
+ print 'Kind = %s' % goal.get('kind')
+ print 'Self Link = %s' % goal.get('selfLink')
+
+ print 'Account ID = %s' % goal.get('accountId')
+ print 'Web Property ID = %s' % goal.get('webPropertyId')
+ print ('Internal Web Property ID = %s' %
+ goal.get('internalWebPropertyId'))
+ print 'Profile ID = %s' % goal.get('profileId')
+
+ print 'Goal Name = %s' % goal.get('name')
+ print 'Goal Value = %s' % goal.get('value')
+ print 'Goal Active = %s' % goal.get('active')
+ print 'Goal Type = %s' % goal.get('type')
+
+ print 'Created = %s' % goal.get('created')
+ print 'Updated = %s' % goal.get('updated')
+
+ parent_link = goal.get('parentLink')
+ print 'Parent link href = %s' % parent_link.get('href')
+ print 'Parent link type = %s' % parent_link.get('type')
+
+ # Print the goal details depending on the type of goal.
+ if goal.get('urlDestinationDetails'):
+ print_url_destination_goal_details(
+ goal.get('urlDestinationDetails'))
+
+ elif goal.get('visitTimeOnSiteDetails'):
+ print_visit_time_on_site_goal_details(
+ goal.get('visitTimeOnSiteDetails'))
+
+ elif goal.get('visitNumPagesDetails'):
+ print_visit_num_pages_goal_details(
+ goal.get('visitNumPagesDetails'))
+
+ elif goal.get('eventDetails'):
+ print_event_goal_details(goal.get('eventDetails'))
+
+ print
+ else:
+ print 'No goals found.\n'
+
+
+def print_url_destination_goal_details(goal_details):
+ """Prints all the URL Destination goal type info.
+
+ Args:
+ goal_details: The details portion of the goal response.
+ """
+
+ print '------ Url Destination Goal -------'
+ print 'Goal URL = %s' % goal_details.get('url')
+ print 'Case Sensitive = %s' % goal_details.get('caseSensitive')
+ print 'Match Type = %s' % goal_details.get('matchType')
+ print 'First Step Required = %s' % goal_details.get('firstStepRequired')
+
+ print '------ Url Destination Goal Steps -------'
+ for goal_step in goal_details.get('steps', []):
+ print 'Step Number = %s' % goal_step.get('number')
+ print 'Step Name = %s' % goal_step.get('name')
+ print 'Step URL = %s' % goal_step.get('url')
+ else:
+ print 'No Steps Configured'
+
+
+def print_visit_time_on_site_goal_details(goal_details):
+ """Prints all the Visit Time On Site goal type info.
+
+ Args:
+ goal_details: The details portion of the goal response.
+ """
+
+ print '------ Visit Time On Site Goal -------'
+ print 'Comparison Type = %s' % goal_details.get('comparisonType')
+ print 'comparison Value = %s' % goal_details.get('comparisonValue')
+
+
+def print_visit_num_pages_goal_details(goal_details):
+ """Prints all the Visit Num Pages goal type info.
+
+ Args:
+ goal_details: The details portion of the goal response.
+ """
+
+ print '------ Visit Num Pages Goal -------'
+ print 'Comparison Type = %s' % goal_details.get('comparisonType')
+ print 'comparison Value = %s' % goal_details.get('comparisonValue')
+
+
+def print_event_goal_details(goal_details):
+ """Prints all the Event goal type info.
+
+ Args:
+ goal_details: The details portion of the goal response.
+ """
+
+ print '------ Event Goal -------'
+ print 'Use Event Value = %s' % goal_details.get('useEventValue')
+
+ for event_condition in goal_details.get('eventConditions', []):
+ event_type = event_condition.get('type')
+ print 'Type = %s' % event_type
+
+ if event_type in ('CATEGORY', 'ACTION', 'LABEL'):
+ print 'Match Type = %s' % event_condition.get('matchType')
+ print 'Expression = %s' % event_condition.get('expression')
+ else: # VALUE type.
+ print 'Comparison Type = %s' % event_condition.get('comparisonType')
+ print 'Comparison Value = %s' % event_condition.get('comparisonValue')
+
+
+def print_segments(segments_response):
+ """Prints all the segment info in the Segments collection.
+
+ Args:
+ segments_response: The response object returned from querying the
+ Segments collection.
+ """
+
+ print '------ Segments Collection -------'
+ print_pagination_info(segments_response)
+ print
+
+ for segment in segments_response.get('items', []):
+ print 'Segment ID = %s' % segment.get('id')
+ print 'Kind = %s' % segment.get('kind')
+ print 'Self Link = %s' % segment.get('selfLink')
+ print 'Name = %s' % segment.get('name')
+ print 'Definition = %s' % segment.get('definition')
+ print 'Created = %s' % segment.get('created')
+ print 'Updated = %s' % segment.get('updated')
print
- for account in accounts_list.get('items'):
- print 'Account ID = %s' % account.get('id')
- print 'Kind = %s' % account.get('kind')
- print 'Self Link = %s' % account.get('selfLink')
- print 'Account Name = %s' % account.get('name')
- print 'Created = %s' % account.get('created')
- print 'Updated = %s' % account.get('updated')
- child_link = account.get('childLink')
- print 'Child link href = %s' % child_link.get('href')
- print 'Child link type = %s' % child_link.get('type')
- print
+def print_pagination_info(management_response):
+ """Prints common pagination details.
- def print_webproperties(self, webproperties_list):
- """Prints all the web property info in the WebProperties Collection."""
+ Args:
+ management_response: The common reponse object for each collection in the
+ Management API.
+ """
- print '------ Web Properties Collection -------'
- self.print_pagination_info(webproperties_list)
- print
+ print 'Items per page = %s' % management_response.get('itemsPerPage')
+ print 'Total Results = %s' % management_response.get('totalResults')
+ print 'Start Index = %s' % management_response.get('startIndex')
- for webproperty in webproperties_list.get('items'):
- print 'Kind = %s' % webproperty.get('kind')
- print 'Account ID = %s' % webproperty.get('accountId')
- print 'Web Property ID = %s' % webproperty.get('id')
- print ('Internal Web Property ID = %s' %
- webproperty.get('internalWebPropertyId'))
-
- print 'Website URL = %s' % webproperty.get('websiteUrl')
- print 'Created = %s' % webproperty.get('created')
- print 'Updated = %s' % webproperty.get('updated')
-
- print 'Self Link = %s' % webproperty.get('selfLink')
- parent_link = webproperty.get('parentLink')
- print 'Parent link href = %s' % parent_link.get('href')
- print 'Parent link type = %s' % parent_link.get('type')
- child_link = webproperty.get('childLink')
- print 'Child link href = %s' % child_link.get('href')
- print 'Child link type = %s' % child_link.get('type')
- print
-
- def print_profiles(self, profiles_list):
- """Prints all the profile info in the Profiles Collection."""
-
- print '------ Profiles Collection -------'
- self.print_pagination_info(profiles_list)
- print
-
- for profile in profiles_list.get('items'):
- print 'Kind = %s' % profile.get('kind')
- print 'Account ID = %s' % profile.get('accountId')
- print 'Web Property ID = %s' % profile.get('webPropertyId')
- print ('Internal Web Property ID = %s' %
- profile.get('internalWebPropertyId'))
- print 'Profile ID = %s' % profile.get('id')
- print 'Profile Name = %s' % profile.get('name')
-
- print 'Currency = %s' % profile.get('currency')
- print 'Timezone = %s' % profile.get('timezone')
- print 'Default Page = %s' % profile.get('defaultPage')
-
- print ('Exclude Query Parameters = %s' %
- profile.get('excludeQueryParameters'))
- print ('Site Search Category Parameters = %s' %
- profile.get('siteSearchCategoryParameters'))
- print ('Site Search Query Parameters = %s' %
- profile.get('siteSearchQueryParameters'))
-
- print 'Created = %s' % profile.get('created')
- print 'Updated = %s' % profile.get('updated')
-
- print 'Self Link = %s' % profile.get('selfLink')
- parent_link = profile.get('parentLink')
- print 'Parent link href = %s' % parent_link.get('href')
- print 'Parent link type = %s' % parent_link.get('type')
- child_link = profile.get('childLink')
- print 'Child link href = %s' % child_link.get('href')
- print 'Child link type = %s' % child_link.get('type')
- print
-
- def print_goals(self, goals_list):
- """Prints all the goal info in the Goals Collection."""
-
- print '------ Goals Collection -------'
- self.print_pagination_info(goals_list)
- print
-
- for goal in goals_list.get('items'):
- print 'Goal ID = %s' % goal.get('id')
- print 'Kind = %s' % goal.get('kind')
- print 'Self Link = %s' % goal.get('selfLink')
-
- print 'Account ID = %s' % goal.get('accountId')
- print 'Web Property ID = %s' % goal.get('webPropertyId')
- print ('Internal Web Property ID = %s' %
- goal.get('internalWebPropertyId'))
- print 'Profile ID = %s' % goal.get('profileId')
-
- print 'Goal Name = %s' % goal.get('name')
- print 'Goal Value = %s' % goal.get('value')
- print 'Goal Active = %s' % goal.get('active')
- print 'Goal Type = %s' % goal.get('type')
-
- print 'Created = %s' % goal.get('created')
- print 'Updated = %s' % goal.get('updated')
-
- parent_link = goal.get('parentLink')
- print 'Parent link href = %s' % parent_link.get('href')
- print 'Parent link type = %s' % parent_link.get('type')
-
- # Print the goal details depending on the type of goal.
- if goal.get('urlDestinationDetails'):
- self.print_url_destination_goal_details(
- goal.get('urlDestinationDetails'))
-
- elif goal.get('visitTimeOnSiteDetails'):
- self.print_visit_time_on_site_goal_details(
- goal.get('visitTimeOnSiteDetails'))
-
- elif goal.get('visitNumPagesDetails'):
- self.print_visit_num_pages_goal_details(
- goal.get('visitNumPagesDetails'))
-
- elif goal.get('eventDetails'):
- self.print_event_goal_details(goal.get('eventDetails'))
-
- print
-
- def print_url_destination_goal_details(self, goal_details):
- """Prints all the URL Destination goal type info."""
-
- print '------ Url Destination Goal -------'
- print 'Goal URL = %s' % goal_details.get('url')
- print 'Case Sensitive = %s' % goal_details.get('caseSensitive')
- print 'Match Type = %s' % goal_details.get('matchType')
- print 'First Step Required = %s' % goal_details.get('firstStepRequired')
-
- print '------ Url Destination Goal Steps -------'
- if goal_details.get('steps'):
- for goal_step in goal_details.get('steps'):
- print 'Step Number = %s' % goal_step.get('number')
- print 'Step Name = %s' % goal_step.get('name')
- print 'Step URL = %s' % goal_step.get('url')
- else:
- print 'No Steps Configured'
-
- def print_visit_time_on_site_goal_details(self, goal_details):
- """Prints all the Visit Time On Site goal type info."""
-
- print '------ Visit Time On Site Goal -------'
- print 'Comparison Type = %s' % goal_details.get('comparisonType')
- print 'comparison Value = %s' % goal_details.get('comparisonValue')
-
- def print_visit_num_pages_goal_details(self, goal_details):
- """Prints all the Visit Num Pages goal type info."""
-
- print '------ Visit Num Pages Goal -------'
- print 'Comparison Type = %s' % goal_details.get('comparisonType')
- print 'comparison Value = %s' % goal_details.get('comparisonValue')
-
- def print_event_goal_details(self, goal_details):
- """Prints all the Event goal type info."""
-
- print '------ Event Goal -------'
- print 'Use Event Value = %s' % goal_details.get('useEventValue')
-
- for event_condition in goal_details.get('eventConditions'):
- event_type = event_condition.get('type')
- print 'Type = %s' % event_type
-
- if event_type in ('CATEGORY', 'ACTION', 'LABEL'):
- print 'Match Type = %s' % event_condition.get('matchType')
- print 'Expression = %s' % event_condition.get('expression')
- else: # VALUE type.
- print 'Comparison Type = %s' % event_condition.get('comparisonType')
- print 'Comparison Value = %s' % event_condition.get('comparisonValue')
-
- def print_segments(self, segments_list):
- """Prints all the segment info in the Segments Collection."""
-
- print '------ Segments Collection -------'
- self.print_pagination_info(segments_list)
- print
-
- for segment in segments_list.get('items'):
- print 'Segment ID = %s' % segment.get('id')
- print 'Kind = %s' % segment.get('kind')
- print 'Self Link = %s' % segment.get('selfLink')
- print 'Name = %s' % segment.get('name')
- print 'Definition = %s' % segment.get('definition')
- print 'Created = %s' % segment.get('created')
- print 'Updated = %s' % segment.get('updated')
- print
-
- def print_pagination_info(self, mgmt_list):
- """Prints common pagination details."""
-
- print 'Items per page = %s' % mgmt_list.get('itemsPerPage')
- print 'Total Results = %s' % mgmt_list.get('totalResults')
- print 'Start Index = %s' % mgmt_list.get('startIndex')
-
- # These only have values if other result pages exist.
- if mgmt_list.get('previousLink'):
- print 'Previous Link = %s' % mgmt_list.get('previousLink')
- if mgmt_list.get('nextLink'):
- print 'Next Link = %s' % mgmt_list.get('nextLink')
+ # These only have values if other result pages exist.
+ if management_response.get('previousLink'):
+ print 'Previous Link = %s' % management_response.get('previousLink')
+ if management_response.get('nextLink'):
+ print 'Next Link = %s' % management_response.get('nextLink')
if __name__ == '__main__':
« no previous file with comments | « samples/analytics/hello_analytics_api_v3.py ('k') | samples/analytics/sample_utils.py » ('j') | no next file with comments »

Powered by Google App Engine
RSS Feeds Recent Issues | This issue
This is Rietveld f62528b