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