api.nickm@gmail.com | d6b1106 | 2012-03-12 09:22:42 -0700 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # |
| 3 | # Copyright 2012 Google Inc. All Rights Reserved. |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | # you may not use this file except in compliance with the License. |
| 7 | # You may obtain a copy of the License at |
| 8 | # |
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | # See the License for the specific language governing permissions and |
| 15 | # limitations under the License. |
| 16 | |
| 17 | """Utilities for Analytics API code samples. |
| 18 | |
| 19 | Handles various tasks to do with logging, authentication and initialization. |
| 20 | Mostly taken from Sergio :) |
| 21 | |
| 22 | Before You Begin: |
| 23 | |
| 24 | You must update the client_secrets.json file with a client id, client secret, |
| 25 | and the redirect uri. You get these values by creating a new project |
| 26 | in the Google APIs console and registering for OAuth2.0 for installed |
| 27 | applications: https://code.google.com/apis/console |
| 28 | |
| 29 | Also all OAuth2.0 tokens are stored for resue in the file specified |
| 30 | as TOKEN_FILE_NAME. You can modify this file name if you wish. |
| 31 | """ |
| 32 | |
| 33 | __author__ = ('sergio.gomes@google.com (Sergio Gomes)' |
| 34 | 'api.nickm@gmail.com (Nick Mihailovski)') |
| 35 | |
| 36 | import logging |
| 37 | import os |
| 38 | import sys |
| 39 | from apiclient.discovery import build |
| 40 | import gflags |
| 41 | import httplib2 |
| 42 | from oauth2client.client import flow_from_clientsecrets |
| 43 | from oauth2client.file import Storage |
| 44 | from oauth2client.tools import run |
| 45 | |
| 46 | |
| 47 | FLAGS = gflags.FLAGS |
| 48 | |
| 49 | # CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this |
| 50 | # application, including client_id and client_secret. You get these values by |
| 51 | # creating a new project in the Google APIs console and registering for |
| 52 | # OAuth2.0 for installed applications: <https://code.google.com/apis/console> |
| 53 | CLIENT_SECRETS = 'client_secrets.json' |
| 54 | |
| 55 | |
| 56 | # Helpful message to display in the browser if the CLIENT_SECRETS file |
| 57 | # is missing. |
| 58 | MISSING_CLIENT_SECRETS_MESSAGE = """ |
| 59 | WARNING: Please configure OAuth 2.0 |
| 60 | |
| 61 | To make this sample run you will need to populate the client_secrets.json file |
| 62 | found at: |
| 63 | |
| 64 | %s |
| 65 | |
| 66 | with information from the APIs Console <https://code.google.com/apis/console>. |
| 67 | |
| 68 | """ % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS) |
| 69 | |
| 70 | # Set up a Flow object to be used if we need to authenticate. |
| 71 | FLOW = flow_from_clientsecrets(CLIENT_SECRETS, |
| 72 | scope='https://www.googleapis.com/auth/analytics.readonly', |
| 73 | message=MISSING_CLIENT_SECRETS_MESSAGE) |
| 74 | |
| 75 | # The gflags module makes defining command-line options easy for applications. |
| 76 | # Run this program with the '--help' argument to see all the flags that it |
| 77 | # understands. |
| 78 | gflags.DEFINE_enum('logging_level', 'ERROR', |
| 79 | ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], |
| 80 | 'Set the level of logging detail.') |
| 81 | |
| 82 | |
| 83 | # Name of file that will store the access and refresh tokens to access |
| 84 | # the API without having to login each time. Make sure this file is in |
| 85 | # a secure place. |
| 86 | TOKEN_FILE_NAME = 'analytics.dat' |
| 87 | |
| 88 | |
| 89 | def process_flags(argv): |
| 90 | """Uses the command-line flags to set the logging level. |
| 91 | |
| 92 | Args: |
| 93 | argv: List of command line arguments passed to the python script. |
| 94 | """ |
| 95 | |
| 96 | # Let the gflags module process the command-line arguments. |
| 97 | try: |
| 98 | argv = FLAGS(argv) |
| 99 | except gflags.FlagsError, e: |
| 100 | print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS) |
| 101 | sys.exit(1) |
| 102 | |
| 103 | # Set the logging according to the command-line flag. |
| 104 | logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level)) |
| 105 | |
| 106 | |
| 107 | def initialize_service(): |
| 108 | """Returns an instance of service from discovery data and does auth. |
| 109 | |
| 110 | This method tries to read any existing OAuth 2.0 credentials from the |
| 111 | Storage object. If the credentials do not exist, new credentials are |
| 112 | obtained. The crdentials are used to authorize an http object. The |
| 113 | http object is used to build the analytics service object. |
| 114 | |
| 115 | Returns: |
| 116 | An analytics v3 service object. |
| 117 | """ |
| 118 | |
| 119 | # Create an httplib2.Http object to handle our HTTP requests. |
| 120 | http = httplib2.Http() |
| 121 | |
| 122 | # Prepare credentials, and authorize HTTP object with them. |
| 123 | storage = Storage(TOKEN_FILE_NAME) |
| 124 | credentials = storage.get() |
| 125 | if credentials is None or credentials.invalid: |
| 126 | credentials = run(FLOW, storage) |
| 127 | |
| 128 | http = credentials.authorize(http) |
| 129 | |
| 130 | # Retrieve service. |
| 131 | return build('analytics', 'v3', http=http) |