blob: da67afe780d022d9571ce939c905d9048c3a4af6 [file] [log] [blame]
Joe Gregorio077363d2011-10-31 09:12:56 -04001#!/usr/bin/python2.4
2# -*- coding: utf-8 -*-
3#
4# Copyright (C) 2010 Google Inc.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18"""Simple command-line sample for Blogger.
19
20Command-line application that retrieves the users blogs and posts.
21
22Usage:
23 $ python blogger.py
24
25You can also get help on all the command-line flags the program understands
26by running:
27
28 $ python blogger.py --help
29
30To get detailed log output run:
31
32 $ python blogger.py --logging_level=DEBUG
33"""
34
35__author__ = 'jcgregorio@google.com (Joe Gregorio)'
36
37import gflags
38import httplib2
39import logging
40import pprint
41import sys
42import os
43
44from apiclient.discovery import build
45from oauth2client.file import Storage
46from oauth2client.client import AccessTokenRefreshError
47from oauth2client.client import flow_from_clientsecrets
48from oauth2client.tools import run
49
50FLAGS = 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>
56CLIENT_SECRETS = 'client_secrets.json'
57
58# Helpful message to display in the browser if the CLIENT_SECRETS file
59# is missing.
60MISSING_CLIENT_SECRETS_MESSAGE = """
61WARNING: Please configure OAuth 2.0
62
63To make this sample run you will need to populate the client_secrets.json file
64found at:
65
66%s
67
68with 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.
73FLOW = 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.
80gflags.DEFINE_enum('logging_level', 'ERROR',
81 ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
82 'Set the level of logging detail.')
83
84
85def 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)
108
109 service = build("blogger", "v2", http=http)
110
111 try:
112
113 users = service.users()
114
115 # Retrieve this user's profile information
116 thisuser = users.get(userId="self").execute(http)
117 print "This user's display name is: %s" % thisuser['displayName']
118
119 # Retrieve the list of Blogs this user has write privileges on
120 thisusersblogs = users.blogs().list(userId="self").execute()
121 for blog in thisusersblogs['items']:
122 print "The blog named \"%s\" is at: %s" % (blog['name'], blog['url'])
123
124 posts = service.posts()
125
126 # List the posts for each blog this user has
127 for blog in thisusersblogs['items']:
128 print "The posts for %s:" % blog['name']
129 request = posts.list(blogId=blog['id'])
130 while request != None:
131 posts_doc = request.execute(http)
132 if 'items' in posts_doc and not (posts_doc['items'] is None):
133 for post in posts_doc['items']:
134 print " %s (%s)" % (post['title'], post['url'])
135 request = posts.list_next(request, posts_doc)
136
137 except AccessTokenRefreshError:
138 print ("The credentials have been revoked or expired, please re-run"
139 "the application to re-authorize")
140
141if __name__ == '__main__':
142 main(sys.argv)