sample_tools.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. # Copyright 2014 Google Inc. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Utilities for making samples.
  15. Consolidates a lot of code commonly repeated in sample applications.
  16. """
  17. from __future__ import absolute_import
  18. __author__ = "jcgregorio@google.com (Joe Gregorio)"
  19. __all__ = ["init"]
  20. import argparse
  21. import os
  22. from googleapiclient import discovery
  23. from googleapiclient.http import build_http
  24. def init(
  25. argv, name, version, doc, filename, scope=None, parents=[], discovery_filename=None
  26. ):
  27. """A common initialization routine for samples.
  28. Many of the sample applications do the same initialization, which has now
  29. been consolidated into this function. This function uses common idioms found
  30. in almost all the samples, i.e. for an API with name 'apiname', the
  31. credentials are stored in a file named apiname.dat, and the
  32. client_secrets.json file is stored in the same directory as the application
  33. main file.
  34. Args:
  35. argv: list of string, the command-line parameters of the application.
  36. name: string, name of the API.
  37. version: string, version of the API.
  38. doc: string, description of the application. Usually set to __doc__.
  39. file: string, filename of the application. Usually set to __file__.
  40. parents: list of argparse.ArgumentParser, additional command-line flags.
  41. scope: string, The OAuth scope used.
  42. discovery_filename: string, name of local discovery file (JSON). Use when discovery doc not available via URL.
  43. Returns:
  44. A tuple of (service, flags), where service is the service object and flags
  45. is the parsed command-line flags.
  46. """
  47. try:
  48. from oauth2client import client, file, tools
  49. except ImportError:
  50. raise ImportError(
  51. "googleapiclient.sample_tools requires oauth2client. Please install oauth2client and try again."
  52. )
  53. if scope is None:
  54. scope = "https://www.googleapis.com/auth/" + name
  55. # Parser command-line arguments.
  56. parent_parsers = [tools.argparser]
  57. parent_parsers.extend(parents)
  58. parser = argparse.ArgumentParser(
  59. description=doc,
  60. formatter_class=argparse.RawDescriptionHelpFormatter,
  61. parents=parent_parsers,
  62. )
  63. flags = parser.parse_args(argv[1:])
  64. # Name of a file containing the OAuth 2.0 information for this
  65. # application, including client_id and client_secret, which are found
  66. # on the API Access tab on the Google APIs
  67. # Console <http://code.google.com/apis/console>.
  68. client_secrets = os.path.join(os.path.dirname(filename), "client_secrets.json")
  69. # Set up a Flow object to be used if we need to authenticate.
  70. flow = client.flow_from_clientsecrets(
  71. client_secrets, scope=scope, message=tools.message_if_missing(client_secrets)
  72. )
  73. # Prepare credentials, and authorize HTTP object with them.
  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 = file.Storage(name + ".dat")
  78. credentials = storage.get()
  79. if credentials is None or credentials.invalid:
  80. credentials = tools.run_flow(flow, storage, flags)
  81. http = credentials.authorize(http=build_http())
  82. if discovery_filename is None:
  83. # Construct a service object via the discovery service.
  84. service = discovery.build(name, version, http=http)
  85. else:
  86. # Construct a service object using a local discovery document file.
  87. with open(discovery_filename) as discovery_file:
  88. service = discovery.build_from_document(
  89. discovery_file.read(), base="https://www.googleapis.com/", http=http
  90. )
  91. return (service, flags)