1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 """Utilities for making samples.
16
17 Consolidates a lot of code commonly repeated in sample applications.
18 """
19
20 __author__ = 'jcgregorio@google.com (Joe Gregorio)'
21 __all__ = ['init']
22
23
24 import argparse
25 import httplib2
26 import os
27
28 from apiclient import discovery
29 from oauth2client import client
30 from oauth2client import file
31 from oauth2client import tools
32
33
34 -def init(argv, name, version, doc, filename, scope=None, parents=[]):
35 """A common initialization routine for samples.
36
37 Many of the sample applications do the same initialization, which has now
38 been consolidated into this function. This function uses common idioms found
39 in almost all the samples, i.e. for an API with name 'apiname', the
40 credentials are stored in a file named apiname.dat, and the
41 client_secrets.json file is stored in the same directory as the application
42 main file.
43
44 Args:
45 argv: list of string, the command-line parameters of the application.
46 name: string, name of the API.
47 version: string, version of the API.
48 doc: string, description of the application. Usually set to __doc__.
49 file: string, filename of the application. Usually set to __file__.
50 parents: list of argparse.ArgumentParser, additional command-line flags.
51 scope: string, The OAuth scope used.
52
53 Returns:
54 A tuple of (service, flags), where service is the service object and flags
55 is the parsed command-line flags.
56 """
57 if scope is None:
58 scope = 'https://www.googleapis.com/auth/' + name
59
60
61 parent_parsers = [tools.argparser]
62 parent_parsers.extend(parents)
63 parser = argparse.ArgumentParser(
64 description=doc,
65 formatter_class=argparse.RawDescriptionHelpFormatter,
66 parents=parent_parsers)
67 flags = parser.parse_args(argv[1:])
68
69
70
71
72
73 client_secrets = os.path.join(os.path.dirname(filename),
74 'client_secrets.json')
75
76
77 flow = client.flow_from_clientsecrets(client_secrets,
78 scope=scope,
79 message=tools.message_if_missing(client_secrets))
80
81
82
83
84
85 storage = file.Storage(name + '.dat')
86 credentials = storage.get()
87 if credentials is None or credentials.invalid:
88 credentials = tools.run_flow(flow, storage, flags)
89 http = credentials.authorize(http = httplib2.Http())
90
91
92 service = discovery.build(name, version, http=http)
93 return (service, flags)
94