1# -*- coding: utf-8 -*-
2# Copyright 2022 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17import dataclasses
18import json # type: ignore
19import re
20from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
21import warnings
22
23from google.api_core import (
24 gapic_v1,
25 operations_v1,
26 path_template,
27 rest_helpers,
28 rest_streaming,
29)
30from google.api_core import exceptions as core_exceptions
31from google.api_core import retry as retries
32from google.auth import credentials as ga_credentials # type: ignore
33from google.auth.transport.grpc import SslCredentials # type: ignore
34from google.auth.transport.requests import AuthorizedSession # type: ignore
35from google.longrunning import operations_pb2
36from google.protobuf import json_format
37import grpc # type: ignore
38from requests import __version__ as requests_version
39
40try:
41 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
42except AttributeError: # pragma: NO COVER
43 OptionalRetry = Union[retries.Retry, object] # type: ignore
44
45
46from google.iam.v1 import iam_policy_pb2 # type: ignore
47from google.iam.v1 import policy_pb2 # type: ignore
48from google.longrunning import operations_pb2 # type: ignore
49
50from google.cloud.resourcemanager_v3.types import projects
51
52from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
53from .base import ProjectsTransport
54
55DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
56 gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
57 grpc_version=None,
58 rest_version=requests_version,
59)
60
61
62class ProjectsRestInterceptor:
63 """Interceptor for Projects.
64
65 Interceptors are used to manipulate requests, request metadata, and responses
66 in arbitrary ways.
67 Example use cases include:
68 * Logging
69 * Verifying requests according to service or custom semantics
70 * Stripping extraneous information from responses
71
72 These use cases and more can be enabled by injecting an
73 instance of a custom subclass when constructing the ProjectsRestTransport.
74
75 .. code-block:: python
76 class MyCustomProjectsInterceptor(ProjectsRestInterceptor):
77 def pre_create_project(self, request, metadata):
78 logging.log(f"Received request: {request}")
79 return request, metadata
80
81 def post_create_project(self, response):
82 logging.log(f"Received response: {response}")
83 return response
84
85 def pre_delete_project(self, request, metadata):
86 logging.log(f"Received request: {request}")
87 return request, metadata
88
89 def post_delete_project(self, response):
90 logging.log(f"Received response: {response}")
91 return response
92
93 def pre_get_iam_policy(self, request, metadata):
94 logging.log(f"Received request: {request}")
95 return request, metadata
96
97 def post_get_iam_policy(self, response):
98 logging.log(f"Received response: {response}")
99 return response
100
101 def pre_get_project(self, request, metadata):
102 logging.log(f"Received request: {request}")
103 return request, metadata
104
105 def post_get_project(self, response):
106 logging.log(f"Received response: {response}")
107 return response
108
109 def pre_list_projects(self, request, metadata):
110 logging.log(f"Received request: {request}")
111 return request, metadata
112
113 def post_list_projects(self, response):
114 logging.log(f"Received response: {response}")
115 return response
116
117 def pre_move_project(self, request, metadata):
118 logging.log(f"Received request: {request}")
119 return request, metadata
120
121 def post_move_project(self, response):
122 logging.log(f"Received response: {response}")
123 return response
124
125 def pre_search_projects(self, request, metadata):
126 logging.log(f"Received request: {request}")
127 return request, metadata
128
129 def post_search_projects(self, response):
130 logging.log(f"Received response: {response}")
131 return response
132
133 def pre_set_iam_policy(self, request, metadata):
134 logging.log(f"Received request: {request}")
135 return request, metadata
136
137 def post_set_iam_policy(self, response):
138 logging.log(f"Received response: {response}")
139 return response
140
141 def pre_test_iam_permissions(self, request, metadata):
142 logging.log(f"Received request: {request}")
143 return request, metadata
144
145 def post_test_iam_permissions(self, response):
146 logging.log(f"Received response: {response}")
147 return response
148
149 def pre_undelete_project(self, request, metadata):
150 logging.log(f"Received request: {request}")
151 return request, metadata
152
153 def post_undelete_project(self, response):
154 logging.log(f"Received response: {response}")
155 return response
156
157 def pre_update_project(self, request, metadata):
158 logging.log(f"Received request: {request}")
159 return request, metadata
160
161 def post_update_project(self, response):
162 logging.log(f"Received response: {response}")
163 return response
164
165 transport = ProjectsRestTransport(interceptor=MyCustomProjectsInterceptor())
166 client = ProjectsClient(transport=transport)
167
168
169 """
170
171 def pre_create_project(
172 self,
173 request: projects.CreateProjectRequest,
174 metadata: Sequence[Tuple[str, str]],
175 ) -> Tuple[projects.CreateProjectRequest, Sequence[Tuple[str, str]]]:
176 """Pre-rpc interceptor for create_project
177
178 Override in a subclass to manipulate the request or metadata
179 before they are sent to the Projects server.
180 """
181 return request, metadata
182
183 def post_create_project(
184 self, response: operations_pb2.Operation
185 ) -> operations_pb2.Operation:
186 """Post-rpc interceptor for create_project
187
188 Override in a subclass to manipulate the response
189 after it is returned by the Projects server but before
190 it is returned to user code.
191 """
192 return response
193
194 def pre_delete_project(
195 self,
196 request: projects.DeleteProjectRequest,
197 metadata: Sequence[Tuple[str, str]],
198 ) -> Tuple[projects.DeleteProjectRequest, Sequence[Tuple[str, str]]]:
199 """Pre-rpc interceptor for delete_project
200
201 Override in a subclass to manipulate the request or metadata
202 before they are sent to the Projects server.
203 """
204 return request, metadata
205
206 def post_delete_project(
207 self, response: operations_pb2.Operation
208 ) -> operations_pb2.Operation:
209 """Post-rpc interceptor for delete_project
210
211 Override in a subclass to manipulate the response
212 after it is returned by the Projects server but before
213 it is returned to user code.
214 """
215 return response
216
217 def pre_get_iam_policy(
218 self,
219 request: iam_policy_pb2.GetIamPolicyRequest,
220 metadata: Sequence[Tuple[str, str]],
221 ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]:
222 """Pre-rpc interceptor for get_iam_policy
223
224 Override in a subclass to manipulate the request or metadata
225 before they are sent to the Projects server.
226 """
227 return request, metadata
228
229 def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
230 """Post-rpc interceptor for get_iam_policy
231
232 Override in a subclass to manipulate the response
233 after it is returned by the Projects server but before
234 it is returned to user code.
235 """
236 return response
237
238 def pre_get_project(
239 self, request: projects.GetProjectRequest, metadata: Sequence[Tuple[str, str]]
240 ) -> Tuple[projects.GetProjectRequest, Sequence[Tuple[str, str]]]:
241 """Pre-rpc interceptor for get_project
242
243 Override in a subclass to manipulate the request or metadata
244 before they are sent to the Projects server.
245 """
246 return request, metadata
247
248 def post_get_project(self, response: projects.Project) -> projects.Project:
249 """Post-rpc interceptor for get_project
250
251 Override in a subclass to manipulate the response
252 after it is returned by the Projects server but before
253 it is returned to user code.
254 """
255 return response
256
257 def pre_list_projects(
258 self, request: projects.ListProjectsRequest, metadata: Sequence[Tuple[str, str]]
259 ) -> Tuple[projects.ListProjectsRequest, Sequence[Tuple[str, str]]]:
260 """Pre-rpc interceptor for list_projects
261
262 Override in a subclass to manipulate the request or metadata
263 before they are sent to the Projects server.
264 """
265 return request, metadata
266
267 def post_list_projects(
268 self, response: projects.ListProjectsResponse
269 ) -> projects.ListProjectsResponse:
270 """Post-rpc interceptor for list_projects
271
272 Override in a subclass to manipulate the response
273 after it is returned by the Projects server but before
274 it is returned to user code.
275 """
276 return response
277
278 def pre_move_project(
279 self, request: projects.MoveProjectRequest, metadata: Sequence[Tuple[str, str]]
280 ) -> Tuple[projects.MoveProjectRequest, Sequence[Tuple[str, str]]]:
281 """Pre-rpc interceptor for move_project
282
283 Override in a subclass to manipulate the request or metadata
284 before they are sent to the Projects server.
285 """
286 return request, metadata
287
288 def post_move_project(
289 self, response: operations_pb2.Operation
290 ) -> operations_pb2.Operation:
291 """Post-rpc interceptor for move_project
292
293 Override in a subclass to manipulate the response
294 after it is returned by the Projects server but before
295 it is returned to user code.
296 """
297 return response
298
299 def pre_search_projects(
300 self,
301 request: projects.SearchProjectsRequest,
302 metadata: Sequence[Tuple[str, str]],
303 ) -> Tuple[projects.SearchProjectsRequest, Sequence[Tuple[str, str]]]:
304 """Pre-rpc interceptor for search_projects
305
306 Override in a subclass to manipulate the request or metadata
307 before they are sent to the Projects server.
308 """
309 return request, metadata
310
311 def post_search_projects(
312 self, response: projects.SearchProjectsResponse
313 ) -> projects.SearchProjectsResponse:
314 """Post-rpc interceptor for search_projects
315
316 Override in a subclass to manipulate the response
317 after it is returned by the Projects server but before
318 it is returned to user code.
319 """
320 return response
321
322 def pre_set_iam_policy(
323 self,
324 request: iam_policy_pb2.SetIamPolicyRequest,
325 metadata: Sequence[Tuple[str, str]],
326 ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]:
327 """Pre-rpc interceptor for set_iam_policy
328
329 Override in a subclass to manipulate the request or metadata
330 before they are sent to the Projects server.
331 """
332 return request, metadata
333
334 def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
335 """Post-rpc interceptor for set_iam_policy
336
337 Override in a subclass to manipulate the response
338 after it is returned by the Projects server but before
339 it is returned to user code.
340 """
341 return response
342
343 def pre_test_iam_permissions(
344 self,
345 request: iam_policy_pb2.TestIamPermissionsRequest,
346 metadata: Sequence[Tuple[str, str]],
347 ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]:
348 """Pre-rpc interceptor for test_iam_permissions
349
350 Override in a subclass to manipulate the request or metadata
351 before they are sent to the Projects server.
352 """
353 return request, metadata
354
355 def post_test_iam_permissions(
356 self, response: iam_policy_pb2.TestIamPermissionsResponse
357 ) -> iam_policy_pb2.TestIamPermissionsResponse:
358 """Post-rpc interceptor for test_iam_permissions
359
360 Override in a subclass to manipulate the response
361 after it is returned by the Projects server but before
362 it is returned to user code.
363 """
364 return response
365
366 def pre_undelete_project(
367 self,
368 request: projects.UndeleteProjectRequest,
369 metadata: Sequence[Tuple[str, str]],
370 ) -> Tuple[projects.UndeleteProjectRequest, Sequence[Tuple[str, str]]]:
371 """Pre-rpc interceptor for undelete_project
372
373 Override in a subclass to manipulate the request or metadata
374 before they are sent to the Projects server.
375 """
376 return request, metadata
377
378 def post_undelete_project(
379 self, response: operations_pb2.Operation
380 ) -> operations_pb2.Operation:
381 """Post-rpc interceptor for undelete_project
382
383 Override in a subclass to manipulate the response
384 after it is returned by the Projects server but before
385 it is returned to user code.
386 """
387 return response
388
389 def pre_update_project(
390 self,
391 request: projects.UpdateProjectRequest,
392 metadata: Sequence[Tuple[str, str]],
393 ) -> Tuple[projects.UpdateProjectRequest, Sequence[Tuple[str, str]]]:
394 """Pre-rpc interceptor for update_project
395
396 Override in a subclass to manipulate the request or metadata
397 before they are sent to the Projects server.
398 """
399 return request, metadata
400
401 def post_update_project(
402 self, response: operations_pb2.Operation
403 ) -> operations_pb2.Operation:
404 """Post-rpc interceptor for update_project
405
406 Override in a subclass to manipulate the response
407 after it is returned by the Projects server but before
408 it is returned to user code.
409 """
410 return response
411
412 def pre_get_operation(
413 self,
414 request: operations_pb2.GetOperationRequest,
415 metadata: Sequence[Tuple[str, str]],
416 ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]:
417 """Pre-rpc interceptor for get_operation
418
419 Override in a subclass to manipulate the request or metadata
420 before they are sent to the Projects server.
421 """
422 return request, metadata
423
424 def post_get_operation(
425 self, response: operations_pb2.Operation
426 ) -> operations_pb2.Operation:
427 """Post-rpc interceptor for get_operation
428
429 Override in a subclass to manipulate the response
430 after it is returned by the Projects server but before
431 it is returned to user code.
432 """
433 return response
434
435
436@dataclasses.dataclass
437class ProjectsRestStub:
438 _session: AuthorizedSession
439 _host: str
440 _interceptor: ProjectsRestInterceptor
441
442
443class ProjectsRestTransport(ProjectsTransport):
444 """REST backend transport for Projects.
445
446 Manages Google Cloud Projects.
447
448 This class defines the same methods as the primary client, so the
449 primary client can load the underlying transport implementation
450 and call it.
451
452 It sends JSON representations of protocol buffers over HTTP/1.1
453
454 """
455
456 def __init__(
457 self,
458 *,
459 host: str = "cloudresourcemanager.googleapis.com",
460 credentials: Optional[ga_credentials.Credentials] = None,
461 credentials_file: Optional[str] = None,
462 scopes: Optional[Sequence[str]] = None,
463 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
464 quota_project_id: Optional[str] = None,
465 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
466 always_use_jwt_access: Optional[bool] = False,
467 url_scheme: str = "https",
468 interceptor: Optional[ProjectsRestInterceptor] = None,
469 api_audience: Optional[str] = None,
470 ) -> None:
471 """Instantiate the transport.
472
473 Args:
474 host (Optional[str]):
475 The hostname to connect to.
476 credentials (Optional[google.auth.credentials.Credentials]): The
477 authorization credentials to attach to requests. These
478 credentials identify the application to the service; if none
479 are specified, the client will attempt to ascertain the
480 credentials from the environment.
481
482 credentials_file (Optional[str]): A file with credentials that can
483 be loaded with :func:`google.auth.load_credentials_from_file`.
484 This argument is ignored if ``channel`` is provided.
485 scopes (Optional(Sequence[str])): A list of scopes. This argument is
486 ignored if ``channel`` is provided.
487 client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
488 certificate to configure mutual TLS HTTP channel. It is ignored
489 if ``channel`` is provided.
490 quota_project_id (Optional[str]): An optional project to use for billing
491 and quota.
492 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
493 The client info used to send a user-agent string along with
494 API requests. If ``None``, then default info will be used.
495 Generally, you only need to set this if you are developing
496 your own client library.
497 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
498 be used for service account credentials.
499 url_scheme: the protocol scheme for the API endpoint. Normally
500 "https", but for testing or local servers,
501 "http" can be specified.
502 """
503 # Run the base constructor
504 # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
505 # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
506 # credentials object
507 maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
508 if maybe_url_match is None:
509 raise ValueError(
510 f"Unexpected hostname structure: {host}"
511 ) # pragma: NO COVER
512
513 url_match_items = maybe_url_match.groupdict()
514
515 host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
516
517 super().__init__(
518 host=host,
519 credentials=credentials,
520 client_info=client_info,
521 always_use_jwt_access=always_use_jwt_access,
522 api_audience=api_audience,
523 )
524 self._session = AuthorizedSession(
525 self._credentials, default_host=self.DEFAULT_HOST
526 )
527 self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None
528 if client_cert_source_for_mtls:
529 self._session.configure_mtls_channel(client_cert_source_for_mtls)
530 self._interceptor = interceptor or ProjectsRestInterceptor()
531 self._prep_wrapped_messages(client_info)
532
533 @property
534 def operations_client(self) -> operations_v1.AbstractOperationsClient:
535 """Create the client designed to process long-running operations.
536
537 This property caches on the instance; repeated calls return the same
538 client.
539 """
540 # Only create a new client if we do not already have one.
541 if self._operations_client is None:
542 http_options: Dict[str, List[Dict[str, str]]] = {
543 "google.longrunning.Operations.GetOperation": [
544 {
545 "method": "get",
546 "uri": "/v3/{name=operations/**}",
547 },
548 ],
549 }
550
551 rest_transport = operations_v1.OperationsRestTransport(
552 host=self._host,
553 # use the credentials which are saved
554 credentials=self._credentials,
555 scopes=self._scopes,
556 http_options=http_options,
557 path_prefix="v3",
558 )
559
560 self._operations_client = operations_v1.AbstractOperationsClient(
561 transport=rest_transport
562 )
563
564 # Return the client from cache.
565 return self._operations_client
566
567 class _CreateProject(ProjectsRestStub):
568 def __hash__(self):
569 return hash("CreateProject")
570
571 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
572
573 @classmethod
574 def _get_unset_required_fields(cls, message_dict):
575 return {
576 k: v
577 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
578 if k not in message_dict
579 }
580
581 def __call__(
582 self,
583 request: projects.CreateProjectRequest,
584 *,
585 retry: OptionalRetry = gapic_v1.method.DEFAULT,
586 timeout: Optional[float] = None,
587 metadata: Sequence[Tuple[str, str]] = (),
588 ) -> operations_pb2.Operation:
589 r"""Call the create project method over HTTP.
590
591 Args:
592 request (~.projects.CreateProjectRequest):
593 The request object. The request sent to the
594 [CreateProject][google.cloud.resourcemanager.v3.Projects.CreateProject]
595 method.
596 retry (google.api_core.retry.Retry): Designation of what errors, if any,
597 should be retried.
598 timeout (float): The timeout for this request.
599 metadata (Sequence[Tuple[str, str]]): Strings which should be
600 sent along with the request as metadata.
601
602 Returns:
603 ~.operations_pb2.Operation:
604 This resource represents a
605 long-running operation that is the
606 result of a network API call.
607
608 """
609
610 http_options: List[Dict[str, str]] = [
611 {
612 "method": "post",
613 "uri": "/v3/projects",
614 "body": "project",
615 },
616 ]
617 request, metadata = self._interceptor.pre_create_project(request, metadata)
618 pb_request = projects.CreateProjectRequest.pb(request)
619 transcoded_request = path_template.transcode(http_options, pb_request)
620
621 # Jsonify the request body
622
623 body = json_format.MessageToJson(
624 transcoded_request["body"],
625 including_default_value_fields=False,
626 use_integers_for_enums=True,
627 )
628 uri = transcoded_request["uri"]
629 method = transcoded_request["method"]
630
631 # Jsonify the query params
632 query_params = json.loads(
633 json_format.MessageToJson(
634 transcoded_request["query_params"],
635 including_default_value_fields=False,
636 use_integers_for_enums=True,
637 )
638 )
639 query_params.update(self._get_unset_required_fields(query_params))
640
641 query_params["$alt"] = "json;enum-encoding=int"
642
643 # Send the request
644 headers = dict(metadata)
645 headers["Content-Type"] = "application/json"
646 response = getattr(self._session, method)(
647 "{host}{uri}".format(host=self._host, uri=uri),
648 timeout=timeout,
649 headers=headers,
650 params=rest_helpers.flatten_query_params(query_params, strict=True),
651 data=body,
652 )
653
654 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
655 # subclass.
656 if response.status_code >= 400:
657 raise core_exceptions.from_http_response(response)
658
659 # Return the response
660 resp = operations_pb2.Operation()
661 json_format.Parse(response.content, resp, ignore_unknown_fields=True)
662 resp = self._interceptor.post_create_project(resp)
663 return resp
664
665 class _DeleteProject(ProjectsRestStub):
666 def __hash__(self):
667 return hash("DeleteProject")
668
669 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
670
671 @classmethod
672 def _get_unset_required_fields(cls, message_dict):
673 return {
674 k: v
675 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
676 if k not in message_dict
677 }
678
679 def __call__(
680 self,
681 request: projects.DeleteProjectRequest,
682 *,
683 retry: OptionalRetry = gapic_v1.method.DEFAULT,
684 timeout: Optional[float] = None,
685 metadata: Sequence[Tuple[str, str]] = (),
686 ) -> operations_pb2.Operation:
687 r"""Call the delete project method over HTTP.
688
689 Args:
690 request (~.projects.DeleteProjectRequest):
691 The request object. [DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject]
692 method.
693 retry (google.api_core.retry.Retry): Designation of what errors, if any,
694 should be retried.
695 timeout (float): The timeout for this request.
696 metadata (Sequence[Tuple[str, str]]): Strings which should be
697 sent along with the request as metadata.
698
699 Returns:
700 ~.operations_pb2.Operation:
701 This resource represents a
702 long-running operation that is the
703 result of a network API call.
704
705 """
706
707 http_options: List[Dict[str, str]] = [
708 {
709 "method": "delete",
710 "uri": "/v3/{name=projects/*}",
711 },
712 ]
713 request, metadata = self._interceptor.pre_delete_project(request, metadata)
714 pb_request = projects.DeleteProjectRequest.pb(request)
715 transcoded_request = path_template.transcode(http_options, pb_request)
716
717 uri = transcoded_request["uri"]
718 method = transcoded_request["method"]
719
720 # Jsonify the query params
721 query_params = json.loads(
722 json_format.MessageToJson(
723 transcoded_request["query_params"],
724 including_default_value_fields=False,
725 use_integers_for_enums=True,
726 )
727 )
728 query_params.update(self._get_unset_required_fields(query_params))
729
730 query_params["$alt"] = "json;enum-encoding=int"
731
732 # Send the request
733 headers = dict(metadata)
734 headers["Content-Type"] = "application/json"
735 response = getattr(self._session, method)(
736 "{host}{uri}".format(host=self._host, uri=uri),
737 timeout=timeout,
738 headers=headers,
739 params=rest_helpers.flatten_query_params(query_params, strict=True),
740 )
741
742 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
743 # subclass.
744 if response.status_code >= 400:
745 raise core_exceptions.from_http_response(response)
746
747 # Return the response
748 resp = operations_pb2.Operation()
749 json_format.Parse(response.content, resp, ignore_unknown_fields=True)
750 resp = self._interceptor.post_delete_project(resp)
751 return resp
752
753 class _GetIamPolicy(ProjectsRestStub):
754 def __hash__(self):
755 return hash("GetIamPolicy")
756
757 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
758
759 @classmethod
760 def _get_unset_required_fields(cls, message_dict):
761 return {
762 k: v
763 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
764 if k not in message_dict
765 }
766
767 def __call__(
768 self,
769 request: iam_policy_pb2.GetIamPolicyRequest,
770 *,
771 retry: OptionalRetry = gapic_v1.method.DEFAULT,
772 timeout: Optional[float] = None,
773 metadata: Sequence[Tuple[str, str]] = (),
774 ) -> policy_pb2.Policy:
775 r"""Call the get iam policy method over HTTP.
776
777 Args:
778 request (~.iam_policy_pb2.GetIamPolicyRequest):
779 The request object. Request message for ``GetIamPolicy`` method.
780 retry (google.api_core.retry.Retry): Designation of what errors, if any,
781 should be retried.
782 timeout (float): The timeout for this request.
783 metadata (Sequence[Tuple[str, str]]): Strings which should be
784 sent along with the request as metadata.
785
786 Returns:
787 ~.policy_pb2.Policy:
788 An Identity and Access Management (IAM) policy, which
789 specifies access controls for Google Cloud resources.
790
791 A ``Policy`` is a collection of ``bindings``. A
792 ``binding`` binds one or more ``members``, or
793 principals, to a single ``role``. Principals can be user
794 accounts, service accounts, Google groups, and domains
795 (such as G Suite). A ``role`` is a named list of
796 permissions; each ``role`` can be an IAM predefined role
797 or a user-created custom role.
798
799 For some types of Google Cloud resources, a ``binding``
800 can also specify a ``condition``, which is a logical
801 expression that allows access to a resource only if the
802 expression evaluates to ``true``. A condition can add
803 constraints based on attributes of the request, the
804 resource, or both. To learn which resources support
805 conditions in their IAM policies, see the `IAM
806 documentation <https://cloud.google.com/iam/help/conditions/resource-policies>`__.
807
808 **JSON example:**
809
810 ::
811
812 {
813 "bindings": [
814 {
815 "role": "roles/resourcemanager.organizationAdmin",
816 "members": [
817 "user:mike@example.com",
818 "group:admins@example.com",
819 "domain:google.com",
820 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
821 ]
822 },
823 {
824 "role": "roles/resourcemanager.organizationViewer",
825 "members": [
826 "user:eve@example.com"
827 ],
828 "condition": {
829 "title": "expirable access",
830 "description": "Does not grant access after Sep 2020",
831 "expression": "request.time <
832 timestamp('2020-10-01T00:00:00.000Z')",
833 }
834 }
835 ],
836 "etag": "BwWWja0YfJA=",
837 "version": 3
838 }
839
840 **YAML example:**
841
842 ::
843
844 bindings:
845 - members:
846 - user:mike@example.com
847 - group:admins@example.com
848 - domain:google.com
849 - serviceAccount:my-project-id@appspot.gserviceaccount.com
850 role: roles/resourcemanager.organizationAdmin
851 - members:
852 - user:eve@example.com
853 role: roles/resourcemanager.organizationViewer
854 condition:
855 title: expirable access
856 description: Does not grant access after Sep 2020
857 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
858 etag: BwWWja0YfJA=
859 version: 3
860
861 For a description of IAM and its features, see the `IAM
862 documentation <https://cloud.google.com/iam/docs/>`__.
863
864 """
865
866 http_options: List[Dict[str, str]] = [
867 {
868 "method": "post",
869 "uri": "/v3/{resource=projects/*}:getIamPolicy",
870 "body": "*",
871 },
872 ]
873 request, metadata = self._interceptor.pre_get_iam_policy(request, metadata)
874 pb_request = request
875 transcoded_request = path_template.transcode(http_options, pb_request)
876
877 # Jsonify the request body
878
879 body = json_format.MessageToJson(
880 transcoded_request["body"],
881 including_default_value_fields=False,
882 use_integers_for_enums=True,
883 )
884 uri = transcoded_request["uri"]
885 method = transcoded_request["method"]
886
887 # Jsonify the query params
888 query_params = json.loads(
889 json_format.MessageToJson(
890 transcoded_request["query_params"],
891 including_default_value_fields=False,
892 use_integers_for_enums=True,
893 )
894 )
895 query_params.update(self._get_unset_required_fields(query_params))
896
897 query_params["$alt"] = "json;enum-encoding=int"
898
899 # Send the request
900 headers = dict(metadata)
901 headers["Content-Type"] = "application/json"
902 response = getattr(self._session, method)(
903 "{host}{uri}".format(host=self._host, uri=uri),
904 timeout=timeout,
905 headers=headers,
906 params=rest_helpers.flatten_query_params(query_params, strict=True),
907 data=body,
908 )
909
910 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
911 # subclass.
912 if response.status_code >= 400:
913 raise core_exceptions.from_http_response(response)
914
915 # Return the response
916 resp = policy_pb2.Policy()
917 pb_resp = resp
918
919 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
920 resp = self._interceptor.post_get_iam_policy(resp)
921 return resp
922
923 class _GetProject(ProjectsRestStub):
924 def __hash__(self):
925 return hash("GetProject")
926
927 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
928
929 @classmethod
930 def _get_unset_required_fields(cls, message_dict):
931 return {
932 k: v
933 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
934 if k not in message_dict
935 }
936
937 def __call__(
938 self,
939 request: projects.GetProjectRequest,
940 *,
941 retry: OptionalRetry = gapic_v1.method.DEFAULT,
942 timeout: Optional[float] = None,
943 metadata: Sequence[Tuple[str, str]] = (),
944 ) -> projects.Project:
945 r"""Call the get project method over HTTP.
946
947 Args:
948 request (~.projects.GetProjectRequest):
949 The request object. The request sent to the
950 [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject]
951 method.
952 retry (google.api_core.retry.Retry): Designation of what errors, if any,
953 should be retried.
954 timeout (float): The timeout for this request.
955 metadata (Sequence[Tuple[str, str]]): Strings which should be
956 sent along with the request as metadata.
957
958 Returns:
959 ~.projects.Project:
960 A project is a high-level Google
961 Cloud entity. It is a container for
962 ACLs, APIs, App Engine Apps, VMs, and
963 other Google Cloud Platform resources.
964
965 """
966
967 http_options: List[Dict[str, str]] = [
968 {
969 "method": "get",
970 "uri": "/v3/{name=projects/*}",
971 },
972 ]
973 request, metadata = self._interceptor.pre_get_project(request, metadata)
974 pb_request = projects.GetProjectRequest.pb(request)
975 transcoded_request = path_template.transcode(http_options, pb_request)
976
977 uri = transcoded_request["uri"]
978 method = transcoded_request["method"]
979
980 # Jsonify the query params
981 query_params = json.loads(
982 json_format.MessageToJson(
983 transcoded_request["query_params"],
984 including_default_value_fields=False,
985 use_integers_for_enums=True,
986 )
987 )
988 query_params.update(self._get_unset_required_fields(query_params))
989
990 query_params["$alt"] = "json;enum-encoding=int"
991
992 # Send the request
993 headers = dict(metadata)
994 headers["Content-Type"] = "application/json"
995 response = getattr(self._session, method)(
996 "{host}{uri}".format(host=self._host, uri=uri),
997 timeout=timeout,
998 headers=headers,
999 params=rest_helpers.flatten_query_params(query_params, strict=True),
1000 )
1001
1002 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1003 # subclass.
1004 if response.status_code >= 400:
1005 raise core_exceptions.from_http_response(response)
1006
1007 # Return the response
1008 resp = projects.Project()
1009 pb_resp = projects.Project.pb(resp)
1010
1011 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1012 resp = self._interceptor.post_get_project(resp)
1013 return resp
1014
1015 class _ListProjects(ProjectsRestStub):
1016 def __hash__(self):
1017 return hash("ListProjects")
1018
1019 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
1020 "parent": "",
1021 }
1022
1023 @classmethod
1024 def _get_unset_required_fields(cls, message_dict):
1025 return {
1026 k: v
1027 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1028 if k not in message_dict
1029 }
1030
1031 def __call__(
1032 self,
1033 request: projects.ListProjectsRequest,
1034 *,
1035 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1036 timeout: Optional[float] = None,
1037 metadata: Sequence[Tuple[str, str]] = (),
1038 ) -> projects.ListProjectsResponse:
1039 r"""Call the list projects method over HTTP.
1040
1041 Args:
1042 request (~.projects.ListProjectsRequest):
1043 The request object. The request sent to the
1044 [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects]
1045 method.
1046 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1047 should be retried.
1048 timeout (float): The timeout for this request.
1049 metadata (Sequence[Tuple[str, str]]): Strings which should be
1050 sent along with the request as metadata.
1051
1052 Returns:
1053 ~.projects.ListProjectsResponse:
1054 A page of the response received from the
1055 [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects]
1056 method.
1057
1058 A paginated response where more pages are available has
1059 ``next_page_token`` set. This token can be used in a
1060 subsequent request to retrieve the next request page.
1061
1062 NOTE: A response may contain fewer elements than the
1063 request ``page_size`` and still have a
1064 ``next_page_token``.
1065
1066 """
1067
1068 http_options: List[Dict[str, str]] = [
1069 {
1070 "method": "get",
1071 "uri": "/v3/projects",
1072 },
1073 ]
1074 request, metadata = self._interceptor.pre_list_projects(request, metadata)
1075 pb_request = projects.ListProjectsRequest.pb(request)
1076 transcoded_request = path_template.transcode(http_options, pb_request)
1077
1078 uri = transcoded_request["uri"]
1079 method = transcoded_request["method"]
1080
1081 # Jsonify the query params
1082 query_params = json.loads(
1083 json_format.MessageToJson(
1084 transcoded_request["query_params"],
1085 including_default_value_fields=False,
1086 use_integers_for_enums=True,
1087 )
1088 )
1089 query_params.update(self._get_unset_required_fields(query_params))
1090
1091 query_params["$alt"] = "json;enum-encoding=int"
1092
1093 # Send the request
1094 headers = dict(metadata)
1095 headers["Content-Type"] = "application/json"
1096 response = getattr(self._session, method)(
1097 "{host}{uri}".format(host=self._host, uri=uri),
1098 timeout=timeout,
1099 headers=headers,
1100 params=rest_helpers.flatten_query_params(query_params, strict=True),
1101 )
1102
1103 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1104 # subclass.
1105 if response.status_code >= 400:
1106 raise core_exceptions.from_http_response(response)
1107
1108 # Return the response
1109 resp = projects.ListProjectsResponse()
1110 pb_resp = projects.ListProjectsResponse.pb(resp)
1111
1112 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1113 resp = self._interceptor.post_list_projects(resp)
1114 return resp
1115
1116 class _MoveProject(ProjectsRestStub):
1117 def __hash__(self):
1118 return hash("MoveProject")
1119
1120 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1121
1122 @classmethod
1123 def _get_unset_required_fields(cls, message_dict):
1124 return {
1125 k: v
1126 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1127 if k not in message_dict
1128 }
1129
1130 def __call__(
1131 self,
1132 request: projects.MoveProjectRequest,
1133 *,
1134 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1135 timeout: Optional[float] = None,
1136 metadata: Sequence[Tuple[str, str]] = (),
1137 ) -> operations_pb2.Operation:
1138 r"""Call the move project method over HTTP.
1139
1140 Args:
1141 request (~.projects.MoveProjectRequest):
1142 The request object. The request sent to
1143 [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject]
1144 method.
1145 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1146 should be retried.
1147 timeout (float): The timeout for this request.
1148 metadata (Sequence[Tuple[str, str]]): Strings which should be
1149 sent along with the request as metadata.
1150
1151 Returns:
1152 ~.operations_pb2.Operation:
1153 This resource represents a
1154 long-running operation that is the
1155 result of a network API call.
1156
1157 """
1158
1159 http_options: List[Dict[str, str]] = [
1160 {
1161 "method": "post",
1162 "uri": "/v3/{name=projects/*}:move",
1163 "body": "*",
1164 },
1165 ]
1166 request, metadata = self._interceptor.pre_move_project(request, metadata)
1167 pb_request = projects.MoveProjectRequest.pb(request)
1168 transcoded_request = path_template.transcode(http_options, pb_request)
1169
1170 # Jsonify the request body
1171
1172 body = json_format.MessageToJson(
1173 transcoded_request["body"],
1174 including_default_value_fields=False,
1175 use_integers_for_enums=True,
1176 )
1177 uri = transcoded_request["uri"]
1178 method = transcoded_request["method"]
1179
1180 # Jsonify the query params
1181 query_params = json.loads(
1182 json_format.MessageToJson(
1183 transcoded_request["query_params"],
1184 including_default_value_fields=False,
1185 use_integers_for_enums=True,
1186 )
1187 )
1188 query_params.update(self._get_unset_required_fields(query_params))
1189
1190 query_params["$alt"] = "json;enum-encoding=int"
1191
1192 # Send the request
1193 headers = dict(metadata)
1194 headers["Content-Type"] = "application/json"
1195 response = getattr(self._session, method)(
1196 "{host}{uri}".format(host=self._host, uri=uri),
1197 timeout=timeout,
1198 headers=headers,
1199 params=rest_helpers.flatten_query_params(query_params, strict=True),
1200 data=body,
1201 )
1202
1203 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1204 # subclass.
1205 if response.status_code >= 400:
1206 raise core_exceptions.from_http_response(response)
1207
1208 # Return the response
1209 resp = operations_pb2.Operation()
1210 json_format.Parse(response.content, resp, ignore_unknown_fields=True)
1211 resp = self._interceptor.post_move_project(resp)
1212 return resp
1213
1214 class _SearchProjects(ProjectsRestStub):
1215 def __hash__(self):
1216 return hash("SearchProjects")
1217
1218 def __call__(
1219 self,
1220 request: projects.SearchProjectsRequest,
1221 *,
1222 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1223 timeout: Optional[float] = None,
1224 metadata: Sequence[Tuple[str, str]] = (),
1225 ) -> projects.SearchProjectsResponse:
1226 r"""Call the search projects method over HTTP.
1227
1228 Args:
1229 request (~.projects.SearchProjectsRequest):
1230 The request object. The request sent to the
1231 [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects]
1232 method.
1233 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1234 should be retried.
1235 timeout (float): The timeout for this request.
1236 metadata (Sequence[Tuple[str, str]]): Strings which should be
1237 sent along with the request as metadata.
1238
1239 Returns:
1240 ~.projects.SearchProjectsResponse:
1241 A page of the response received from the
1242 [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects]
1243 method.
1244
1245 A paginated response where more pages are available has
1246 ``next_page_token`` set. This token can be used in a
1247 subsequent request to retrieve the next request page.
1248
1249 """
1250
1251 http_options: List[Dict[str, str]] = [
1252 {
1253 "method": "get",
1254 "uri": "/v3/projects:search",
1255 },
1256 ]
1257 request, metadata = self._interceptor.pre_search_projects(request, metadata)
1258 pb_request = projects.SearchProjectsRequest.pb(request)
1259 transcoded_request = path_template.transcode(http_options, pb_request)
1260
1261 uri = transcoded_request["uri"]
1262 method = transcoded_request["method"]
1263
1264 # Jsonify the query params
1265 query_params = json.loads(
1266 json_format.MessageToJson(
1267 transcoded_request["query_params"],
1268 including_default_value_fields=False,
1269 use_integers_for_enums=True,
1270 )
1271 )
1272
1273 query_params["$alt"] = "json;enum-encoding=int"
1274
1275 # Send the request
1276 headers = dict(metadata)
1277 headers["Content-Type"] = "application/json"
1278 response = getattr(self._session, method)(
1279 "{host}{uri}".format(host=self._host, uri=uri),
1280 timeout=timeout,
1281 headers=headers,
1282 params=rest_helpers.flatten_query_params(query_params, strict=True),
1283 )
1284
1285 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1286 # subclass.
1287 if response.status_code >= 400:
1288 raise core_exceptions.from_http_response(response)
1289
1290 # Return the response
1291 resp = projects.SearchProjectsResponse()
1292 pb_resp = projects.SearchProjectsResponse.pb(resp)
1293
1294 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1295 resp = self._interceptor.post_search_projects(resp)
1296 return resp
1297
1298 class _SetIamPolicy(ProjectsRestStub):
1299 def __hash__(self):
1300 return hash("SetIamPolicy")
1301
1302 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1303
1304 @classmethod
1305 def _get_unset_required_fields(cls, message_dict):
1306 return {
1307 k: v
1308 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1309 if k not in message_dict
1310 }
1311
1312 def __call__(
1313 self,
1314 request: iam_policy_pb2.SetIamPolicyRequest,
1315 *,
1316 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1317 timeout: Optional[float] = None,
1318 metadata: Sequence[Tuple[str, str]] = (),
1319 ) -> policy_pb2.Policy:
1320 r"""Call the set iam policy method over HTTP.
1321
1322 Args:
1323 request (~.iam_policy_pb2.SetIamPolicyRequest):
1324 The request object. Request message for ``SetIamPolicy`` method.
1325 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1326 should be retried.
1327 timeout (float): The timeout for this request.
1328 metadata (Sequence[Tuple[str, str]]): Strings which should be
1329 sent along with the request as metadata.
1330
1331 Returns:
1332 ~.policy_pb2.Policy:
1333 An Identity and Access Management (IAM) policy, which
1334 specifies access controls for Google Cloud resources.
1335
1336 A ``Policy`` is a collection of ``bindings``. A
1337 ``binding`` binds one or more ``members``, or
1338 principals, to a single ``role``. Principals can be user
1339 accounts, service accounts, Google groups, and domains
1340 (such as G Suite). A ``role`` is a named list of
1341 permissions; each ``role`` can be an IAM predefined role
1342 or a user-created custom role.
1343
1344 For some types of Google Cloud resources, a ``binding``
1345 can also specify a ``condition``, which is a logical
1346 expression that allows access to a resource only if the
1347 expression evaluates to ``true``. A condition can add
1348 constraints based on attributes of the request, the
1349 resource, or both. To learn which resources support
1350 conditions in their IAM policies, see the `IAM
1351 documentation <https://cloud.google.com/iam/help/conditions/resource-policies>`__.
1352
1353 **JSON example:**
1354
1355 ::
1356
1357 {
1358 "bindings": [
1359 {
1360 "role": "roles/resourcemanager.organizationAdmin",
1361 "members": [
1362 "user:mike@example.com",
1363 "group:admins@example.com",
1364 "domain:google.com",
1365 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
1366 ]
1367 },
1368 {
1369 "role": "roles/resourcemanager.organizationViewer",
1370 "members": [
1371 "user:eve@example.com"
1372 ],
1373 "condition": {
1374 "title": "expirable access",
1375 "description": "Does not grant access after Sep 2020",
1376 "expression": "request.time <
1377 timestamp('2020-10-01T00:00:00.000Z')",
1378 }
1379 }
1380 ],
1381 "etag": "BwWWja0YfJA=",
1382 "version": 3
1383 }
1384
1385 **YAML example:**
1386
1387 ::
1388
1389 bindings:
1390 - members:
1391 - user:mike@example.com
1392 - group:admins@example.com
1393 - domain:google.com
1394 - serviceAccount:my-project-id@appspot.gserviceaccount.com
1395 role: roles/resourcemanager.organizationAdmin
1396 - members:
1397 - user:eve@example.com
1398 role: roles/resourcemanager.organizationViewer
1399 condition:
1400 title: expirable access
1401 description: Does not grant access after Sep 2020
1402 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
1403 etag: BwWWja0YfJA=
1404 version: 3
1405
1406 For a description of IAM and its features, see the `IAM
1407 documentation <https://cloud.google.com/iam/docs/>`__.
1408
1409 """
1410
1411 http_options: List[Dict[str, str]] = [
1412 {
1413 "method": "post",
1414 "uri": "/v3/{resource=projects/*}:setIamPolicy",
1415 "body": "*",
1416 },
1417 ]
1418 request, metadata = self._interceptor.pre_set_iam_policy(request, metadata)
1419 pb_request = request
1420 transcoded_request = path_template.transcode(http_options, pb_request)
1421
1422 # Jsonify the request body
1423
1424 body = json_format.MessageToJson(
1425 transcoded_request["body"],
1426 including_default_value_fields=False,
1427 use_integers_for_enums=True,
1428 )
1429 uri = transcoded_request["uri"]
1430 method = transcoded_request["method"]
1431
1432 # Jsonify the query params
1433 query_params = json.loads(
1434 json_format.MessageToJson(
1435 transcoded_request["query_params"],
1436 including_default_value_fields=False,
1437 use_integers_for_enums=True,
1438 )
1439 )
1440 query_params.update(self._get_unset_required_fields(query_params))
1441
1442 query_params["$alt"] = "json;enum-encoding=int"
1443
1444 # Send the request
1445 headers = dict(metadata)
1446 headers["Content-Type"] = "application/json"
1447 response = getattr(self._session, method)(
1448 "{host}{uri}".format(host=self._host, uri=uri),
1449 timeout=timeout,
1450 headers=headers,
1451 params=rest_helpers.flatten_query_params(query_params, strict=True),
1452 data=body,
1453 )
1454
1455 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1456 # subclass.
1457 if response.status_code >= 400:
1458 raise core_exceptions.from_http_response(response)
1459
1460 # Return the response
1461 resp = policy_pb2.Policy()
1462 pb_resp = resp
1463
1464 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1465 resp = self._interceptor.post_set_iam_policy(resp)
1466 return resp
1467
1468 class _TestIamPermissions(ProjectsRestStub):
1469 def __hash__(self):
1470 return hash("TestIamPermissions")
1471
1472 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1473
1474 @classmethod
1475 def _get_unset_required_fields(cls, message_dict):
1476 return {
1477 k: v
1478 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1479 if k not in message_dict
1480 }
1481
1482 def __call__(
1483 self,
1484 request: iam_policy_pb2.TestIamPermissionsRequest,
1485 *,
1486 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1487 timeout: Optional[float] = None,
1488 metadata: Sequence[Tuple[str, str]] = (),
1489 ) -> iam_policy_pb2.TestIamPermissionsResponse:
1490 r"""Call the test iam permissions method over HTTP.
1491
1492 Args:
1493 request (~.iam_policy_pb2.TestIamPermissionsRequest):
1494 The request object. Request message for ``TestIamPermissions`` method.
1495 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1496 should be retried.
1497 timeout (float): The timeout for this request.
1498 metadata (Sequence[Tuple[str, str]]): Strings which should be
1499 sent along with the request as metadata.
1500
1501 Returns:
1502 ~.iam_policy_pb2.TestIamPermissionsResponse:
1503 Response message for ``TestIamPermissions`` method.
1504 """
1505
1506 http_options: List[Dict[str, str]] = [
1507 {
1508 "method": "post",
1509 "uri": "/v3/{resource=projects/*}:testIamPermissions",
1510 "body": "*",
1511 },
1512 ]
1513 request, metadata = self._interceptor.pre_test_iam_permissions(
1514 request, metadata
1515 )
1516 pb_request = request
1517 transcoded_request = path_template.transcode(http_options, pb_request)
1518
1519 # Jsonify the request body
1520
1521 body = json_format.MessageToJson(
1522 transcoded_request["body"],
1523 including_default_value_fields=False,
1524 use_integers_for_enums=True,
1525 )
1526 uri = transcoded_request["uri"]
1527 method = transcoded_request["method"]
1528
1529 # Jsonify the query params
1530 query_params = json.loads(
1531 json_format.MessageToJson(
1532 transcoded_request["query_params"],
1533 including_default_value_fields=False,
1534 use_integers_for_enums=True,
1535 )
1536 )
1537 query_params.update(self._get_unset_required_fields(query_params))
1538
1539 query_params["$alt"] = "json;enum-encoding=int"
1540
1541 # Send the request
1542 headers = dict(metadata)
1543 headers["Content-Type"] = "application/json"
1544 response = getattr(self._session, method)(
1545 "{host}{uri}".format(host=self._host, uri=uri),
1546 timeout=timeout,
1547 headers=headers,
1548 params=rest_helpers.flatten_query_params(query_params, strict=True),
1549 data=body,
1550 )
1551
1552 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1553 # subclass.
1554 if response.status_code >= 400:
1555 raise core_exceptions.from_http_response(response)
1556
1557 # Return the response
1558 resp = iam_policy_pb2.TestIamPermissionsResponse()
1559 pb_resp = resp
1560
1561 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1562 resp = self._interceptor.post_test_iam_permissions(resp)
1563 return resp
1564
1565 class _UndeleteProject(ProjectsRestStub):
1566 def __hash__(self):
1567 return hash("UndeleteProject")
1568
1569 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1570
1571 @classmethod
1572 def _get_unset_required_fields(cls, message_dict):
1573 return {
1574 k: v
1575 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1576 if k not in message_dict
1577 }
1578
1579 def __call__(
1580 self,
1581 request: projects.UndeleteProjectRequest,
1582 *,
1583 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1584 timeout: Optional[float] = None,
1585 metadata: Sequence[Tuple[str, str]] = (),
1586 ) -> operations_pb2.Operation:
1587 r"""Call the undelete project method over HTTP.
1588
1589 Args:
1590 request (~.projects.UndeleteProjectRequest):
1591 The request object. The request sent to the [UndeleteProject]
1592 [google.cloud.resourcemanager.v3.Projects.UndeleteProject]
1593 method.
1594 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1595 should be retried.
1596 timeout (float): The timeout for this request.
1597 metadata (Sequence[Tuple[str, str]]): Strings which should be
1598 sent along with the request as metadata.
1599
1600 Returns:
1601 ~.operations_pb2.Operation:
1602 This resource represents a
1603 long-running operation that is the
1604 result of a network API call.
1605
1606 """
1607
1608 http_options: List[Dict[str, str]] = [
1609 {
1610 "method": "post",
1611 "uri": "/v3/{name=projects/*}:undelete",
1612 "body": "*",
1613 },
1614 ]
1615 request, metadata = self._interceptor.pre_undelete_project(
1616 request, metadata
1617 )
1618 pb_request = projects.UndeleteProjectRequest.pb(request)
1619 transcoded_request = path_template.transcode(http_options, pb_request)
1620
1621 # Jsonify the request body
1622
1623 body = json_format.MessageToJson(
1624 transcoded_request["body"],
1625 including_default_value_fields=False,
1626 use_integers_for_enums=True,
1627 )
1628 uri = transcoded_request["uri"]
1629 method = transcoded_request["method"]
1630
1631 # Jsonify the query params
1632 query_params = json.loads(
1633 json_format.MessageToJson(
1634 transcoded_request["query_params"],
1635 including_default_value_fields=False,
1636 use_integers_for_enums=True,
1637 )
1638 )
1639 query_params.update(self._get_unset_required_fields(query_params))
1640
1641 query_params["$alt"] = "json;enum-encoding=int"
1642
1643 # Send the request
1644 headers = dict(metadata)
1645 headers["Content-Type"] = "application/json"
1646 response = getattr(self._session, method)(
1647 "{host}{uri}".format(host=self._host, uri=uri),
1648 timeout=timeout,
1649 headers=headers,
1650 params=rest_helpers.flatten_query_params(query_params, strict=True),
1651 data=body,
1652 )
1653
1654 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1655 # subclass.
1656 if response.status_code >= 400:
1657 raise core_exceptions.from_http_response(response)
1658
1659 # Return the response
1660 resp = operations_pb2.Operation()
1661 json_format.Parse(response.content, resp, ignore_unknown_fields=True)
1662 resp = self._interceptor.post_undelete_project(resp)
1663 return resp
1664
1665 class _UpdateProject(ProjectsRestStub):
1666 def __hash__(self):
1667 return hash("UpdateProject")
1668
1669 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1670
1671 @classmethod
1672 def _get_unset_required_fields(cls, message_dict):
1673 return {
1674 k: v
1675 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1676 if k not in message_dict
1677 }
1678
1679 def __call__(
1680 self,
1681 request: projects.UpdateProjectRequest,
1682 *,
1683 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1684 timeout: Optional[float] = None,
1685 metadata: Sequence[Tuple[str, str]] = (),
1686 ) -> operations_pb2.Operation:
1687 r"""Call the update project method over HTTP.
1688
1689 Args:
1690 request (~.projects.UpdateProjectRequest):
1691 The request object. The request sent to the
1692 [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject]
1693 method.
1694
1695 Only the ``display_name`` and ``labels`` fields can be
1696 change. Use the
1697 [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject]
1698 method to change the ``parent`` field.
1699 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1700 should be retried.
1701 timeout (float): The timeout for this request.
1702 metadata (Sequence[Tuple[str, str]]): Strings which should be
1703 sent along with the request as metadata.
1704
1705 Returns:
1706 ~.operations_pb2.Operation:
1707 This resource represents a
1708 long-running operation that is the
1709 result of a network API call.
1710
1711 """
1712
1713 http_options: List[Dict[str, str]] = [
1714 {
1715 "method": "patch",
1716 "uri": "/v3/{project.name=projects/*}",
1717 "body": "project",
1718 },
1719 ]
1720 request, metadata = self._interceptor.pre_update_project(request, metadata)
1721 pb_request = projects.UpdateProjectRequest.pb(request)
1722 transcoded_request = path_template.transcode(http_options, pb_request)
1723
1724 # Jsonify the request body
1725
1726 body = json_format.MessageToJson(
1727 transcoded_request["body"],
1728 including_default_value_fields=False,
1729 use_integers_for_enums=True,
1730 )
1731 uri = transcoded_request["uri"]
1732 method = transcoded_request["method"]
1733
1734 # Jsonify the query params
1735 query_params = json.loads(
1736 json_format.MessageToJson(
1737 transcoded_request["query_params"],
1738 including_default_value_fields=False,
1739 use_integers_for_enums=True,
1740 )
1741 )
1742 query_params.update(self._get_unset_required_fields(query_params))
1743
1744 query_params["$alt"] = "json;enum-encoding=int"
1745
1746 # Send the request
1747 headers = dict(metadata)
1748 headers["Content-Type"] = "application/json"
1749 response = getattr(self._session, method)(
1750 "{host}{uri}".format(host=self._host, uri=uri),
1751 timeout=timeout,
1752 headers=headers,
1753 params=rest_helpers.flatten_query_params(query_params, strict=True),
1754 data=body,
1755 )
1756
1757 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1758 # subclass.
1759 if response.status_code >= 400:
1760 raise core_exceptions.from_http_response(response)
1761
1762 # Return the response
1763 resp = operations_pb2.Operation()
1764 json_format.Parse(response.content, resp, ignore_unknown_fields=True)
1765 resp = self._interceptor.post_update_project(resp)
1766 return resp
1767
1768 @property
1769 def create_project(
1770 self,
1771 ) -> Callable[[projects.CreateProjectRequest], operations_pb2.Operation]:
1772 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1773 # In C++ this would require a dynamic_cast
1774 return self._CreateProject(self._session, self._host, self._interceptor) # type: ignore
1775
1776 @property
1777 def delete_project(
1778 self,
1779 ) -> Callable[[projects.DeleteProjectRequest], operations_pb2.Operation]:
1780 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1781 # In C++ this would require a dynamic_cast
1782 return self._DeleteProject(self._session, self._host, self._interceptor) # type: ignore
1783
1784 @property
1785 def get_iam_policy(
1786 self,
1787 ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
1788 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1789 # In C++ this would require a dynamic_cast
1790 return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
1791
1792 @property
1793 def get_project(self) -> Callable[[projects.GetProjectRequest], projects.Project]:
1794 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1795 # In C++ this would require a dynamic_cast
1796 return self._GetProject(self._session, self._host, self._interceptor) # type: ignore
1797
1798 @property
1799 def list_projects(
1800 self,
1801 ) -> Callable[[projects.ListProjectsRequest], projects.ListProjectsResponse]:
1802 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1803 # In C++ this would require a dynamic_cast
1804 return self._ListProjects(self._session, self._host, self._interceptor) # type: ignore
1805
1806 @property
1807 def move_project(
1808 self,
1809 ) -> Callable[[projects.MoveProjectRequest], operations_pb2.Operation]:
1810 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1811 # In C++ this would require a dynamic_cast
1812 return self._MoveProject(self._session, self._host, self._interceptor) # type: ignore
1813
1814 @property
1815 def search_projects(
1816 self,
1817 ) -> Callable[[projects.SearchProjectsRequest], projects.SearchProjectsResponse]:
1818 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1819 # In C++ this would require a dynamic_cast
1820 return self._SearchProjects(self._session, self._host, self._interceptor) # type: ignore
1821
1822 @property
1823 def set_iam_policy(
1824 self,
1825 ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
1826 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1827 # In C++ this would require a dynamic_cast
1828 return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
1829
1830 @property
1831 def test_iam_permissions(
1832 self,
1833 ) -> Callable[
1834 [iam_policy_pb2.TestIamPermissionsRequest],
1835 iam_policy_pb2.TestIamPermissionsResponse,
1836 ]:
1837 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1838 # In C++ this would require a dynamic_cast
1839 return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore
1840
1841 @property
1842 def undelete_project(
1843 self,
1844 ) -> Callable[[projects.UndeleteProjectRequest], operations_pb2.Operation]:
1845 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1846 # In C++ this would require a dynamic_cast
1847 return self._UndeleteProject(self._session, self._host, self._interceptor) # type: ignore
1848
1849 @property
1850 def update_project(
1851 self,
1852 ) -> Callable[[projects.UpdateProjectRequest], operations_pb2.Operation]:
1853 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1854 # In C++ this would require a dynamic_cast
1855 return self._UpdateProject(self._session, self._host, self._interceptor) # type: ignore
1856
1857 @property
1858 def get_operation(self):
1859 return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
1860
1861 class _GetOperation(ProjectsRestStub):
1862 def __call__(
1863 self,
1864 request: operations_pb2.GetOperationRequest,
1865 *,
1866 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1867 timeout: Optional[float] = None,
1868 metadata: Sequence[Tuple[str, str]] = (),
1869 ) -> operations_pb2.Operation:
1870
1871 r"""Call the get operation method over HTTP.
1872
1873 Args:
1874 request (operations_pb2.GetOperationRequest):
1875 The request object for GetOperation method.
1876 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1877 should be retried.
1878 timeout (float): The timeout for this request.
1879 metadata (Sequence[Tuple[str, str]]): Strings which should be
1880 sent along with the request as metadata.
1881
1882 Returns:
1883 operations_pb2.Operation: Response from GetOperation method.
1884 """
1885
1886 http_options: List[Dict[str, str]] = [
1887 {
1888 "method": "get",
1889 "uri": "/v3/{name=operations/**}",
1890 },
1891 ]
1892
1893 request, metadata = self._interceptor.pre_get_operation(request, metadata)
1894 request_kwargs = json_format.MessageToDict(request)
1895 transcoded_request = path_template.transcode(http_options, **request_kwargs)
1896
1897 uri = transcoded_request["uri"]
1898 method = transcoded_request["method"]
1899
1900 # Jsonify the query params
1901 query_params = json.loads(json.dumps(transcoded_request["query_params"]))
1902
1903 # Send the request
1904 headers = dict(metadata)
1905 headers["Content-Type"] = "application/json"
1906
1907 response = getattr(self._session, method)(
1908 "{host}{uri}".format(host=self._host, uri=uri),
1909 timeout=timeout,
1910 headers=headers,
1911 params=rest_helpers.flatten_query_params(query_params),
1912 )
1913
1914 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1915 # subclass.
1916 if response.status_code >= 400:
1917 raise core_exceptions.from_http_response(response)
1918
1919 resp = operations_pb2.Operation()
1920 resp = json_format.Parse(response.content.decode("utf-8"), resp)
1921 resp = self._interceptor.post_get_operation(resp)
1922 return resp
1923
1924 @property
1925 def kind(self) -> str:
1926 return "rest"
1927
1928 def close(self):
1929 self._session.close()
1930
1931
1932__all__ = ("ProjectsRestTransport",)