Dreamstime

Monday, 29 February 2016

My First Google OAuth2 Python Program

Below is the code for my first Google OAuth2 Python program. The last time I had a look at it was something like 6 months ago - that long already? As I recall, the sample script file blogger.py that was bundled in 'google-api-python-client-samples-1.2.zip', if I am not mistaken, by Google didn't work. I had to debug it myself to get it working.

What this program does is to print out the user's Google login name, the list of blogs at Blogger.com that is associated with this account and the list of blog entries for each blog. The OAuth2 login credentials is named 'plus.dat' and it must be located in the same directory as this Python script file.

I ran this script file under Python 2.4 with some customisation made to the Google API Python Client Library Version 1.2.

I hope somebody will find this useful.

The Source Code

==== BEGIN ====

#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Simple command-line sample for Blogger.

Command-line application that retrieves the users blogs and posts.

Usage:
  $ python blogger.py

You can also get help on all the command-line flags the program understands
by running:

  $ python blogger.py --help

To get detailed log output run:

  $ python blogger.py --logging_level=DEBUG
"""

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

import sys

from oauth2client import client # , file, tools  # file and tools added by Chuah TC
from apiclient import sample_tools
# Chuah TC:  6-6-2015
from apiclient.discovery import build
from httplib2 import Http

# Chuah TC:  7-6-2015 - To fix [No handlers could be found for logger "oauth2client.util"] error message.
import logging
# 


def main(argv):
  # Chuah TC:  7-6-2015 - To fix [No handlers could be found for logger "oauth2client.util"] error message.
  logging.basicConfig(filename='debug.log',level=logging.WARNING)


  # Authenticate and construct service.
  print "--- 111 ---"
  credentials, service, flags = sample_tools.init(
      argv, 'plus', 'v1', __doc__, __file__,
      # CTC: OAuth 2.0 scope information for the Blogger API
      scope='https://www.googleapis.com/auth/blogger')

  print "--- 222 ---"
  
  # Chuah TC  Date: 6-6-2015
  # store = file.Storage('plus.dat')
  #credentials = store.get()
  #if not credentials or credentials.invalid:
  #    flow = client.flow_from_clientsecrets('client_secret.json', 'https://www.googleapis.com/auth/blogger')
  #    credentials = tools.run(flow, store)
  # DRIVE = build('drive', 'v2', http=credentials.authorize(Http()))  
  #
  
  service = build('blogger', 'v3', http=credentials.authorize(Http()))
  
  print "--- 333 ---"

  try:

      print "--- 444 ---"
      users = service.users()
      print "--- 555 ---"

      # Retrieve this user's profile information
      # thisuser = users.get(userId='self').execute(http=http)
      # Chuah TC Date: 6-6-2015
      thisuser = users.get(userId='self').execute(credentials.authorize(Http()))
      print "--- 666 ---"

      
      print 'This user\'s display name is: %s' % thisuser['displayName']

      # Retrieve the list of Blogs this user has write privileges on
      # thisusersblogs = users.blogs().list(userId='self').execute()  - for Blogger v2
      thisusersblogs = service.blogs().listByUser(userId='self').execute()
      for blog in thisusersblogs['items']:
        print 'The blog named \'%s\' is at: %s' % (blog['name'], blog['url'])

      posts = service.posts()

      # List the posts for each blog this user has
      for blog in thisusersblogs['items']:
        print 'The posts for %s:' % blog['name']
        request = posts.list(blogId=blog['id'])
        while request != None:
          posts_doc = request.execute(credentials.authorize(Http()))
          if 'items' in posts_doc and not (posts_doc['items'] is None):
            for post in posts_doc['items']:
              print '  %s (%s)' % (post['title'], post['url'])
          request = posts.list_next(request, posts_doc)

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run'
      'the application to re-authorize')
# CTC: Test      
#   except Exception, e:
#     print ('Communication error 2 '), e

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


==== END ====

0 comments:

Post a Comment