This repository has been archived by the owner on Jun 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathmain.snip
329 lines (287 loc) · 13.9 KB
/
main.snip
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
@extends "py/common.snip"
@extends "py/method_sample.snip"
@snippet generate(api)
{@licenseSection(api.fileHeader)}
"""Accesses the {@api.servicePhraseName}."""
{@renderImportSection(api.fileHeader.importSection)}
_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution(
'{@api.gapicPackageName}',
).version
class {@api.name}(object):
@if api.doc.lines
@if api.doc.remainingLines
"""
@join line : api.doc.lines
{@line}
@end
"""
@else
"""{@api.doc.firstLine}"""
@end
@end
SERVICE_ADDRESS = '{@api.serviceAddress}:{@api.servicePort}'
"""The default address of the service."""
@# The name of the interface for this client. This is the key used to
@# find the method configuration in the client_config dictionary.
_INTERFACE_NAME = '{@api.interfaceKey}'
@@classmethod
def from_service_account_file(cls, filename, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
{@api.name}: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(
filename)
kwargs['credentials'] = credentials
return cls(*args, **kwargs)
from_service_account_json = from_service_account_file
@if api.formatResourceFunctions
@join function : api.formatResourceFunctions
@@classmethod
def {@function.name}(cls, {@createResourceFunctionParams(function.resourceIdParams)}):
"""Return a fully-qualified {@function.entityName} string."""
return google.api_core.path_template.expand(
'{@function.pattern}',
{@createRenderParams(function.resourceIdParams)}
)
@end
@end
def __init__(self, transport=None, channel=None, credentials=None,
client_config={@api.clientConfigName}.config,
client_info=None):
"""Constructor.
Args:
transport (Union[~.{@api.grpcTransportClassName},
Callable[[~.Credentials, type], ~.{@api.grpcTransportClassName}]): A transport
instance, responsible for actually making the API calls.
The default transport uses the gRPC protocol.
This argument may also be a callable which returns a
transport instance. Callables will be sent the credentials
as the first argument and the default transport class as
the second argument.
channel (grpc.Channel): DEPRECATED. A ``Channel`` instance
through which to make calls. This argument is mutually exclusive
with ``credentials``; providing both will raise an exception.
credentials (google.auth.credentials.Credentials): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is mutually exclusive with providing a
transport instance to ``transport``; doing so will raise
an exception.
client_config (dict): DEPRECATED. A dictionary of call options for
each method. If not specified, the default configuration is used.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
"""
@# Raise deprecation warnings for things we want to go away.
if client_config:
warnings.warn('The `client_config` argument is deprecated.',
PendingDeprecationWarning)
if channel:
warnings.warn('The `channel` argument is deprecated; use '
'`transport` instead.', PendingDeprecationWarning)
@# Instantiate the transport.
@# The transport is responsible for handling serialization and
@# deserialization and actually sending data to the service.
if transport:
if callable(transport):
self.transport = transport(
credentials=credentials,
default_class={@api.grpcTransportImportName}.{@api.grpcTransportClassName},
)
else:
if credentials:
raise ValueError(
'Received both a transport instance and '
'credentials; these are mutually exclusive.'
)
self.transport = transport
else:
self.transport = {@api.grpcTransportImportName}.{@api.grpcTransportClassName}(
address=self.SERVICE_ADDRESS,
channel=channel,
credentials=credentials,
)
# Client information initialization.
if client_info is None:
client_info = (
google.api_core.gapic_v1.client_info.DEFAULT_CLIENT_INFO)
client_info.gapic_version = _GAPIC_LIBRARY_VERSION
self._client_info = client_info
@# Parse out the default settings for retry and timeout for each RPC
@# from the client configuration.
@# (Ordinarily, these are the defaults specified in the `*_config.py`
@# file next to this one.)
self._method_configs = google.api_core.gapic_v1.config.parse_method_configs(
client_config['interfaces'][self._INTERFACE_NAME],
)
@# Save a dictionary of cached API call functions.
@# These are the actual callables which invoke the proper
@# transport methods, wrapped with `wrap_method` to add retry,
@# timeout, and the like.
self._inner_api_calls = {}
@# Service calls
@join apiMethod : api.apiMethods on BREAK.add(BREAK)
def {@apiMethod.name}(
{@renderMethodParams(apiMethod.methodParams)}):
"""
@join line : util.trimDocs(apiMethod.doc.mainDocLines)
{@line}
@end
@if apiMethod.hasRequestStreaming
EXPERIMENTAL: This method interface might change in the future.
@end
{@exampleInCode(apiMethod)}
Args:
@join paramDoc : apiMethod.doc.paramDocs
@if paramDoc.lines
{@paramDoc.paramName} ({@paramDoc.typeName}): {@paramDoc.firstLine}
@join line : paramDoc.remainingLines
{@line}
@end
@else
{@paramDoc.paramName} ({@paramDoc.typeName})
@end
@end
@if apiMethod.doc.returnsDocLines
Returns:
@join line : apiMethod.doc.returnsDocLines
{@line}
@end
@end
Raises:
@join line : apiMethod.doc.throwsDocLines
{@line}
@end
"""
@# Wrap the transport method to add retry and timeout logic.
if '{@apiMethod.name}' not in self._inner_api_calls:
self._inner_api_calls['{@apiMethod.name}'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.{@apiMethod.name},
default_retry=self._method_configs['{@apiMethod.grpcMethodName}'].retry,
default_timeout=self._method_configs['{@apiMethod.grpcMethodName}'].timeout,
client_info=self._client_info,
)
@if apiMethod.isSingularRequestMethod
@if apiMethod.oneofParams
@join oneOf : apiMethod.oneofParams on BREAK
@# Sanity check: We have some fields which are mutually exclusive;
@# raise ValueError if more than one is sent.
google.api_core.protobuf_helpers.check_oneof(
@join oneOfField : oneOf on BREAK
{@oneOfField}={@oneOfField},
@end
)
@end
@end
@if apiMethod.optionalRequestObjectParamsNoPageToken
@if apiMethod.requiredRequestObjectParams
request = {@apiMethod.requestTypeName}(
{@requestObjectParams(apiMethod.requiredRequestObjectParams)},
{@requestObjectParams(apiMethod.optionalRequestObjectParamsNoPageToken)},
)
@else
request = {@apiMethod.requestTypeName}(
{@requestObjectParams(apiMethod.optionalRequestObjectParamsNoPageToken)},
)
@end
@else
@if apiMethod.requiredRequestObjectParams
request = {@apiMethod.requestTypeName}(
{@requestObjectParams(apiMethod.requiredRequestObjectParams)},
)
@else
request = {@apiMethod.requestTypeName}()
@end
@end
@if apiMethod.headerRequestParams
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [{@routingHeader(apiMethod.headerRequestParams)}]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(routing_header)
metadata.append(routing_metadata)
@end
@end
@switch apiMethod.type
@case "OptionalArrayMethod"
@if apiMethod.hasReturnValue
return self._inner_api_calls['{@apiMethod.name}']({@apiMethod.requestVariableName}{@optionalParams(apiMethod)})
@else
self._inner_api_calls['{@apiMethod.name}']({@apiMethod.requestVariableName}{@optionalParams(apiMethod)})
@end
@case "PagedOptionalArrayMethod"
iterator = google.api_core.page_iterator.GRPCIterator(
client=None,
method=functools.partial(self._inner_api_calls['{@apiMethod.name}']{@optionalParams(apiMethod)}),
request={@apiMethod.requestVariableName},
items_field='{@apiMethod.pageStreamingView.resourcesFieldName}',
request_token_field='{@apiMethod.pageStreamingView.requestTokenFieldName}',
response_token_field='{@apiMethod.pageStreamingView.responseTokenFieldName}',
)
return iterator
@case "LongRunningOptionalArrayMethod"
operation = self._inner_api_calls['{@apiMethod.name}']({@apiMethod.requestVariableName}{@optionalParams(apiMethod)})
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
{@apiMethod.longRunningView.operationPayloadTypeName},
metadata_type={@apiMethod.longRunningView.metadataTypeName},
)
@default
{@unhandledCase()}
@end
@end
@end
@private createResourceFunctionParams(params)
@join param : params on ", "
{@param.name}
@end
@end
@private createRenderParams(params)
@join param: params on BREAK
{@param.templateKey}={@param.name},
@end
@end
@private optionalParams(apiMethod)
, retry=retry, timeout=timeout, metadata=metadata
@end
@private renderMethodParams(params)
@join param : params on ",".add(BREAK)
@if param.defaultValue
{@param.name}={@param.defaultValue}
@else
{@param.name}
@end
@end
@end
@private requestObjectParams(params)
@join param : params on ",".add(BREAK)
{@param.keyName}={@param.name}
@end
@end
@private routingHeader(params)
@join param : params on ", "
('{@param.fullyQualifiedName}', {@routingHeaderGetters(param.gettersChain)})
@end
@end
@private routingHeaderGetters(getters)
@join getter : getters on "."
{@getter}
@end
@end