Skip to content

Commit 652492b

Browse files
committed
Update coordinate, blogger and audit API samples to use apiclient.sample_tools.
Reviewed in https://codereview.appspot.com/10802043/.
1 parent eeace5f commit 652492b

3 files changed

Lines changed: 37 additions & 227 deletions

File tree

samples/audit/audit.py

Lines changed: 9 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -36,80 +36,18 @@
3636

3737
__author__ = 'rahulpaul@google.com (Rahul Paul)'
3838

39-
import gflags
40-
import httplib2
41-
import logging
42-
import os
4339
import pprint
4440
import sys
4541

46-
from apiclient.discovery import build
47-
from oauth2client.client import AccessTokenRefreshError
48-
from oauth2client.client import flow_from_clientsecrets
49-
from oauth2client.file import Storage
50-
from oauth2client.tools import run
51-
52-
53-
FLAGS = gflags.FLAGS
54-
55-
# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
56-
# application, including client_id and client_secret, which are found
57-
# on the API Access tab on the Google APIs
58-
# Console <http://code.google.com/apis/console>
59-
CLIENT_SECRETS = 'client_secrets.json'
60-
61-
# Helpful message to display in the browser if the CLIENT_SECRETS file
62-
# is missing.
63-
MISSING_CLIENT_SECRETS_MESSAGE = """
64-
WARNING: Please configure OAuth 2.0
65-
66-
To make this sample run you will need to populate the client_secrets.json file
67-
found at:
68-
69-
%s
70-
71-
with information from the APIs Console <https://code.google.com/apis/console>.
72-
73-
""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
74-
75-
# Set up a Flow object to be used if we need to authenticate.
76-
FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
77-
scope='https://www.googleapis.com/auth/apps/reporting/audit.readonly',
78-
message=MISSING_CLIENT_SECRETS_MESSAGE)
79-
80-
81-
# The gflags module makes defining command-line options easy for
82-
# applications. Run this program with the '--help' argument to see
83-
# all the flags that it understands.
84-
gflags.DEFINE_enum('logging_level', 'ERROR',
85-
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
86-
'Set the level of logging detail.')
42+
from oauth2client import client
43+
from apiclient import sample_tools
8744

8845

8946
def main(argv):
90-
# Let the gflags module process the command-line arguments
91-
try:
92-
argv = FLAGS(argv)
93-
except gflags.FlagsError, e:
94-
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
95-
sys.exit(1)
96-
97-
# Set the logging according to the command-line flag
98-
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
99-
100-
# If the Credentials don't exist or are invalid run through the native client
101-
# flow. The Storage object will ensure that if successful the good
102-
# Credentials will get written back to a file.
103-
storage = Storage('plus.dat')
104-
credentials = storage.get()
105-
106-
if credentials is None or credentials.invalid:
107-
credentials = run(FLOW, storage)
108-
109-
# Create an httplib2.Http object to handle our HTTP requests and authorize it
110-
# with our good Credentials.
111-
http = httplib2.Http()
112-
http = credentials.authorize(http)
47+
# Authenticate and construct service.
48+
service, flags = sample_tools.init(
49+
argv, 'audit', 'v1', __doc__, __file__,
50+
scope='https://www.googleapis.com/auth/apps/reporting/audit.readonly')
11351

11452
service = build('audit', 'v1', http=http)
11553

@@ -121,7 +59,7 @@ def main(argv):
12159
activity_list = activities.list(
12260
applicationId='207535951991', customerId='C01rv1wm7', maxResults='2',
12361
actorEmail='admin@enterprise-audit-clientlib.com').execute()
124-
print_activities(activity_list)
62+
pprint.pprint(activity_list)
12563

12664
# Now retrieve the next 2 events
12765
match = re.search('(?<=continuationToken=).+$', activity_list['next'])
@@ -133,9 +71,9 @@ def main(argv):
13371
applicationId='207535951991', customerId='C01rv1wm7',
13472
maxResults='2', actorEmail='admin@enterprise-audit-clientlib.com',
13573
continuationToken=next_token).execute()
136-
print_activities(activity_list)
74+
pprint.pprint(activity_list)
13775

138-
except AccessTokenRefreshError:
76+
except client.AccessTokenRefreshError:
13977
print ('The credentials have been revoked or expired, please re-run'
14078
'the application to re-authorize')
14179

samples/blogger/blogger.py

Lines changed: 16 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -34,109 +34,49 @@
3434

3535
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
3636

37-
import gflags
38-
import httplib2
39-
import logging
40-
import pprint
4137
import sys
42-
import os
4338

44-
from apiclient.discovery import build
45-
from oauth2client.file import Storage
46-
from oauth2client.client import AccessTokenRefreshError
47-
from oauth2client.client import flow_from_clientsecrets
48-
from oauth2client.tools import run
49-
50-
FLAGS = gflags.FLAGS
51-
52-
# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
53-
# application, including client_id and client_secret, which are found
54-
# on the API Access tab on the Google APIs
55-
# Console <http://code.google.com/apis/console>
56-
CLIENT_SECRETS = 'client_secrets.json'
57-
58-
# Helpful message to display in the browser if the CLIENT_SECRETS file
59-
# is missing.
60-
MISSING_CLIENT_SECRETS_MESSAGE = """
61-
WARNING: Please configure OAuth 2.0
62-
63-
To make this sample run you will need to populate the client_secrets.json file
64-
found at:
65-
66-
%s
67-
68-
with information from the APIs Console <https://code.google.com/apis/console>.
69-
70-
""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
71-
72-
# Set up a Flow object to be used if we need to authenticate.
73-
FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
74-
scope='https://www.googleapis.com/auth/blogger',
75-
message=MISSING_CLIENT_SECRETS_MESSAGE)
76-
77-
# The gflags module makes defining command-line options easy for
78-
# applications. Run this program with the '--help' argument to see
79-
# all the flags that it understands.
80-
gflags.DEFINE_enum('logging_level', 'ERROR',
81-
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
82-
'Set the level of logging detail.')
39+
from oauth2client import client
40+
from apiclient import sample_tools
8341

