PageRenderTime 91ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/samples/plus/plus.py

https://bitbucket.org/ts/google-api-python-client
Python | 138 lines | 91 code | 8 blank | 39 comment | 1 complexity | fd4bf8965307dad167db1aa94b1153bc MD5 | raw file
Possible License(s): Apache-2.0
  1. #!/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. """Simple command-line sample for the Google+ API.
  18. Command-line application that retrieves the users latest content and
  19. then adds a new entry.
  20. Usage:
  21. $ python plus.py
  22. You can also get help on all the command-line flags the program understands
  23. by running:
  24. $ python plus.py --help
  25. To get detailed log output run:
  26. $ python plus.py --logging_level=DEBUG
  27. """
  28. __author__ = 'jcgregorio@google.com (Joe Gregorio)'
  29. import gflags
  30. import httplib2
  31. import logging
  32. import os
  33. import pprint
  34. import sys
  35. from apiclient.discovery import build
  36. from oauth2client.file import Storage
  37. from oauth2client.client import AccessTokenRefreshError
  38. from oauth2client.client import flow_from_clientsecrets
  39. from oauth2client.tools import run
  40. FLAGS = gflags.FLAGS
  41. # CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
  42. # application, including client_id and client_secret, which are found
  43. # on the API Access tab on the Google APIs
  44. # Console <http://code.google.com/apis/console>
  45. CLIENT_SECRETS = 'client_secrets.json'
  46. # Helpful message to display in the browser if the CLIENT_SECRETS file
  47. # is missing.
  48. MISSING_CLIENT_SECRETS_MESSAGE = """
  49. WARNING: Please configure OAuth 2.0
  50. To make this sample run you will need to populate the client_secrets.json file
  51. found at:
  52. %s
  53. with information from the APIs Console <https://code.google.com/apis/console>.
  54. """ % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
  55. # Set up a Flow object to be used if we need to authenticate.
  56. FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
  57. scope='https://www.googleapis.com/auth/plus.me',
  58. message=MISSING_CLIENT_SECRETS_MESSAGE)
  59. # The gflags module makes defining command-line options easy for
  60. # applications. Run this program with the '--help' argument to see
  61. # all the flags that it understands.
  62. gflags.DEFINE_enum('logging_level', 'ERROR',
  63. ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
  64. 'Set the level of logging detail.')
  65. def main(argv):
  66. # Let the gflags module process the command-line arguments
  67. try:
  68. argv = FLAGS(argv)
  69. except gflags.FlagsError, e:
  70. print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
  71. sys.exit(1)
  72. # Set the logging according to the command-line flag
  73. logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
  74. # If the Credentials don't exist or are invalid run through the native client
  75. # flow. The Storage object will ensure that if successful the good
  76. # Credentials will get written back to a file.
  77. storage = Storage('plus.dat')
  78. credentials = storage.get()
  79. if credentials is None or credentials.invalid:
  80. credentials = run(FLOW, storage)
  81. # Create an httplib2.Http object to handle our HTTP requests and authorize it
  82. # with our good Credentials.
  83. http = httplib2.Http()
  84. http = credentials.authorize(http)
  85. service = build("plus", "v1", http=http)
  86. try:
  87. person = service.people().get(userId='me').execute(http=http)
  88. print "Got your ID: %s" % person['displayName']
  89. print
  90. print "%-040s -> %s" % ("[Activitity ID]", "[Content]")
  91. # Don't execute the request until we reach the paging loop below
  92. request = service.activities().list(
  93. userId=person['id'], collection='public')
  94. # Loop over every activity and print the ID and a short snippet of content.
  95. while ( request != None ):
  96. activities_doc = request.execute()
  97. for item in activities_doc.get('items', []):
  98. print '%-040s -> %s' % (item['id'], item['object']['content'][:30])
  99. request = service.activities().list_next(request, activities_doc)
  100. except AccessTokenRefreshError:
  101. print ("The credentials have been revoked or expired, please re-run"
  102. "the application to re-authorize")
  103. if __name__ == '__main__':
  104. main(sys.argv)