blob: 5cb7a06ee6226be86ff44d960e8e13b617c9e567 [file] [log] [blame]
Craig Citro751b7fb2014-09-23 11:20:38 -07001# Copyright 2014 Google Inc. All Rights Reserved.
John Asmuth864311d2014-04-24 15:46:08 -04002#
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
15"""Utilities for making samples.
16
17Consolidates a lot of code commonly repeated in sample applications.
18"""
INADA Naokie4ea1a92015-03-04 03:45:42 +090019from __future__ import absolute_import
John Asmuth864311d2014-04-24 15:46:08 -040020
21__author__ = 'jcgregorio@google.com (Joe Gregorio)'
22__all__ = ['init']
23
24
25import argparse
John Asmuth864311d2014-04-24 15:46:08 -040026import os
27
28from googleapiclient import discovery
Igor Maravić22435292017-01-19 22:28:22 +010029from googleapiclient.http import build_http
Helen Koikede13e3b2018-04-26 16:05:16 -030030
Craig Citro63caac02014-10-15 10:11:30 -070031def init(argv, name, version, doc, filename, scope=None, parents=[], discovery_filename=None):
John Asmuth864311d2014-04-24 15:46:08 -040032 """A common initialization routine for samples.
33
34 Many of the sample applications do the same initialization, which has now
35 been consolidated into this function. This function uses common idioms found
36 in almost all the samples, i.e. for an API with name 'apiname', the
37 credentials are stored in a file named apiname.dat, and the
38 client_secrets.json file is stored in the same directory as the application
39 main file.
40
41 Args:
42 argv: list of string, the command-line parameters of the application.
43 name: string, name of the API.
44 version: string, version of the API.
45 doc: string, description of the application. Usually set to __doc__.
46 file: string, filename of the application. Usually set to __file__.
47 parents: list of argparse.ArgumentParser, additional command-line flags.
48 scope: string, The OAuth scope used.
Craig Citro63caac02014-10-15 10:11:30 -070049 discovery_filename: string, name of local discovery file (JSON). Use when discovery doc not available via URL.
John Asmuth864311d2014-04-24 15:46:08 -040050
51 Returns:
52 A tuple of (service, flags), where service is the service object and flags
53 is the parsed command-line flags.
54 """
Chris McDonoughbbaad282018-07-17 13:32:46 -040055 try:
56 from oauth2client import client
57 from oauth2client import file
58 from oauth2client import tools
59 except ImportError:
60 raise ImportError('googleapiclient.sample_tools requires oauth2client. Please install oauth2client and try again.')
61
John Asmuth864311d2014-04-24 15:46:08 -040062 if scope is None:
63 scope = 'https://www.googleapis.com/auth/' + name
64
65 # Parser command-line arguments.
66 parent_parsers = [tools.argparser]
67 parent_parsers.extend(parents)
68 parser = argparse.ArgumentParser(
69 description=doc,
70 formatter_class=argparse.RawDescriptionHelpFormatter,
71 parents=parent_parsers)
72 flags = parser.parse_args(argv[1:])
73
74 # Name of a file containing the OAuth 2.0 information for this
75 # application, including client_id and client_secret, which are found
76 # on the API Access tab on the Google APIs
77 # Console <http://code.google.com/apis/console>.
78 client_secrets = os.path.join(os.path.dirname(filename),
79 'client_secrets.json')
80
81 # Set up a Flow object to be used if we need to authenticate.
82 flow = client.flow_from_clientsecrets(client_secrets,
83 scope=scope,
84 message=tools.message_if_missing(client_secrets))
85
86 # Prepare credentials, and authorize HTTP object with them.
87 # If the credentials don't exist or are invalid run through the native client
88 # flow. The Storage object will ensure that if successful the good
89 # credentials will get written back to a file.
90 storage = file.Storage(name + '.dat')
91 credentials = storage.get()
92 if credentials is None or credentials.invalid:
93 credentials = tools.run_flow(flow, storage, flags)
Igor Maravić22435292017-01-19 22:28:22 +010094 http = credentials.authorize(http=build_http())
John Asmuth864311d2014-04-24 15:46:08 -040095
Craig Citro63caac02014-10-15 10:11:30 -070096 if discovery_filename is None:
97 # Construct a service object via the discovery service.
98 service = discovery.build(name, version, http=http)
99 else:
100 # Construct a service object using a local discovery document file.
Pat Ferate73f88132015-03-03 18:27:49 -0800101 with open(discovery_filename) as discovery_file:
102 service = discovery.build_from_document(
103 discovery_file.read(),
104 base='https://www.googleapis.com/',
105 http=http)
John Asmuth864311d2014-04-24 15:46:08 -0400106 return (service, flags)