8442

8543
def main(argv):
86-
# Let the gflags module process the command-line arguments
87-
try:
88-
argv = FLAGS(argv)
89-
except gflags.FlagsError, e:
90-
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
91-
sys.exit(1)
92-
93-
# Set the logging according to the command-line flag
94-
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
95-
96-
# If the Credentials don't exist or are invalid run through the native client
97-
# flow. The Storage object will ensure that if successful the good
98-
# Credentials will get written back to a file.
99-
storage = Storage('blogger.dat')
100-
credentials = storage.get()
101-
if credentials is None or credentials.invalid:
102-
credentials = run(FLOW, storage)
103-
104-
# Create an httplib2.Http object to handle our HTTP requests and authorize it
105-
# with our good Credentials.
106-
http = httplib2.Http()
107-
http = credentials.authorize(http)
44+
# Authenticate and construct service.
45+
service, flags = sample_tools.init(
46+
argv, 'plus', 'v1', __doc__, __file__,
47+
scope='https://www.googleapis.com/auth/blogger')
10848

109-
service = build("blogger", "v2", http=http)
49+
service = build('blogger', 'v2', http=http)
11050

11151
try:
11252

11353
users = service.users()
11454

11555
# Retrieve this user's profile information
116-
thisuser = users.get(userId="self").execute(http=http)
117-
print "This user's display name is: %s" % thisuser['displayName']
56+
thisuser = users.get(userId='self').execute(http=http)
57+
print 'This user\'s display name is: %s' % thisuser['displayName']
11858

11959
# Retrieve the list of Blogs this user has write privileges on
120-
thisusersblogs = users.blogs().list(userId="self").execute()
60+
thisusersblogs = users.blogs().list(userId='self').execute()
12161
for blog in thisusersblogs['items']:
122-
print "The blog named \"%s\" is at: %s" % (blog['name'], blog['url'])
62+
print 'The blog named \'%s\' is at: %s' % (blog['name'], blog['url'])
12363

12464
posts = service.posts()
12565

12666
# List the posts for each blog this user has
12767
for blog in thisusersblogs['items']:
128-
print "The posts for %s:" % blog['name']
68+
print 'The posts for %s:' % blog['name']
12969
request = posts.list(blogId=blog['id'])
13070
while request != None:
13171
posts_doc = request.execute(http=http)
13272
if 'items' in posts_doc and not (posts_doc['items'] is None):
13373
for post in posts_doc['items']:
134-
print " %s (%s)" % (post['title'], post['url'])
74+
print ' %s (%s)' % (post['title'], post['url'])
13575
request = posts.list_next(request, posts_doc)
13676

137-
except AccessTokenRefreshError:
138-
print ("The credentials have been revoked or expired, please re-run"
139-
"the application to re-authorize")
77+
except client.AccessTokenRefreshError:
78+
print ('The credentials have been revoked or expired, please re-run'
79+
'the application to re-authorize')
14080

