updating analytics sample to migrate auth to new client lib flows

reviewed here: https://codereview.appspot.com/9749044/
This commit is contained in:
api.nickm@gmail.com
2013-05-29 11:19:55 -07:00
parent fba580ba1d
commit 5ae38c8296
5 changed files with 42 additions and 165 deletions

View File

@@ -1,4 +1,4 @@
Command-line samples for producting reports with the Analytics API. Command-line samples for producing reports with the Analytics API.
api: analytics api: analytics
keywords: cmdline keywords: cmdline

View File

@@ -33,7 +33,7 @@ Update the client_secrets.json file
applications: https://code.google.com/apis/console applications: https://code.google.com/apis/console
Learn more about registering your analytics application here: Learn more about registering your analytics application here:
http://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html http://developers.google.com/analytics/devguides/reporting/core/v3/gdataAuthorization
Supply your TABLE_ID Supply your TABLE_ID
@@ -45,7 +45,11 @@ Supply your TABLE_ID
Sample Usage: Sample Usage:
$ python core_reporting_v3_reference.py $ python core_reporting_v3_reference.py ga:xxxx
Where the table ID is used to identify from which Google Anlaytics profile
to retrieve data. This ID is in the format ga:xxxx where xxxx is the
profile ID.
Also you can also get help on all the command-line flags the program Also you can also get help on all the command-line flags the program
understands by running: understands by running:
@@ -55,28 +59,29 @@ understands by running:
__author__ = 'api.nickm@gmail.com (Nick Mihailovski)' __author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
import argparse
import sys import sys
import sample_utils
from apiclient.errors import HttpError from apiclient.errors import HttpError
from apiclient import sample_tools
from oauth2client.client import AccessTokenRefreshError from oauth2client.client import AccessTokenRefreshError
# Declare command-line flags.
# The table ID is used to identify from which Google Anlaytics profile argparser = argparse.ArgumentParser(add_help=False)
# to retrieve data. This ID is in the format ga:xxxx where xxxx is the argparser.add_argument('table_id', type=str,
# profile ID. help=('The table ID of the profile you wish to access. '
TABLE_ID = 'INSERT_YOUR_TABLE_ID_HERE' 'Format is ga:xxx where xxx is your profile ID.'))
def main(argv): def main(argv):
sample_utils.process_flags(argv)
# Authenticate and construct service. # Authenticate and construct service.
service = sample_utils.initialize_service() service, flags = sample_tools.init(
argv, 'analytics', 'v3', __doc__, __file__, parents=[argparser],
scope='https://www.googleapis.com/auth/analytics.readonly')
# Try to make a request to the API. Print the results or handle errors. # Try to make a request to the API. Print the results or handle errors.
try: try:
results = get_api_query(service).execute() results = get_api_query(service, flags.table_id).execute()
print_results(results) print_results(results)
except TypeError, error: except TypeError, error:
@@ -94,15 +99,16 @@ def main(argv):
'the application to re-authorize') 'the application to re-authorize')
def get_api_query(service): def get_api_query(service, table_id):
"""Returns a query object to retrieve data from the Core Reporting API. """Returns a query object to retrieve data from the Core Reporting API.
Args: Args:
service: The service object built by the Google API Python client library. service: The service object built by the Google API Python client library.
table_id: str The table ID form which to retrieve data.
""" """
return service.data().ga().get( return service.data().ga().get(
ids=TABLE_ID, ids=table_id,
start_date='2012-01-01', start_date='2012-01-01',
end_date='2012-01-15', end_date='2012-01-15',
metrics='ga:visits', metrics='ga:visits',

View File

@@ -43,18 +43,19 @@ understands by running:
__author__ = 'api.nickm@gmail.com (Nick Mihailovski)' __author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
import argparse
import sys import sys
import sample_utils
from apiclient.errors import HttpError from apiclient.errors import HttpError
from apiclient import sample_tools
from oauth2client.client import AccessTokenRefreshError from oauth2client.client import AccessTokenRefreshError
def main(argv): def main(argv):
sample_utils.process_flags(argv)
# Authenticate and construct service. # Authenticate and construct service.
service = sample_utils.initialize_service() service, flags = sample_tools.init(
argv, 'analytics', 'v3', __doc__, __file__,
scope='https://www.googleapis.com/auth/analytics.readonly')
# Try to make a request to the API. Print the results or handle errors. # Try to make a request to the API. Print the results or handle errors.
try: try:

View File

@@ -28,9 +28,6 @@ first account, then all the profiles for the first web property and finally
all the goals for the first profile. The sample then prints all the all the goals for the first profile. The sample then prints all the
user's advanced segments. user's advanced segments.
To read an indepth discussion on how this file works, check out the Management
API Python Getting Started guide here:
http://code.google.com/apis/analytics/docs/mgmt/v3/mgmtPython.html
Before You Begin: Before You Begin:
@@ -42,7 +39,7 @@ Update the client_secrets.json file
applications: https://code.google.com/apis/console applications: https://code.google.com/apis/console
Learn more about registering your analytics application here: Learn more about registering your analytics application here:
http://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtAuthorization
Sample Usage: Sample Usage:
@@ -56,18 +53,19 @@ understands by running:
__author__ = 'api.nickm@gmail.com (Nick Mihailovski)' __author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
import argparse
import sys import sys
import sample_utils
from apiclient.errors import HttpError from apiclient.errors import HttpError
from apiclient import sample_tools
from oauth2client.client import AccessTokenRefreshError from oauth2client.client import AccessTokenRefreshError
def main(argv): def main(argv):
sample_utils.process_flags(argv)
# Authenticate and construct service. # Authenticate and construct service.
service = sample_utils.initialize_service() service, flags = sample_tools.init(
argv, 'analytics', 'v3', __doc__, __file__,
scope='https://www.googleapis.com/auth/analytics.readonly')
# Traverse the Management hiearchy and print results or handle errors. # Traverse the Management hiearchy and print results or handle errors.
try: try:
@@ -157,7 +155,8 @@ def print_accounts(accounts_response):
print 'Child link href = %s' % child_link.get('href') print 'Child link href = %s' % child_link.get('href')
print 'Child link type = %s' % child_link.get('type') print 'Child link type = %s' % child_link.get('type')
print print
else:
if not accounts_response.get('items'):
print 'No accounts found.\n' print 'No accounts found.\n'
@@ -192,7 +191,8 @@ def print_webproperties(webproperties_response):
print 'Child link href = %s' % child_link.get('href') print 'Child link href = %s' % child_link.get('href')
print 'Child link type = %s' % child_link.get('type') print 'Child link type = %s' % child_link.get('type')
print print
else:
if not webproperties_response.get('items'):
print 'No webproperties found.\n' print 'No webproperties found.\n'
@@ -239,7 +239,8 @@ def print_profiles(profiles_response):
print 'Child link href = %s' % child_link.get('href') print 'Child link href = %s' % child_link.get('href')
print 'Child link type = %s' % child_link.get('type') print 'Child link type = %s' % child_link.get('type')
print print
else:
if not profiles_response.get('items'):
print 'No profiles found.\n' print 'No profiles found.\n'
@@ -295,7 +296,8 @@ def print_goals(goals_response):
print_event_goal_details(goal.get('eventDetails')) print_event_goal_details(goal.get('eventDetails'))
print print
else:
if not goals_response.get('items'):
print 'No goals found.\n' print 'No goals found.\n'
@@ -317,7 +319,8 @@ def print_url_destination_goal_details(goal_details):
print 'Step Number = %s' % goal_step.get('number') print 'Step Number = %s' % goal_step.get('number')
print 'Step Name = %s' % goal_step.get('name') print 'Step Name = %s' % goal_step.get('name')
print 'Step URL = %s' % goal_step.get('url') print 'Step URL = %s' % goal_step.get('url')
else:
if not goal_details.get('steps'):
print 'No Steps Configured' print 'No Steps Configured'

View File

@@ -1,133 +0,0 @@
#!/usr/bin/python
#
# 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for Analytics API code samples.
Handles various tasks to do with logging, authentication and initialization.
Mostly taken from Sergio :)
Before You Begin:
You must update the client_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
Also all OAuth2.0 tokens are stored for resue in the file specified
as TOKEN_FILE_NAME. You can modify this file name if you wish.
"""
__author__ = ('sergio.gomes@google.com (Sergio Gomes)'
'api.nickm@gmail.com (Nick Mihailovski)')
import logging
import os
import sys
from apiclient.discovery import build
import gflags
import httplib2
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import OOB_CALLBACK_URN
from oauth2client.file import Storage
from oauth2client.tools import run
FLAGS = gflags.FLAGS
# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
# application, including client_id and client_secret. 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>
CLIENT_SECRETS = 'client_secrets.json'
# Helpful message to display in the browser if the CLIENT_SECRETS file
# is missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:
%s
with information from the APIs Console <https://code.google.com/apis/console>.
""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
# Set up a Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
scope='https://www.googleapis.com/auth/analytics.readonly',
redirect_uri=OOB_CALLBACK_URN,
message=MISSING_CLIENT_SECRETS_MESSAGE)
# The gflags module makes defining command-line options easy for applications.
# Run this program with the '--help' argument to see all the flags that it
# understands.
gflags.DEFINE_enum('logging_level', 'ERROR',
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
'Set the level of logging detail.')
# Name of file that will store the access and refresh tokens to access
# the API without having to login each time. Make sure this file is in
# a secure place.
TOKEN_FILE_NAME = 'analytics.dat'
def process_flags(argv):
"""Uses the command-line flags to set the logging level.
Args:
argv: List of command line arguments passed to the python script.
"""
# 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)
# Set the logging according to the command-line flag.
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
def initialize_service():
"""Returns an instance of service from discovery data and does auth.
This method tries to read any existing OAuth 2.0 credentials from the
Storage object. If the credentials do not exist, new credentials are
obtained. The crdentials are used to authorize an http object. The
http object is used to build the analytics service object.
Returns:
An analytics v3 service object.
"""
# Create an httplib2.Http object to handle our HTTP requests.
http = httplib2.Http()
# Prepare credentials, and authorize HTTP object with them.
storage = Storage(TOKEN_FILE_NAME)
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run(FLOW, storage)
http = credentials.authorize(http)
# Retrieve service.
return build('analytics', 'v3', http=http)