blob: 25bd3e99816b0fff7b745848658f6bf5b5044b29 [file] [log] [blame]
Joe Gregorioba10e562011-12-08 13:16:42 -05001#!/usr/bin/python
2#
3# Copyright 2011 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"""Auxiliary file for AdSense Management API code samples.
18
19Handles various tasks to do with logging, authentication and initialization.
20"""
21
22__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
23
24import logging
25import os
26import sys
27from apiclient.discovery import build
28import gflags
29import httplib2
30from oauth2client.client import flow_from_clientsecrets
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040031from oauth2client.client import OOB_CALLBACK_URN
Joe Gregorioba10e562011-12-08 13:16:42 -050032from oauth2client.file import Storage
33from oauth2client.tools import run
34
35
36FLAGS = gflags.FLAGS
37
38# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
39# application, including client_id and client_secret, which are found
40# on the API Access tab on the Google APIs
41# Console <http://code.google.com/apis/console>
42CLIENT_SECRETS = 'client_secrets.json'
43
44# Helpful message to display in the browser if the CLIENT_SECRETS file
45# is missing.
46MISSING_CLIENT_SECRETS_MESSAGE = """
47WARNING: Please configure OAuth 2.0
48
49To make this sample run you will need to populate the client_secrets.json file
50found at:
51
52 %s
53
54with information from the APIs Console <https://code.google.com/apis/console>.
55
56""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
57
58# Set up a Flow object to be used if we need to authenticate.
59FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
60 scope='https://www.googleapis.com/auth/adsense.readonly',
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040061 redirect_uri=OOB_CALLBACK_URN,
Joe Gregorioba10e562011-12-08 13:16:42 -050062 message=MISSING_CLIENT_SECRETS_MESSAGE)
63
64# The gflags module makes defining command-line options easy for applications.
65# Run this program with the '--help' argument to see all the flags that it
66# understands.
67gflags.DEFINE_enum('logging_level', 'ERROR',
68 ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
69 'Set the level of logging detail.')
70
71
72def process_flags(argv):
73 """Uses the command-line flags to set the logging level."""
74
75 # Let the gflags module process the command-line arguments.
76 try:
77 argv = FLAGS(argv)
78 except gflags.FlagsError, e:
Joe Gregorio579c8c92012-02-07 14:31:01 -050079 print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS)
Joe Gregorioba10e562011-12-08 13:16:42 -050080 sys.exit(1)
81
82 # Set the logging according to the command-line flag.
83 logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
84
85
86def prepare_credentials():
87 """Handles auth. Reuses credentialss if available or runs the auth flow."""
88
89 # If the credentials don't exist or are invalid run through the native client
90 # flow. The Storage object will ensure that if successful the good
91 # Credentials will get written back to a file.
92 storage = Storage('adsense.dat')
93 credentials = storage.get()
94 if credentials is None or credentials.invalid:
95 credentials = run(FLOW, storage)
96 return credentials
97
98
99def retrieve_service(http):
100 """Retrieves an AdSense Management API service via the discovery service."""
101
102 # Construct a service object via the discovery service.
Joe Gregorio579c8c92012-02-07 14:31:01 -0500103 service = build("adsense", "v1.1", http=http)
Joe Gregorioba10e562011-12-08 13:16:42 -0500104 return service
105
106
107def initialize_service():
108 """Builds instance of service from discovery data and does auth."""
109
110 # Create an httplib2.Http object to handle our HTTP requests.
111 http = httplib2.Http()
112
113 # Prepare credentials, and authorize HTTP object with them.
114 credentials = prepare_credentials()
115 http = credentials.authorize(http)
116
117 # Retrieve service.
118 return retrieve_service(http)