Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(641)

Side by Side Diff: samples/analytics/sample_utils.py

Issue 5494058: Adding py sample for google analytics core reporting api (Closed)
Patch Set: adding new hello world sample, moving to common auth util, cleaning up errors Created 13 years, 2 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « samples/analytics/management_v3_reference.py ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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 # Let the gflags module process the command-line arguments.
93 try:
94 argv = FLAGS(argv)
95 except gflags.FlagsError, e:
96 print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS)
97 sys.exit(1)
98
99 # Set the logging according to the command-line flag.
100 logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
101
102
103 def prepare_credentials():
104 """Handles auth. Reuses credentialss if available or runs the auth flow."""
105
106 # If the credentials don't exist or are invalid run through the native client
107 # flow. The Storage object will ensure that if successful the good
108 # Credentials will get written back to a file.
109 storage = Storage(TOKEN_FILE_NAME)
110 credentials = storage.get()
111 if credentials is None or credentials.invalid:
112 credentials = run(FLOW, storage)
113 return credentials
114
115
116 def retrieve_service(http):
117 """Retrieves an AdSense Management API service via the discovery service."""
118
119 # Construct a service object via the discovery service.
120 return build('analytics', 'v3', http=http)
121
122
123 def initialize_service():
124 """Builds instance of service from discovery data and does auth."""
125
126 # Create an httplib2.Http object to handle our HTTP requests.
127 http = httplib2.Http()
128
129 # Prepare credentials, and authorize HTTP object with them.
130 credentials = prepare_credentials()
131 http = credentials.authorize(http)
132
133 # Retrieve service.
134 return retrieve_service(http)
OLDNEW
« no previous file with comments | « samples/analytics/management_v3_reference.py ('k') | no next file » | no next file with comments »

Powered by Google App Engine
RSS Feeds Recent Issues | This issue
This is Rietveld f62528b