14181
if __name__ == '__main__':
14282
main(sys.argv)

samples/coordinate/coordinate.py

Lines changed: 12 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -38,91 +38,23 @@
3838

3939
__author__ = 'zachn@google.com (Zach Newell)'
4040

41-
import gflags
42-
import httplib2
43-
import logging
44-
import os
41+
import argparse
4542
import pprint
4643
import sys
4744

48-
from apiclient.discovery import build
49-
from oauth2client.client import AccessTokenRefreshError
50-
from oauth2client.client import flow_from_clientsecrets
51-
from oauth2client.file import Storage
52-
from oauth2client.tools import run
45+
from oauth2client import client
46+
from apiclient import sample_tools
5347

54-
55-
FLAGS = gflags.FLAGS
56-
57-
58-
# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
59-
# application, including client_id and client_secret, which are found
60-
# on the API Access tab on the Google APIs
61-
# Console <http://code.google.com/apis/console>
62-
CLIENT_SECRETS = 'client_secrets.json'
63-
64-
# Helpful message to display in the browser if the CLIENT_SECRETS file
65-
# is missing.
66-
MISSING_CLIENT_SECRETS_MESSAGE = """
67-
WARNING: Please configure OAuth 2.0
68-
69-
To make this sample run you will need to populate the client_secrets.json file
70-
found at:
71-
72-
%s
73-
74-
with information from the APIs Console <https://code.google.com/apis/console>.
75-
76-
""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
77-
78-
FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
79-
scope='https://www.googleapis.com/auth/coordinate',
80-
message=MISSING_CLIENT_SECRETS_MESSAGE)
81-
82-
83-
# The gflags module makes defining command-line options easy for
84-
# applications. Run this program with the '--help' argument to see
85-
# all the flags that it understands.
86-
gflags.DEFINE_enum('logging_level', 'ERROR',
87-
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
88-
'Set the level of logging detail.')
89-
90-
gflags.DEFINE_string('teamId', None, 'Coordinate Team ID', short_name='t')
91-
92-
# Create a validator for the teamId flag.
93-
gflags.RegisterValidator('teamId',
94-
lambda value: value is not None,
95-
message='--teamId must be defined.',
96-
flag_values=FLAGS)
97-
98-
# Make the flag mandatory
99-
gflags.MarkFlagAsRequired('teamId')
48+
# Declare command-line flags.
49+
argparser = argparse.ArgumentParser(add_help=False)
50+
argparser.add_argument('teamId', help='Coordinate Team ID')
10051

10152

10253
def main(argv):
103-
# Let the gflags module process the command-line arguments
104-
try:
105-
argv = FLAGS(argv)
106-
except gflags.FlagsError, e:
107-
print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS)
108-
sys.exit(1)
109-
110-
# Set the logging according to the command-line flag
111-
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
112-
113-
# If the Credentials don't exist or are invalid run through the native client
114-
# flow. The Storage object will ensure that if successful the good
115-
# Credentials will get written back to a file.
116-
storage = Storage('coordinate.dat')
117-
credentials = storage.get()
118-
119-
if credentials is None or credentials.invalid:
120-
credentials = run(FLOW, storage)
121-
122-
# Create an httplib2.Http object to handle our HTTP requests and authorize it
123-
# with our good Credentials.
124-
http = httplib2.Http()
125-
http = credentials.authorize(http)
54+
# Authenticate and construct service.
55+
service, flags = sample_tools.init(
56+
argv, 'coordinate', 'v1', __doc__, __file__, parents=[argparser],
57+
scope='https://www.googleapis.com/auth/coordinate')
12658

12759
service = build('coordinate', 'v1', http=http)
12860

@@ -142,7 +74,7 @@ def main(argv):
14274
# Insert a job and store the results
14375
insert_result = service.jobs().insert(body='',
14476
title='Google Campus',
145-
teamId=FLAGS.teamId,
77+
teamId=flags.teamId,
14678
address='1600 Amphitheatre Parkway Mountain View, CA 94043',
14779
lat='37.422120',
14880
lng='122.084429',
@@ -153,7 +85,7 @@ def main(argv):
15385

15486
# Close the job
15587
update_result = service.jobs().update(body='',
156-
teamId=FLAGS.teamId,
88+
teamId=flags.teamId,
15789
jobId=insert_result['id'],
15890
progress='COMPLETED').execute()
15991

0 commit comments

Comments
 (0)