blob: 10aa12c1192e5b825d3e8c5d0c3e11ed29d9acef [file] [log] [blame]
api.nickm@gmail.comd6b11062012-03-12 09:22:42 -07001#!/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
19Handles various tasks to do with logging, authentication and initialization.
20Mostly taken from Sergio :)
21
22Before You Begin:
23
24You must update the client_secrets.json file with a client id, client secret,
25and the redirect uri. You get these values by creating a new project
26in the Google APIs console and registering for OAuth2.0 for installed
27applications: https://code.google.com/apis/console
28
29Also all OAuth2.0 tokens are stored for resue in the file specified
30as 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
36import logging
37import os
38import sys
39from apiclient.discovery import build
40import gflags
41import httplib2
42from oauth2client.client import flow_from_clientsecrets
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040043from oauth2client.client import OOB_CALLBACK_URN
api.nickm@gmail.comd6b11062012-03-12 09:22:42 -070044from oauth2client.file import Storage
45from oauth2client.tools import run
46
47
48FLAGS = gflags.FLAGS
49
50# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
51# application, including client_id and client_secret. You get these values by
52# creating a new project in the Google APIs console and registering for
53# OAuth2.0 for installed applications: <https://code.google.com/apis/console>
54CLIENT_SECRETS = 'client_secrets.json'
55
56
57# Helpful message to display in the browser if the CLIENT_SECRETS file
58# is missing.
59MISSING_CLIENT_SECRETS_MESSAGE = """
60WARNING: Please configure OAuth 2.0
61
62To make this sample run you will need to populate the client_secrets.json file
63found at:
64
65 %s
66
67with information from the APIs Console <https://code.google.com/apis/console>.
68
69""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
70
71# Set up a Flow object to be used if we need to authenticate.
72FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
73 scope='https://www.googleapis.com/auth/analytics.readonly',
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040074 redirect_uri=OOB_CALLBACK_URN,
api.nickm@gmail.comd6b11062012-03-12 09:22:42 -070075 message=MISSING_CLIENT_SECRETS_MESSAGE)
76
77# The gflags module makes defining command-line options easy for applications.
78# Run this program with the '--help' argument to see all the flags that it
79# understands.
80gflags.DEFINE_enum('logging_level', 'ERROR',
81 ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
82 'Set the level of logging detail.')
83
84
85# Name of file that will store the access and refresh tokens to access
86# the API without having to login each time. Make sure this file is in
87# a secure place.
88TOKEN_FILE_NAME = 'analytics.dat'
89
90
91def process_flags(argv):
92 """Uses the command-line flags to set the logging level.
93
94 Args:
95 argv: List of command line arguments passed to the python script.
96 """
97
98 # Let the gflags module process the command-line arguments.
99 try:
100 argv = FLAGS(argv)
101 except gflags.FlagsError, e:
102 print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS)
103 sys.exit(1)
104
105 # Set the logging according to the command-line flag.
106 logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
107
108
109def initialize_service():
110 """Returns an instance of service from discovery data and does auth.
111
112 This method tries to read any existing OAuth 2.0 credentials from the
113 Storage object. If the credentials do not exist, new credentials are
114 obtained. The crdentials are used to authorize an http object. The
115 http object is used to build the analytics service object.
116
117 Returns:
118 An analytics v3 service object.
119 """
120
121 # Create an httplib2.Http object to handle our HTTP requests.
122 http = httplib2.Http()
123
124 # Prepare credentials, and authorize HTTP object with them.
125 storage = Storage(TOKEN_FILE_NAME)
126 credentials = storage.get()
127 if credentials is None or credentials.invalid:
128 credentials = run(FLOW, storage)
129
130 http = credentials.authorize(http)
131
132 # Retrieve service.
133 return build('analytics', 'v3', http=http)