Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/cloud/tasks_v2/services/cloud_tasks/transports/rest.py: 33%
591 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 07:07 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 07:07 +0000
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#
17import dataclasses
18import json # type: ignore
19import re
20from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
21import warnings
23from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
24from google.api_core import exceptions as core_exceptions
25from google.api_core import retry as retries
26from google.auth import credentials as ga_credentials # type: ignore
27from google.auth.transport.grpc import SslCredentials # type: ignore
28from google.auth.transport.requests import AuthorizedSession # type: ignore
29from google.protobuf import json_format
30import grpc # type: ignore
31from requests import __version__ as requests_version
33try:
34 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
35except AttributeError: # pragma: NO COVER
36 OptionalRetry = Union[retries.Retry, object] # type: ignore
39from google.iam.v1 import iam_policy_pb2 # type: ignore
40from google.iam.v1 import policy_pb2 # type: ignore
41from google.protobuf import empty_pb2 # type: ignore
43from google.cloud.tasks_v2.types import cloudtasks
44from google.cloud.tasks_v2.types import queue
45from google.cloud.tasks_v2.types import queue as gct_queue
46from google.cloud.tasks_v2.types import task
47from google.cloud.tasks_v2.types import task as gct_task
49from .base import CloudTasksTransport
50from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
52DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
53 gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
54 grpc_version=None,
55 rest_version=requests_version,
56)
59class CloudTasksRestInterceptor:
60 """Interceptor for CloudTasks.
62 Interceptors are used to manipulate requests, request metadata, and responses
63 in arbitrary ways.
64 Example use cases include:
65 * Logging
66 * Verifying requests according to service or custom semantics
67 * Stripping extraneous information from responses
69 These use cases and more can be enabled by injecting an
70 instance of a custom subclass when constructing the CloudTasksRestTransport.
72 .. code-block:: python
73 class MyCustomCloudTasksInterceptor(CloudTasksRestInterceptor):
74 def pre_create_queue(self, request, metadata):
75 logging.log(f"Received request: {request}")
76 return request, metadata
78 def post_create_queue(self, response):
79 logging.log(f"Received response: {response}")
80 return response
82 def pre_create_task(self, request, metadata):
83 logging.log(f"Received request: {request}")
84 return request, metadata
86 def post_create_task(self, response):
87 logging.log(f"Received response: {response}")
88 return response
90 def pre_delete_queue(self, request, metadata):
91 logging.log(f"Received request: {request}")
92 return request, metadata
94 def pre_delete_task(self, request, metadata):
95 logging.log(f"Received request: {request}")
96 return request, metadata
98 def pre_get_iam_policy(self, request, metadata):
99 logging.log(f"Received request: {request}")
100 return request, metadata
102 def post_get_iam_policy(self, response):
103 logging.log(f"Received response: {response}")
104 return response
106 def pre_get_queue(self, request, metadata):
107 logging.log(f"Received request: {request}")
108 return request, metadata
110 def post_get_queue(self, response):
111 logging.log(f"Received response: {response}")
112 return response
114 def pre_get_task(self, request, metadata):
115 logging.log(f"Received request: {request}")
116 return request, metadata
118 def post_get_task(self, response):
119 logging.log(f"Received response: {response}")
120 return response
122 def pre_list_queues(self, request, metadata):
123 logging.log(f"Received request: {request}")
124 return request, metadata
126 def post_list_queues(self, response):
127 logging.log(f"Received response: {response}")
128 return response
130 def pre_list_tasks(self, request, metadata):
131 logging.log(f"Received request: {request}")
132 return request, metadata
134 def post_list_tasks(self, response):
135 logging.log(f"Received response: {response}")
136 return response
138 def pre_pause_queue(self, request, metadata):
139 logging.log(f"Received request: {request}")
140 return request, metadata
142 def post_pause_queue(self, response):
143 logging.log(f"Received response: {response}")
144 return response
146 def pre_purge_queue(self, request, metadata):
147 logging.log(f"Received request: {request}")
148 return request, metadata
150 def post_purge_queue(self, response):
151 logging.log(f"Received response: {response}")
152 return response
154 def pre_resume_queue(self, request, metadata):
155 logging.log(f"Received request: {request}")
156 return request, metadata
158 def post_resume_queue(self, response):
159 logging.log(f"Received response: {response}")
160 return response
162 def pre_run_task(self, request, metadata):
163 logging.log(f"Received request: {request}")
164 return request, metadata
166 def post_run_task(self, response):
167 logging.log(f"Received response: {response}")
168 return response
170 def pre_set_iam_policy(self, request, metadata):
171 logging.log(f"Received request: {request}")
172 return request, metadata
174 def post_set_iam_policy(self, response):
175 logging.log(f"Received response: {response}")
176 return response
178 def pre_test_iam_permissions(self, request, metadata):
179 logging.log(f"Received request: {request}")
180 return request, metadata
182 def post_test_iam_permissions(self, response):
183 logging.log(f"Received response: {response}")
184 return response
186 def pre_update_queue(self, request, metadata):
187 logging.log(f"Received request: {request}")
188 return request, metadata
190 def post_update_queue(self, response):
191 logging.log(f"Received response: {response}")
192 return response
194 transport = CloudTasksRestTransport(interceptor=MyCustomCloudTasksInterceptor())
195 client = CloudTasksClient(transport=transport)
198 """
200 def pre_create_queue(
201 self,
202 request: cloudtasks.CreateQueueRequest,
203 metadata: Sequence[Tuple[str, str]],
204 ) -> Tuple[cloudtasks.CreateQueueRequest, Sequence[Tuple[str, str]]]:
205 """Pre-rpc interceptor for create_queue
207 Override in a subclass to manipulate the request or metadata
208 before they are sent to the CloudTasks server.
209 """
210 return request, metadata
212 def post_create_queue(self, response: gct_queue.Queue) -> gct_queue.Queue:
213 """Post-rpc interceptor for create_queue
215 Override in a subclass to manipulate the response
216 after it is returned by the CloudTasks server but before
217 it is returned to user code.
218 """
219 return response
221 def pre_create_task(
222 self, request: cloudtasks.CreateTaskRequest, metadata: Sequence[Tuple[str, str]]
223 ) -> Tuple[cloudtasks.CreateTaskRequest, Sequence[Tuple[str, str]]]:
224 """Pre-rpc interceptor for create_task
226 Override in a subclass to manipulate the request or metadata
227 before they are sent to the CloudTasks server.
228 """
229 return request, metadata
231 def post_create_task(self, response: gct_task.Task) -> gct_task.Task:
232 """Post-rpc interceptor for create_task
234 Override in a subclass to manipulate the response
235 after it is returned by the CloudTasks server but before
236 it is returned to user code.
237 """
238 return response
240 def pre_delete_queue(
241 self,
242 request: cloudtasks.DeleteQueueRequest,
243 metadata: Sequence[Tuple[str, str]],
244 ) -> Tuple[cloudtasks.DeleteQueueRequest, Sequence[Tuple[str, str]]]:
245 """Pre-rpc interceptor for delete_queue
247 Override in a subclass to manipulate the request or metadata
248 before they are sent to the CloudTasks server.
249 """
250 return request, metadata
252 def pre_delete_task(
253 self, request: cloudtasks.DeleteTaskRequest, metadata: Sequence[Tuple[str, str]]
254 ) -> Tuple[cloudtasks.DeleteTaskRequest, Sequence[Tuple[str, str]]]:
255 """Pre-rpc interceptor for delete_task
257 Override in a subclass to manipulate the request or metadata
258 before they are sent to the CloudTasks server.
259 """
260 return request, metadata
262 def pre_get_iam_policy(
263 self,
264 request: iam_policy_pb2.GetIamPolicyRequest,
265 metadata: Sequence[Tuple[str, str]],
266 ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]:
267 """Pre-rpc interceptor for get_iam_policy
269 Override in a subclass to manipulate the request or metadata
270 before they are sent to the CloudTasks server.
271 """
272 return request, metadata
274 def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
275 """Post-rpc interceptor for get_iam_policy
277 Override in a subclass to manipulate the response
278 after it is returned by the CloudTasks server but before
279 it is returned to user code.
280 """
281 return response
283 def pre_get_queue(
284 self, request: cloudtasks.GetQueueRequest, metadata: Sequence[Tuple[str, str]]
285 ) -> Tuple[cloudtasks.GetQueueRequest, Sequence[Tuple[str, str]]]:
286 """Pre-rpc interceptor for get_queue
288 Override in a subclass to manipulate the request or metadata
289 before they are sent to the CloudTasks server.
290 """
291 return request, metadata
293 def post_get_queue(self, response: queue.Queue) -> queue.Queue:
294 """Post-rpc interceptor for get_queue
296 Override in a subclass to manipulate the response
297 after it is returned by the CloudTasks server but before
298 it is returned to user code.
299 """
300 return response
302 def pre_get_task(
303 self, request: cloudtasks.GetTaskRequest, metadata: Sequence[Tuple[str, str]]
304 ) -> Tuple[cloudtasks.GetTaskRequest, Sequence[Tuple[str, str]]]:
305 """Pre-rpc interceptor for get_task
307 Override in a subclass to manipulate the request or metadata
308 before they are sent to the CloudTasks server.
309 """
310 return request, metadata
312 def post_get_task(self, response: task.Task) -> task.Task:
313 """Post-rpc interceptor for get_task
315 Override in a subclass to manipulate the response
316 after it is returned by the CloudTasks server but before
317 it is returned to user code.
318 """
319 return response
321 def pre_list_queues(
322 self, request: cloudtasks.ListQueuesRequest, metadata: Sequence[Tuple[str, str]]
323 ) -> Tuple[cloudtasks.ListQueuesRequest, Sequence[Tuple[str, str]]]:
324 """Pre-rpc interceptor for list_queues
326 Override in a subclass to manipulate the request or metadata
327 before they are sent to the CloudTasks server.
328 """
329 return request, metadata
331 def post_list_queues(
332 self, response: cloudtasks.ListQueuesResponse
333 ) -> cloudtasks.ListQueuesResponse:
334 """Post-rpc interceptor for list_queues
336 Override in a subclass to manipulate the response
337 after it is returned by the CloudTasks server but before
338 it is returned to user code.
339 """
340 return response
342 def pre_list_tasks(
343 self, request: cloudtasks.ListTasksRequest, metadata: Sequence[Tuple[str, str]]
344 ) -> Tuple[cloudtasks.ListTasksRequest, Sequence[Tuple[str, str]]]:
345 """Pre-rpc interceptor for list_tasks
347 Override in a subclass to manipulate the request or metadata
348 before they are sent to the CloudTasks server.
349 """
350 return request, metadata
352 def post_list_tasks(
353 self, response: cloudtasks.ListTasksResponse
354 ) -> cloudtasks.ListTasksResponse:
355 """Post-rpc interceptor for list_tasks
357 Override in a subclass to manipulate the response
358 after it is returned by the CloudTasks server but before
359 it is returned to user code.
360 """
361 return response
363 def pre_pause_queue(
364 self, request: cloudtasks.PauseQueueRequest, metadata: Sequence[Tuple[str, str]]
365 ) -> Tuple[cloudtasks.PauseQueueRequest, Sequence[Tuple[str, str]]]:
366 """Pre-rpc interceptor for pause_queue
368 Override in a subclass to manipulate the request or metadata
369 before they are sent to the CloudTasks server.
370 """
371 return request, metadata
373 def post_pause_queue(self, response: queue.Queue) -> queue.Queue:
374 """Post-rpc interceptor for pause_queue
376 Override in a subclass to manipulate the response
377 after it is returned by the CloudTasks server but before
378 it is returned to user code.
379 """
380 return response
382 def pre_purge_queue(
383 self, request: cloudtasks.PurgeQueueRequest, metadata: Sequence[Tuple[str, str]]
384 ) -> Tuple[cloudtasks.PurgeQueueRequest, Sequence[Tuple[str, str]]]:
385 """Pre-rpc interceptor for purge_queue
387 Override in a subclass to manipulate the request or metadata
388 before they are sent to the CloudTasks server.
389 """
390 return request, metadata
392 def post_purge_queue(self, response: queue.Queue) -> queue.Queue:
393 """Post-rpc interceptor for purge_queue
395 Override in a subclass to manipulate the response
396 after it is returned by the CloudTasks server but before
397 it is returned to user code.
398 """
399 return response
401 def pre_resume_queue(
402 self,
403 request: cloudtasks.ResumeQueueRequest,
404 metadata: Sequence[Tuple[str, str]],
405 ) -> Tuple[cloudtasks.ResumeQueueRequest, Sequence[Tuple[str, str]]]:
406 """Pre-rpc interceptor for resume_queue
408 Override in a subclass to manipulate the request or metadata
409 before they are sent to the CloudTasks server.
410 """
411 return request, metadata
413 def post_resume_queue(self, response: queue.Queue) -> queue.Queue:
414 """Post-rpc interceptor for resume_queue
416 Override in a subclass to manipulate the response
417 after it is returned by the CloudTasks server but before
418 it is returned to user code.
419 """
420 return response
422 def pre_run_task(
423 self, request: cloudtasks.RunTaskRequest, metadata: Sequence[Tuple[str, str]]
424 ) -> Tuple[cloudtasks.RunTaskRequest, Sequence[Tuple[str, str]]]:
425 """Pre-rpc interceptor for run_task
427 Override in a subclass to manipulate the request or metadata
428 before they are sent to the CloudTasks server.
429 """
430 return request, metadata
432 def post_run_task(self, response: task.Task) -> task.Task:
433 """Post-rpc interceptor for run_task
435 Override in a subclass to manipulate the response
436 after it is returned by the CloudTasks server but before
437 it is returned to user code.
438 """
439 return response
441 def pre_set_iam_policy(
442 self,
443 request: iam_policy_pb2.SetIamPolicyRequest,
444 metadata: Sequence[Tuple[str, str]],
445 ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]:
446 """Pre-rpc interceptor for set_iam_policy
448 Override in a subclass to manipulate the request or metadata
449 before they are sent to the CloudTasks server.
450 """
451 return request, metadata
453 def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
454 """Post-rpc interceptor for set_iam_policy
456 Override in a subclass to manipulate the response
457 after it is returned by the CloudTasks server but before
458 it is returned to user code.
459 """
460 return response
462 def pre_test_iam_permissions(
463 self,
464 request: iam_policy_pb2.TestIamPermissionsRequest,
465 metadata: Sequence[Tuple[str, str]],
466 ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]:
467 """Pre-rpc interceptor for test_iam_permissions
469 Override in a subclass to manipulate the request or metadata
470 before they are sent to the CloudTasks server.
471 """
472 return request, metadata
474 def post_test_iam_permissions(
475 self, response: iam_policy_pb2.TestIamPermissionsResponse
476 ) -> iam_policy_pb2.TestIamPermissionsResponse:
477 """Post-rpc interceptor for test_iam_permissions
479 Override in a subclass to manipulate the response
480 after it is returned by the CloudTasks server but before
481 it is returned to user code.
482 """
483 return response
485 def pre_update_queue(
486 self,
487 request: cloudtasks.UpdateQueueRequest,
488 metadata: Sequence[Tuple[str, str]],
489 ) -> Tuple[cloudtasks.UpdateQueueRequest, Sequence[Tuple[str, str]]]:
490 """Pre-rpc interceptor for update_queue
492 Override in a subclass to manipulate the request or metadata
493 before they are sent to the CloudTasks server.
494 """
495 return request, metadata
497 def post_update_queue(self, response: gct_queue.Queue) -> gct_queue.Queue:
498 """Post-rpc interceptor for update_queue
500 Override in a subclass to manipulate the response
501 after it is returned by the CloudTasks server but before
502 it is returned to user code.
503 """
504 return response
507@dataclasses.dataclass
508class CloudTasksRestStub:
509 _session: AuthorizedSession
510 _host: str
511 _interceptor: CloudTasksRestInterceptor
514class CloudTasksRestTransport(CloudTasksTransport):
515 """REST backend transport for CloudTasks.
517 Cloud Tasks allows developers to manage the execution of
518 background work in their applications.
520 This class defines the same methods as the primary client, so the
521 primary client can load the underlying transport implementation
522 and call it.
524 It sends JSON representations of protocol buffers over HTTP/1.1
526 """
528 def __init__(
529 self,
530 *,
531 host: str = "cloudtasks.googleapis.com",
532 credentials: Optional[ga_credentials.Credentials] = None,
533 credentials_file: Optional[str] = None,
534 scopes: Optional[Sequence[str]] = None,
535 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
536 quota_project_id: Optional[str] = None,
537 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
538 always_use_jwt_access: Optional[bool] = False,
539 url_scheme: str = "https",
540 interceptor: Optional[CloudTasksRestInterceptor] = None,
541 api_audience: Optional[str] = None,
542 ) -> None:
543 """Instantiate the transport.
545 Args:
546 host (Optional[str]):
547 The hostname to connect to.
548 credentials (Optional[google.auth.credentials.Credentials]): The
549 authorization credentials to attach to requests. These
550 credentials identify the application to the service; if none
551 are specified, the client will attempt to ascertain the
552 credentials from the environment.
554 credentials_file (Optional[str]): A file with credentials that can
555 be loaded with :func:`google.auth.load_credentials_from_file`.
556 This argument is ignored if ``channel`` is provided.
557 scopes (Optional(Sequence[str])): A list of scopes. This argument is
558 ignored if ``channel`` is provided.
559 client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
560 certificate to configure mutual TLS HTTP channel. It is ignored
561 if ``channel`` is provided.
562 quota_project_id (Optional[str]): An optional project to use for billing
563 and quota.
564 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
565 The client info used to send a user-agent string along with
566 API requests. If ``None``, then default info will be used.
567 Generally, you only need to set this if you are developing
568 your own client library.
569 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
570 be used for service account credentials.
571 url_scheme: the protocol scheme for the API endpoint. Normally
572 "https", but for testing or local servers,
573 "http" can be specified.
574 """
575 # Run the base constructor
576 # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
577 # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
578 # credentials object
579 maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
580 if maybe_url_match is None:
581 raise ValueError(
582 f"Unexpected hostname structure: {host}"
583 ) # pragma: NO COVER
585 url_match_items = maybe_url_match.groupdict()
587 host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
589 super().__init__(
590 host=host,
591 credentials=credentials,
592 client_info=client_info,
593 always_use_jwt_access=always_use_jwt_access,
594 api_audience=api_audience,
595 )
596 self._session = AuthorizedSession(
597 self._credentials, default_host=self.DEFAULT_HOST
598 )
599 if client_cert_source_for_mtls:
600 self._session.configure_mtls_channel(client_cert_source_for_mtls)
601 self._interceptor = interceptor or CloudTasksRestInterceptor()
602 self._prep_wrapped_messages(client_info)
604 class _CreateQueue(CloudTasksRestStub):
605 def __hash__(self):
606 return hash("CreateQueue")
608 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
610 @classmethod
611 def _get_unset_required_fields(cls, message_dict):
612 return {
613 k: v
614 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
615 if k not in message_dict
616 }
618 def __call__(
619 self,
620 request: cloudtasks.CreateQueueRequest,
621 *,
622 retry: OptionalRetry = gapic_v1.method.DEFAULT,
623 timeout: Optional[float] = None,
624 metadata: Sequence[Tuple[str, str]] = (),
625 ) -> gct_queue.Queue:
626 r"""Call the create queue method over HTTP.
628 Args:
629 request (~.cloudtasks.CreateQueueRequest):
630 The request object. Request message for
631 [CreateQueue][google.cloud.tasks.v2.CloudTasks.CreateQueue].
632 retry (google.api_core.retry.Retry): Designation of what errors, if any,
633 should be retried.
634 timeout (float): The timeout for this request.
635 metadata (Sequence[Tuple[str, str]]): Strings which should be
636 sent along with the request as metadata.
638 Returns:
639 ~.gct_queue.Queue:
640 A queue is a container of related
641 tasks. Queues are configured to manage
642 how those tasks are dispatched.
643 Configurable properties include rate
644 limits, retry options, queue types, and
645 others.
647 """
649 http_options: List[Dict[str, str]] = [
650 {
651 "method": "post",
652 "uri": "/v2/{parent=projects/*/locations/*}/queues",
653 "body": "queue",
654 },
655 ]
656 request, metadata = self._interceptor.pre_create_queue(request, metadata)
657 pb_request = cloudtasks.CreateQueueRequest.pb(request)
658 transcoded_request = path_template.transcode(http_options, pb_request)
660 # Jsonify the request body
662 body = json_format.MessageToJson(
663 transcoded_request["body"],
664 including_default_value_fields=False,
665 use_integers_for_enums=True,
666 )
667 uri = transcoded_request["uri"]
668 method = transcoded_request["method"]
670 # Jsonify the query params
671 query_params = json.loads(
672 json_format.MessageToJson(
673 transcoded_request["query_params"],
674 including_default_value_fields=False,
675 use_integers_for_enums=True,
676 )
677 )
678 query_params.update(self._get_unset_required_fields(query_params))
680 query_params["$alt"] = "json;enum-encoding=int"
682 # Send the request
683 headers = dict(metadata)
684 headers["Content-Type"] = "application/json"
685 response = getattr(self._session, method)(
686 "{host}{uri}".format(host=self._host, uri=uri),
687 timeout=timeout,
688 headers=headers,
689 params=rest_helpers.flatten_query_params(query_params, strict=True),
690 data=body,
691 )
693 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
694 # subclass.
695 if response.status_code >= 400:
696 raise core_exceptions.from_http_response(response)
698 # Return the response
699 resp = gct_queue.Queue()
700 pb_resp = gct_queue.Queue.pb(resp)
702 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
703 resp = self._interceptor.post_create_queue(resp)
704 return resp
706 class _CreateTask(CloudTasksRestStub):
707 def __hash__(self):
708 return hash("CreateTask")
710 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
712 @classmethod
713 def _get_unset_required_fields(cls, message_dict):
714 return {
715 k: v
716 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
717 if k not in message_dict
718 }
720 def __call__(
721 self,
722 request: cloudtasks.CreateTaskRequest,
723 *,
724 retry: OptionalRetry = gapic_v1.method.DEFAULT,
725 timeout: Optional[float] = None,
726 metadata: Sequence[Tuple[str, str]] = (),
727 ) -> gct_task.Task:
728 r"""Call the create task method over HTTP.
730 Args:
731 request (~.cloudtasks.CreateTaskRequest):
732 The request object. Request message for
733 [CreateTask][google.cloud.tasks.v2.CloudTasks.CreateTask].
734 retry (google.api_core.retry.Retry): Designation of what errors, if any,
735 should be retried.
736 timeout (float): The timeout for this request.
737 metadata (Sequence[Tuple[str, str]]): Strings which should be
738 sent along with the request as metadata.
740 Returns:
741 ~.gct_task.Task:
742 A unit of scheduled work.
743 """
745 http_options: List[Dict[str, str]] = [
746 {
747 "method": "post",
748 "uri": "/v2/{parent=projects/*/locations/*/queues/*}/tasks",
749 "body": "*",
750 },
751 ]
752 request, metadata = self._interceptor.pre_create_task(request, metadata)
753 pb_request = cloudtasks.CreateTaskRequest.pb(request)
754 transcoded_request = path_template.transcode(http_options, pb_request)
756 # Jsonify the request body
758 body = json_format.MessageToJson(
759 transcoded_request["body"],
760 including_default_value_fields=False,
761 use_integers_for_enums=True,
762 )
763 uri = transcoded_request["uri"]
764 method = transcoded_request["method"]
766 # Jsonify the query params
767 query_params = json.loads(
768 json_format.MessageToJson(
769 transcoded_request["query_params"],
770 including_default_value_fields=False,
771 use_integers_for_enums=True,
772 )
773 )
774 query_params.update(self._get_unset_required_fields(query_params))
776 query_params["$alt"] = "json;enum-encoding=int"
778 # Send the request
779 headers = dict(metadata)
780 headers["Content-Type"] = "application/json"
781 response = getattr(self._session, method)(
782 "{host}{uri}".format(host=self._host, uri=uri),
783 timeout=timeout,
784 headers=headers,
785 params=rest_helpers.flatten_query_params(query_params, strict=True),
786 data=body,
787 )
789 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
790 # subclass.
791 if response.status_code >= 400:
792 raise core_exceptions.from_http_response(response)
794 # Return the response
795 resp = gct_task.Task()
796 pb_resp = gct_task.Task.pb(resp)
798 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
799 resp = self._interceptor.post_create_task(resp)
800 return resp
802 class _DeleteQueue(CloudTasksRestStub):
803 def __hash__(self):
804 return hash("DeleteQueue")
806 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
808 @classmethod
809 def _get_unset_required_fields(cls, message_dict):
810 return {
811 k: v
812 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
813 if k not in message_dict
814 }
816 def __call__(
817 self,
818 request: cloudtasks.DeleteQueueRequest,
819 *,
820 retry: OptionalRetry = gapic_v1.method.DEFAULT,
821 timeout: Optional[float] = None,
822 metadata: Sequence[Tuple[str, str]] = (),
823 ):
824 r"""Call the delete queue method over HTTP.
826 Args:
827 request (~.cloudtasks.DeleteQueueRequest):
828 The request object. Request message for
829 [DeleteQueue][google.cloud.tasks.v2.CloudTasks.DeleteQueue].
830 retry (google.api_core.retry.Retry): Designation of what errors, if any,
831 should be retried.
832 timeout (float): The timeout for this request.
833 metadata (Sequence[Tuple[str, str]]): Strings which should be
834 sent along with the request as metadata.
835 """
837 http_options: List[Dict[str, str]] = [
838 {
839 "method": "delete",
840 "uri": "/v2/{name=projects/*/locations/*/queues/*}",
841 },
842 ]
843 request, metadata = self._interceptor.pre_delete_queue(request, metadata)
844 pb_request = cloudtasks.DeleteQueueRequest.pb(request)
845 transcoded_request = path_template.transcode(http_options, pb_request)
847 uri = transcoded_request["uri"]
848 method = transcoded_request["method"]
850 # Jsonify the query params
851 query_params = json.loads(
852 json_format.MessageToJson(
853 transcoded_request["query_params"],
854 including_default_value_fields=False,
855 use_integers_for_enums=True,
856 )
857 )
858 query_params.update(self._get_unset_required_fields(query_params))
860 query_params["$alt"] = "json;enum-encoding=int"
862 # Send the request
863 headers = dict(metadata)
864 headers["Content-Type"] = "application/json"
865 response = getattr(self._session, method)(
866 "{host}{uri}".format(host=self._host, uri=uri),
867 timeout=timeout,
868 headers=headers,
869 params=rest_helpers.flatten_query_params(query_params, strict=True),
870 )
872 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
873 # subclass.
874 if response.status_code >= 400:
875 raise core_exceptions.from_http_response(response)
877 class _DeleteTask(CloudTasksRestStub):
878 def __hash__(self):
879 return hash("DeleteTask")
881 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
883 @classmethod
884 def _get_unset_required_fields(cls, message_dict):
885 return {
886 k: v
887 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
888 if k not in message_dict
889 }
891 def __call__(
892 self,
893 request: cloudtasks.DeleteTaskRequest,
894 *,
895 retry: OptionalRetry = gapic_v1.method.DEFAULT,
896 timeout: Optional[float] = None,
897 metadata: Sequence[Tuple[str, str]] = (),
898 ):
899 r"""Call the delete task method over HTTP.
901 Args:
902 request (~.cloudtasks.DeleteTaskRequest):
903 The request object. Request message for deleting a task using
904 [DeleteTask][google.cloud.tasks.v2.CloudTasks.DeleteTask].
905 retry (google.api_core.retry.Retry): Designation of what errors, if any,
906 should be retried.
907 timeout (float): The timeout for this request.
908 metadata (Sequence[Tuple[str, str]]): Strings which should be
909 sent along with the request as metadata.
910 """
912 http_options: List[Dict[str, str]] = [
913 {
914 "method": "delete",
915 "uri": "/v2/{name=projects/*/locations/*/queues/*/tasks/*}",
916 },
917 ]
918 request, metadata = self._interceptor.pre_delete_task(request, metadata)
919 pb_request = cloudtasks.DeleteTaskRequest.pb(request)
920 transcoded_request = path_template.transcode(http_options, pb_request)
922 uri = transcoded_request["uri"]
923 method = transcoded_request["method"]
925 # Jsonify the query params
926 query_params = json.loads(
927 json_format.MessageToJson(
928 transcoded_request["query_params"],
929 including_default_value_fields=False,
930 use_integers_for_enums=True,
931 )
932 )
933 query_params.update(self._get_unset_required_fields(query_params))
935 query_params["$alt"] = "json;enum-encoding=int"
937 # Send the request
938 headers = dict(metadata)
939 headers["Content-Type"] = "application/json"
940 response = getattr(self._session, method)(
941 "{host}{uri}".format(host=self._host, uri=uri),
942 timeout=timeout,
943 headers=headers,
944 params=rest_helpers.flatten_query_params(query_params, strict=True),
945 )
947 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
948 # subclass.
949 if response.status_code >= 400:
950 raise core_exceptions.from_http_response(response)
952 class _GetIamPolicy(CloudTasksRestStub):
953 def __hash__(self):
954 return hash("GetIamPolicy")
956 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
958 @classmethod
959 def _get_unset_required_fields(cls, message_dict):
960 return {
961 k: v
962 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
963 if k not in message_dict
964 }
966 def __call__(
967 self,
968 request: iam_policy_pb2.GetIamPolicyRequest,
969 *,
970 retry: OptionalRetry = gapic_v1.method.DEFAULT,
971 timeout: Optional[float] = None,
972 metadata: Sequence[Tuple[str, str]] = (),
973 ) -> policy_pb2.Policy:
974 r"""Call the get iam policy method over HTTP.
976 Args:
977 request (~.iam_policy_pb2.GetIamPolicyRequest):
978 The request object. Request message for ``GetIamPolicy`` method.
979 retry (google.api_core.retry.Retry): Designation of what errors, if any,
980 should be retried.
981 timeout (float): The timeout for this request.
982 metadata (Sequence[Tuple[str, str]]): Strings which should be
983 sent along with the request as metadata.
985 Returns:
986 ~.policy_pb2.Policy:
987 An Identity and Access Management (IAM) policy, which
988 specifies access controls for Google Cloud resources.
990 A ``Policy`` is a collection of ``bindings``. A
991 ``binding`` binds one or more ``members``, or
992 principals, to a single ``role``. Principals can be user
993 accounts, service accounts, Google groups, and domains
994 (such as G Suite). A ``role`` is a named list of
995 permissions; each ``role`` can be an IAM predefined role
996 or a user-created custom role.
998 For some types of Google Cloud resources, a ``binding``
999 can also specify a ``condition``, which is a logical
1000 expression that allows access to a resource only if the
1001 expression evaluates to ``true``. A condition can add
1002 constraints based on attributes of the request, the
1003 resource, or both. To learn which resources support
1004 conditions in their IAM policies, see the `IAM
1005 documentation <https://cloud.google.com/iam/help/conditions/resource-policies>`__.
1007 **JSON example:**
1009 ::
1011 {
1012 "bindings": [
1013 {
1014 "role": "roles/resourcemanager.organizationAdmin",
1015 "members": [
1016 "user:mike@example.com",
1017 "group:admins@example.com",
1018 "domain:google.com",
1019 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
1020 ]
1021 },
1022 {
1023 "role": "roles/resourcemanager.organizationViewer",
1024 "members": [
1025 "user:eve@example.com"
1026 ],
1027 "condition": {
1028 "title": "expirable access",
1029 "description": "Does not grant access after Sep 2020",
1030 "expression": "request.time <
1031 timestamp('2020-10-01T00:00:00.000Z')",
1032 }
1033 }
1034 ],
1035 "etag": "BwWWja0YfJA=",
1036 "version": 3
1037 }
1039 **YAML example:**
1041 ::
1043 bindings:
1044 - members:
1045 - user:mike@example.com
1046 - group:admins@example.com
1047 - domain:google.com
1048 - serviceAccount:my-project-id@appspot.gserviceaccount.com
1049 role: roles/resourcemanager.organizationAdmin
1050 - members:
1051 - user:eve@example.com
1052 role: roles/resourcemanager.organizationViewer
1053 condition:
1054 title: expirable access
1055 description: Does not grant access after Sep 2020
1056 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
1057 etag: BwWWja0YfJA=
1058 version: 3
1060 For a description of IAM and its features, see the `IAM
1061 documentation <https://cloud.google.com/iam/docs/>`__.
1063 """
1065 http_options: List[Dict[str, str]] = [
1066 {
1067 "method": "post",
1068 "uri": "/v2/{resource=projects/*/locations/*/queues/*}:getIamPolicy",
1069 "body": "*",
1070 },
1071 ]
1072 request, metadata = self._interceptor.pre_get_iam_policy(request, metadata)
1073 pb_request = request
1074 transcoded_request = path_template.transcode(http_options, pb_request)
1076 # Jsonify the request body
1078 body = json_format.MessageToJson(
1079 transcoded_request["body"],
1080 including_default_value_fields=False,
1081 use_integers_for_enums=True,
1082 )
1083 uri = transcoded_request["uri"]
1084 method = transcoded_request["method"]
1086 # Jsonify the query params
1087 query_params = json.loads(
1088 json_format.MessageToJson(
1089 transcoded_request["query_params"],
1090 including_default_value_fields=False,
1091 use_integers_for_enums=True,
1092 )
1093 )
1094 query_params.update(self._get_unset_required_fields(query_params))
1096 query_params["$alt"] = "json;enum-encoding=int"
1098 # Send the request
1099 headers = dict(metadata)
1100 headers["Content-Type"] = "application/json"
1101 response = getattr(self._session, method)(
1102 "{host}{uri}".format(host=self._host, uri=uri),
1103 timeout=timeout,
1104 headers=headers,
1105 params=rest_helpers.flatten_query_params(query_params, strict=True),
1106 data=body,
1107 )
1109 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1110 # subclass.
1111 if response.status_code >= 400:
1112 raise core_exceptions.from_http_response(response)
1114 # Return the response
1115 resp = policy_pb2.Policy()
1116 pb_resp = resp
1118 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1119 resp = self._interceptor.post_get_iam_policy(resp)
1120 return resp
1122 class _GetQueue(CloudTasksRestStub):
1123 def __hash__(self):
1124 return hash("GetQueue")
1126 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1128 @classmethod
1129 def _get_unset_required_fields(cls, message_dict):
1130 return {
1131 k: v
1132 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1133 if k not in message_dict
1134 }
1136 def __call__(
1137 self,
1138 request: cloudtasks.GetQueueRequest,
1139 *,
1140 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1141 timeout: Optional[float] = None,
1142 metadata: Sequence[Tuple[str, str]] = (),
1143 ) -> queue.Queue:
1144 r"""Call the get queue method over HTTP.
1146 Args:
1147 request (~.cloudtasks.GetQueueRequest):
1148 The request object. Request message for
1149 [GetQueue][google.cloud.tasks.v2.CloudTasks.GetQueue].
1150 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1151 should be retried.
1152 timeout (float): The timeout for this request.
1153 metadata (Sequence[Tuple[str, str]]): Strings which should be
1154 sent along with the request as metadata.
1156 Returns:
1157 ~.queue.Queue:
1158 A queue is a container of related
1159 tasks. Queues are configured to manage
1160 how those tasks are dispatched.
1161 Configurable properties include rate
1162 limits, retry options, queue types, and
1163 others.
1165 """
1167 http_options: List[Dict[str, str]] = [
1168 {
1169 "method": "get",
1170 "uri": "/v2/{name=projects/*/locations/*/queues/*}",
1171 },
1172 ]
1173 request, metadata = self._interceptor.pre_get_queue(request, metadata)
1174 pb_request = cloudtasks.GetQueueRequest.pb(request)
1175 transcoded_request = path_template.transcode(http_options, pb_request)
1177 uri = transcoded_request["uri"]
1178 method = transcoded_request["method"]
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))
1190 query_params["$alt"] = "json;enum-encoding=int"
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 )
1202 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1203 # subclass.
1204 if response.status_code >= 400:
1205 raise core_exceptions.from_http_response(response)
1207 # Return the response
1208 resp = queue.Queue()
1209 pb_resp = queue.Queue.pb(resp)
1211 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1212 resp = self._interceptor.post_get_queue(resp)
1213 return resp
1215 class _GetTask(CloudTasksRestStub):
1216 def __hash__(self):
1217 return hash("GetTask")
1219 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1221 @classmethod
1222 def _get_unset_required_fields(cls, message_dict):
1223 return {
1224 k: v
1225 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1226 if k not in message_dict
1227 }
1229 def __call__(
1230 self,
1231 request: cloudtasks.GetTaskRequest,
1232 *,
1233 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1234 timeout: Optional[float] = None,
1235 metadata: Sequence[Tuple[str, str]] = (),
1236 ) -> task.Task:
1237 r"""Call the get task method over HTTP.
1239 Args:
1240 request (~.cloudtasks.GetTaskRequest):
1241 The request object. Request message for getting a task using
1242 [GetTask][google.cloud.tasks.v2.CloudTasks.GetTask].
1243 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1244 should be retried.
1245 timeout (float): The timeout for this request.
1246 metadata (Sequence[Tuple[str, str]]): Strings which should be
1247 sent along with the request as metadata.
1249 Returns:
1250 ~.task.Task:
1251 A unit of scheduled work.
1252 """
1254 http_options: List[Dict[str, str]] = [
1255 {
1256 "method": "get",
1257 "uri": "/v2/{name=projects/*/locations/*/queues/*/tasks/*}",
1258 },
1259 ]
1260 request, metadata = self._interceptor.pre_get_task(request, metadata)
1261 pb_request = cloudtasks.GetTaskRequest.pb(request)
1262 transcoded_request = path_template.transcode(http_options, pb_request)
1264 uri = transcoded_request["uri"]
1265 method = transcoded_request["method"]
1267 # Jsonify the query params
1268 query_params = json.loads(
1269 json_format.MessageToJson(
1270 transcoded_request["query_params"],
1271 including_default_value_fields=False,
1272 use_integers_for_enums=True,
1273 )
1274 )
1275 query_params.update(self._get_unset_required_fields(query_params))
1277 query_params["$alt"] = "json;enum-encoding=int"
1279 # Send the request
1280 headers = dict(metadata)
1281 headers["Content-Type"] = "application/json"
1282 response = getattr(self._session, method)(
1283 "{host}{uri}".format(host=self._host, uri=uri),
1284 timeout=timeout,
1285 headers=headers,
1286 params=rest_helpers.flatten_query_params(query_params, strict=True),
1287 )
1289 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1290 # subclass.
1291 if response.status_code >= 400:
1292 raise core_exceptions.from_http_response(response)
1294 # Return the response
1295 resp = task.Task()
1296 pb_resp = task.Task.pb(resp)
1298 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1299 resp = self._interceptor.post_get_task(resp)
1300 return resp
1302 class _ListQueues(CloudTasksRestStub):
1303 def __hash__(self):
1304 return hash("ListQueues")
1306 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1308 @classmethod
1309 def _get_unset_required_fields(cls, message_dict):
1310 return {
1311 k: v
1312 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1313 if k not in message_dict
1314 }
1316 def __call__(
1317 self,
1318 request: cloudtasks.ListQueuesRequest,
1319 *,
1320 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1321 timeout: Optional[float] = None,
1322 metadata: Sequence[Tuple[str, str]] = (),
1323 ) -> cloudtasks.ListQueuesResponse:
1324 r"""Call the list queues method over HTTP.
1326 Args:
1327 request (~.cloudtasks.ListQueuesRequest):
1328 The request object. Request message for
1329 [ListQueues][google.cloud.tasks.v2.CloudTasks.ListQueues].
1330 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1331 should be retried.
1332 timeout (float): The timeout for this request.
1333 metadata (Sequence[Tuple[str, str]]): Strings which should be
1334 sent along with the request as metadata.
1336 Returns:
1337 ~.cloudtasks.ListQueuesResponse:
1338 Response message for
1339 [ListQueues][google.cloud.tasks.v2.CloudTasks.ListQueues].
1341 """
1343 http_options: List[Dict[str, str]] = [
1344 {
1345 "method": "get",
1346 "uri": "/v2/{parent=projects/*/locations/*}/queues",
1347 },
1348 ]
1349 request, metadata = self._interceptor.pre_list_queues(request, metadata)
1350 pb_request = cloudtasks.ListQueuesRequest.pb(request)
1351 transcoded_request = path_template.transcode(http_options, pb_request)
1353 uri = transcoded_request["uri"]
1354 method = transcoded_request["method"]
1356 # Jsonify the query params
1357 query_params = json.loads(
1358 json_format.MessageToJson(
1359 transcoded_request["query_params"],
1360 including_default_value_fields=False,
1361 use_integers_for_enums=True,
1362 )
1363 )
1364 query_params.update(self._get_unset_required_fields(query_params))
1366 query_params["$alt"] = "json;enum-encoding=int"
1368 # Send the request
1369 headers = dict(metadata)
1370 headers["Content-Type"] = "application/json"
1371 response = getattr(self._session, method)(
1372 "{host}{uri}".format(host=self._host, uri=uri),
1373 timeout=timeout,
1374 headers=headers,
1375 params=rest_helpers.flatten_query_params(query_params, strict=True),
1376 )
1378 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1379 # subclass.
1380 if response.status_code >= 400:
1381 raise core_exceptions.from_http_response(response)
1383 # Return the response
1384 resp = cloudtasks.ListQueuesResponse()
1385 pb_resp = cloudtasks.ListQueuesResponse.pb(resp)
1387 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1388 resp = self._interceptor.post_list_queues(resp)
1389 return resp
1391 class _ListTasks(CloudTasksRestStub):
1392 def __hash__(self):
1393 return hash("ListTasks")
1395 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1397 @classmethod
1398 def _get_unset_required_fields(cls, message_dict):
1399 return {
1400 k: v
1401 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1402 if k not in message_dict
1403 }
1405 def __call__(
1406 self,
1407 request: cloudtasks.ListTasksRequest,
1408 *,
1409 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1410 timeout: Optional[float] = None,
1411 metadata: Sequence[Tuple[str, str]] = (),
1412 ) -> cloudtasks.ListTasksResponse:
1413 r"""Call the list tasks method over HTTP.
1415 Args:
1416 request (~.cloudtasks.ListTasksRequest):
1417 The request object. Request message for listing tasks using
1418 [ListTasks][google.cloud.tasks.v2.CloudTasks.ListTasks].
1419 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1420 should be retried.
1421 timeout (float): The timeout for this request.
1422 metadata (Sequence[Tuple[str, str]]): Strings which should be
1423 sent along with the request as metadata.
1425 Returns:
1426 ~.cloudtasks.ListTasksResponse:
1427 Response message for listing tasks using
1428 [ListTasks][google.cloud.tasks.v2.CloudTasks.ListTasks].
1430 """
1432 http_options: List[Dict[str, str]] = [
1433 {
1434 "method": "get",
1435 "uri": "/v2/{parent=projects/*/locations/*/queues/*}/tasks",
1436 },
1437 ]
1438 request, metadata = self._interceptor.pre_list_tasks(request, metadata)
1439 pb_request = cloudtasks.ListTasksRequest.pb(request)
1440 transcoded_request = path_template.transcode(http_options, pb_request)
1442 uri = transcoded_request["uri"]
1443 method = transcoded_request["method"]
1445 # Jsonify the query params
1446 query_params = json.loads(
1447 json_format.MessageToJson(
1448 transcoded_request["query_params"],
1449 including_default_value_fields=False,
1450 use_integers_for_enums=True,
1451 )
1452 )
1453 query_params.update(self._get_unset_required_fields(query_params))
1455 query_params["$alt"] = "json;enum-encoding=int"
1457 # Send the request
1458 headers = dict(metadata)
1459 headers["Content-Type"] = "application/json"
1460 response = getattr(self._session, method)(
1461 "{host}{uri}".format(host=self._host, uri=uri),
1462 timeout=timeout,
1463 headers=headers,
1464 params=rest_helpers.flatten_query_params(query_params, strict=True),
1465 )
1467 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1468 # subclass.
1469 if response.status_code >= 400:
1470 raise core_exceptions.from_http_response(response)
1472 # Return the response
1473 resp = cloudtasks.ListTasksResponse()
1474 pb_resp = cloudtasks.ListTasksResponse.pb(resp)
1476 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1477 resp = self._interceptor.post_list_tasks(resp)
1478 return resp
1480 class _PauseQueue(CloudTasksRestStub):
1481 def __hash__(self):
1482 return hash("PauseQueue")
1484 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1486 @classmethod
1487 def _get_unset_required_fields(cls, message_dict):
1488 return {
1489 k: v
1490 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1491 if k not in message_dict
1492 }
1494 def __call__(
1495 self,
1496 request: cloudtasks.PauseQueueRequest,
1497 *,
1498 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1499 timeout: Optional[float] = None,
1500 metadata: Sequence[Tuple[str, str]] = (),
1501 ) -> queue.Queue:
1502 r"""Call the pause queue method over HTTP.
1504 Args:
1505 request (~.cloudtasks.PauseQueueRequest):
1506 The request object. Request message for
1507 [PauseQueue][google.cloud.tasks.v2.CloudTasks.PauseQueue].
1508 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1509 should be retried.
1510 timeout (float): The timeout for this request.
1511 metadata (Sequence[Tuple[str, str]]): Strings which should be
1512 sent along with the request as metadata.
1514 Returns:
1515 ~.queue.Queue:
1516 A queue is a container of related
1517 tasks. Queues are configured to manage
1518 how those tasks are dispatched.
1519 Configurable properties include rate
1520 limits, retry options, queue types, and
1521 others.
1523 """
1525 http_options: List[Dict[str, str]] = [
1526 {
1527 "method": "post",
1528 "uri": "/v2/{name=projects/*/locations/*/queues/*}:pause",
1529 "body": "*",
1530 },
1531 ]
1532 request, metadata = self._interceptor.pre_pause_queue(request, metadata)
1533 pb_request = cloudtasks.PauseQueueRequest.pb(request)
1534 transcoded_request = path_template.transcode(http_options, pb_request)
1536 # Jsonify the request body
1538 body = json_format.MessageToJson(
1539 transcoded_request["body"],
1540 including_default_value_fields=False,
1541 use_integers_for_enums=True,
1542 )
1543 uri = transcoded_request["uri"]
1544 method = transcoded_request["method"]
1546 # Jsonify the query params
1547 query_params = json.loads(
1548 json_format.MessageToJson(
1549 transcoded_request["query_params"],
1550 including_default_value_fields=False,
1551 use_integers_for_enums=True,
1552 )
1553 )
1554 query_params.update(self._get_unset_required_fields(query_params))
1556 query_params["$alt"] = "json;enum-encoding=int"
1558 # Send the request
1559 headers = dict(metadata)
1560 headers["Content-Type"] = "application/json"
1561 response = getattr(self._session, method)(
1562 "{host}{uri}".format(host=self._host, uri=uri),
1563 timeout=timeout,
1564 headers=headers,
1565 params=rest_helpers.flatten_query_params(query_params, strict=True),
1566 data=body,
1567 )
1569 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1570 # subclass.
1571 if response.status_code >= 400:
1572 raise core_exceptions.from_http_response(response)
1574 # Return the response
1575 resp = queue.Queue()
1576 pb_resp = queue.Queue.pb(resp)
1578 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1579 resp = self._interceptor.post_pause_queue(resp)
1580 return resp
1582 class _PurgeQueue(CloudTasksRestStub):
1583 def __hash__(self):
1584 return hash("PurgeQueue")
1586 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1588 @classmethod
1589 def _get_unset_required_fields(cls, message_dict):
1590 return {
1591 k: v
1592 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1593 if k not in message_dict
1594 }
1596 def __call__(
1597 self,
1598 request: cloudtasks.PurgeQueueRequest,
1599 *,
1600 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1601 timeout: Optional[float] = None,
1602 metadata: Sequence[Tuple[str, str]] = (),
1603 ) -> queue.Queue:
1604 r"""Call the purge queue method over HTTP.
1606 Args:
1607 request (~.cloudtasks.PurgeQueueRequest):
1608 The request object. Request message for
1609 [PurgeQueue][google.cloud.tasks.v2.CloudTasks.PurgeQueue].
1610 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1611 should be retried.
1612 timeout (float): The timeout for this request.
1613 metadata (Sequence[Tuple[str, str]]): Strings which should be
1614 sent along with the request as metadata.
1616 Returns:
1617 ~.queue.Queue:
1618 A queue is a container of related
1619 tasks. Queues are configured to manage
1620 how those tasks are dispatched.
1621 Configurable properties include rate
1622 limits, retry options, queue types, and
1623 others.
1625 """
1627 http_options: List[Dict[str, str]] = [
1628 {
1629 "method": "post",
1630 "uri": "/v2/{name=projects/*/locations/*/queues/*}:purge",
1631 "body": "*",
1632 },
1633 ]
1634 request, metadata = self._interceptor.pre_purge_queue(request, metadata)
1635 pb_request = cloudtasks.PurgeQueueRequest.pb(request)
1636 transcoded_request = path_template.transcode(http_options, pb_request)
1638 # Jsonify the request body
1640 body = json_format.MessageToJson(
1641 transcoded_request["body"],
1642 including_default_value_fields=False,
1643 use_integers_for_enums=True,
1644 )
1645 uri = transcoded_request["uri"]
1646 method = transcoded_request["method"]
1648 # Jsonify the query params
1649 query_params = json.loads(
1650 json_format.MessageToJson(
1651 transcoded_request["query_params"],
1652 including_default_value_fields=False,
1653 use_integers_for_enums=True,
1654 )
1655 )
1656 query_params.update(self._get_unset_required_fields(query_params))
1658 query_params["$alt"] = "json;enum-encoding=int"
1660 # Send the request
1661 headers = dict(metadata)
1662 headers["Content-Type"] = "application/json"
1663 response = getattr(self._session, method)(
1664 "{host}{uri}".format(host=self._host, uri=uri),
1665 timeout=timeout,
1666 headers=headers,
1667 params=rest_helpers.flatten_query_params(query_params, strict=True),
1668 data=body,
1669 )
1671 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1672 # subclass.
1673 if response.status_code >= 400:
1674 raise core_exceptions.from_http_response(response)
1676 # Return the response
1677 resp = queue.Queue()
1678 pb_resp = queue.Queue.pb(resp)
1680 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1681 resp = self._interceptor.post_purge_queue(resp)
1682 return resp
1684 class _ResumeQueue(CloudTasksRestStub):
1685 def __hash__(self):
1686 return hash("ResumeQueue")
1688 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1690 @classmethod
1691 def _get_unset_required_fields(cls, message_dict):
1692 return {
1693 k: v
1694 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1695 if k not in message_dict
1696 }
1698 def __call__(
1699 self,
1700 request: cloudtasks.ResumeQueueRequest,
1701 *,
1702 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1703 timeout: Optional[float] = None,
1704 metadata: Sequence[Tuple[str, str]] = (),
1705 ) -> queue.Queue:
1706 r"""Call the resume queue method over HTTP.
1708 Args:
1709 request (~.cloudtasks.ResumeQueueRequest):
1710 The request object. Request message for
1711 [ResumeQueue][google.cloud.tasks.v2.CloudTasks.ResumeQueue].
1712 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1713 should be retried.
1714 timeout (float): The timeout for this request.
1715 metadata (Sequence[Tuple[str, str]]): Strings which should be
1716 sent along with the request as metadata.
1718 Returns:
1719 ~.queue.Queue:
1720 A queue is a container of related
1721 tasks. Queues are configured to manage
1722 how those tasks are dispatched.
1723 Configurable properties include rate
1724 limits, retry options, queue types, and
1725 others.
1727 """
1729 http_options: List[Dict[str, str]] = [
1730 {
1731 "method": "post",
1732 "uri": "/v2/{name=projects/*/locations/*/queues/*}:resume",
1733 "body": "*",
1734 },
1735 ]
1736 request, metadata = self._interceptor.pre_resume_queue(request, metadata)
1737 pb_request = cloudtasks.ResumeQueueRequest.pb(request)
1738 transcoded_request = path_template.transcode(http_options, pb_request)
1740 # Jsonify the request body
1742 body = json_format.MessageToJson(
1743 transcoded_request["body"],
1744 including_default_value_fields=False,
1745 use_integers_for_enums=True,
1746 )
1747 uri = transcoded_request["uri"]
1748 method = transcoded_request["method"]
1750 # Jsonify the query params
1751 query_params = json.loads(
1752 json_format.MessageToJson(
1753 transcoded_request["query_params"],
1754 including_default_value_fields=False,
1755 use_integers_for_enums=True,
1756 )
1757 )
1758 query_params.update(self._get_unset_required_fields(query_params))
1760 query_params["$alt"] = "json;enum-encoding=int"
1762 # Send the request
1763 headers = dict(metadata)
1764 headers["Content-Type"] = "application/json"
1765 response = getattr(self._session, method)(
1766 "{host}{uri}".format(host=self._host, uri=uri),
1767 timeout=timeout,
1768 headers=headers,
1769 params=rest_helpers.flatten_query_params(query_params, strict=True),
1770 data=body,
1771 )
1773 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1774 # subclass.
1775 if response.status_code >= 400:
1776 raise core_exceptions.from_http_response(response)
1778 # Return the response
1779 resp = queue.Queue()
1780 pb_resp = queue.Queue.pb(resp)
1782 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1783 resp = self._interceptor.post_resume_queue(resp)
1784 return resp
1786 class _RunTask(CloudTasksRestStub):
1787 def __hash__(self):
1788 return hash("RunTask")
1790 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1792 @classmethod
1793 def _get_unset_required_fields(cls, message_dict):
1794 return {
1795 k: v
1796 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1797 if k not in message_dict
1798 }
1800 def __call__(
1801 self,
1802 request: cloudtasks.RunTaskRequest,
1803 *,
1804 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1805 timeout: Optional[float] = None,
1806 metadata: Sequence[Tuple[str, str]] = (),
1807 ) -> task.Task:
1808 r"""Call the run task method over HTTP.
1810 Args:
1811 request (~.cloudtasks.RunTaskRequest):
1812 The request object. Request message for forcing a task to run now using
1813 [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask].
1814 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1815 should be retried.
1816 timeout (float): The timeout for this request.
1817 metadata (Sequence[Tuple[str, str]]): Strings which should be
1818 sent along with the request as metadata.
1820 Returns:
1821 ~.task.Task:
1822 A unit of scheduled work.
1823 """
1825 http_options: List[Dict[str, str]] = [
1826 {
1827 "method": "post",
1828 "uri": "/v2/{name=projects/*/locations/*/queues/*/tasks/*}:run",
1829 "body": "*",
1830 },
1831 ]
1832 request, metadata = self._interceptor.pre_run_task(request, metadata)
1833 pb_request = cloudtasks.RunTaskRequest.pb(request)
1834 transcoded_request = path_template.transcode(http_options, pb_request)
1836 # Jsonify the request body
1838 body = json_format.MessageToJson(
1839 transcoded_request["body"],
1840 including_default_value_fields=False,
1841 use_integers_for_enums=True,
1842 )
1843 uri = transcoded_request["uri"]
1844 method = transcoded_request["method"]
1846 # Jsonify the query params
1847 query_params = json.loads(
1848 json_format.MessageToJson(
1849 transcoded_request["query_params"],
1850 including_default_value_fields=False,
1851 use_integers_for_enums=True,
1852 )
1853 )
1854 query_params.update(self._get_unset_required_fields(query_params))
1856 query_params["$alt"] = "json;enum-encoding=int"
1858 # Send the request
1859 headers = dict(metadata)
1860 headers["Content-Type"] = "application/json"
1861 response = getattr(self._session, method)(
1862 "{host}{uri}".format(host=self._host, uri=uri),
1863 timeout=timeout,
1864 headers=headers,
1865 params=rest_helpers.flatten_query_params(query_params, strict=True),
1866 data=body,
1867 )
1869 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1870 # subclass.
1871 if response.status_code >= 400:
1872 raise core_exceptions.from_http_response(response)
1874 # Return the response
1875 resp = task.Task()
1876 pb_resp = task.Task.pb(resp)
1878 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1879 resp = self._interceptor.post_run_task(resp)
1880 return resp
1882 class _SetIamPolicy(CloudTasksRestStub):
1883 def __hash__(self):
1884 return hash("SetIamPolicy")
1886 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1888 @classmethod
1889 def _get_unset_required_fields(cls, message_dict):
1890 return {
1891 k: v
1892 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1893 if k not in message_dict
1894 }
1896 def __call__(
1897 self,
1898 request: iam_policy_pb2.SetIamPolicyRequest,
1899 *,
1900 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1901 timeout: Optional[float] = None,
1902 metadata: Sequence[Tuple[str, str]] = (),
1903 ) -> policy_pb2.Policy:
1904 r"""Call the set iam policy method over HTTP.
1906 Args:
1907 request (~.iam_policy_pb2.SetIamPolicyRequest):
1908 The request object. Request message for ``SetIamPolicy`` method.
1909 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1910 should be retried.
1911 timeout (float): The timeout for this request.
1912 metadata (Sequence[Tuple[str, str]]): Strings which should be
1913 sent along with the request as metadata.
1915 Returns:
1916 ~.policy_pb2.Policy:
1917 An Identity and Access Management (IAM) policy, which
1918 specifies access controls for Google Cloud resources.
1920 A ``Policy`` is a collection of ``bindings``. A
1921 ``binding`` binds one or more ``members``, or
1922 principals, to a single ``role``. Principals can be user
1923 accounts, service accounts, Google groups, and domains
1924 (such as G Suite). A ``role`` is a named list of
1925 permissions; each ``role`` can be an IAM predefined role
1926 or a user-created custom role.
1928 For some types of Google Cloud resources, a ``binding``
1929 can also specify a ``condition``, which is a logical
1930 expression that allows access to a resource only if the
1931 expression evaluates to ``true``. A condition can add
1932 constraints based on attributes of the request, the
1933 resource, or both. To learn which resources support
1934 conditions in their IAM policies, see the `IAM
1935 documentation <https://cloud.google.com/iam/help/conditions/resource-policies>`__.
1937 **JSON example:**
1939 ::
1941 {
1942 "bindings": [
1943 {
1944 "role": "roles/resourcemanager.organizationAdmin",
1945 "members": [
1946 "user:mike@example.com",
1947 "group:admins@example.com",
1948 "domain:google.com",
1949 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
1950 ]
1951 },
1952 {
1953 "role": "roles/resourcemanager.organizationViewer",
1954 "members": [
1955 "user:eve@example.com"
1956 ],
1957 "condition": {
1958 "title": "expirable access",
1959 "description": "Does not grant access after Sep 2020",
1960 "expression": "request.time <
1961 timestamp('2020-10-01T00:00:00.000Z')",
1962 }
1963 }
1964 ],
1965 "etag": "BwWWja0YfJA=",
1966 "version": 3
1967 }
1969 **YAML example:**
1971 ::
1973 bindings:
1974 - members:
1975 - user:mike@example.com
1976 - group:admins@example.com
1977 - domain:google.com
1978 - serviceAccount:my-project-id@appspot.gserviceaccount.com
1979 role: roles/resourcemanager.organizationAdmin
1980 - members:
1981 - user:eve@example.com
1982 role: roles/resourcemanager.organizationViewer
1983 condition:
1984 title: expirable access
1985 description: Does not grant access after Sep 2020
1986 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
1987 etag: BwWWja0YfJA=
1988 version: 3
1990 For a description of IAM and its features, see the `IAM
1991 documentation <https://cloud.google.com/iam/docs/>`__.
1993 """
1995 http_options: List[Dict[str, str]] = [
1996 {
1997 "method": "post",
1998 "uri": "/v2/{resource=projects/*/locations/*/queues/*}:setIamPolicy",
1999 "body": "*",
2000 },
2001 ]
2002 request, metadata = self._interceptor.pre_set_iam_policy(request, metadata)
2003 pb_request = request
2004 transcoded_request = path_template.transcode(http_options, pb_request)
2006 # Jsonify the request body
2008 body = json_format.MessageToJson(
2009 transcoded_request["body"],
2010 including_default_value_fields=False,
2011 use_integers_for_enums=True,
2012 )
2013 uri = transcoded_request["uri"]
2014 method = transcoded_request["method"]
2016 # Jsonify the query params
2017 query_params = json.loads(
2018 json_format.MessageToJson(
2019 transcoded_request["query_params"],
2020 including_default_value_fields=False,
2021 use_integers_for_enums=True,
2022 )
2023 )
2024 query_params.update(self._get_unset_required_fields(query_params))
2026 query_params["$alt"] = "json;enum-encoding=int"
2028 # Send the request
2029 headers = dict(metadata)
2030 headers["Content-Type"] = "application/json"
2031 response = getattr(self._session, method)(
2032 "{host}{uri}".format(host=self._host, uri=uri),
2033 timeout=timeout,
2034 headers=headers,
2035 params=rest_helpers.flatten_query_params(query_params, strict=True),
2036 data=body,
2037 )
2039 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
2040 # subclass.
2041 if response.status_code >= 400:
2042 raise core_exceptions.from_http_response(response)
2044 # Return the response
2045 resp = policy_pb2.Policy()
2046 pb_resp = resp
2048 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
2049 resp = self._interceptor.post_set_iam_policy(resp)
2050 return resp
2052 class _TestIamPermissions(CloudTasksRestStub):
2053 def __hash__(self):
2054 return hash("TestIamPermissions")
2056 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
2058 @classmethod
2059 def _get_unset_required_fields(cls, message_dict):
2060 return {
2061 k: v
2062 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
2063 if k not in message_dict
2064 }
2066 def __call__(
2067 self,
2068 request: iam_policy_pb2.TestIamPermissionsRequest,
2069 *,
2070 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2071 timeout: Optional[float] = None,
2072 metadata: Sequence[Tuple[str, str]] = (),
2073 ) -> iam_policy_pb2.TestIamPermissionsResponse:
2074 r"""Call the test iam permissions method over HTTP.
2076 Args:
2077 request (~.iam_policy_pb2.TestIamPermissionsRequest):
2078 The request object. Request message for ``TestIamPermissions`` method.
2079 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2080 should be retried.
2081 timeout (float): The timeout for this request.
2082 metadata (Sequence[Tuple[str, str]]): Strings which should be
2083 sent along with the request as metadata.
2085 Returns:
2086 ~.iam_policy_pb2.TestIamPermissionsResponse:
2087 Response message for ``TestIamPermissions`` method.
2088 """
2090 http_options: List[Dict[str, str]] = [
2091 {
2092 "method": "post",
2093 "uri": "/v2/{resource=projects/*/locations/*/queues/*}:testIamPermissions",
2094 "body": "*",
2095 },
2096 ]
2097 request, metadata = self._interceptor.pre_test_iam_permissions(
2098 request, metadata
2099 )
2100 pb_request = request
2101 transcoded_request = path_template.transcode(http_options, pb_request)
2103 # Jsonify the request body
2105 body = json_format.MessageToJson(
2106 transcoded_request["body"],
2107 including_default_value_fields=False,
2108 use_integers_for_enums=True,
2109 )
2110 uri = transcoded_request["uri"]
2111 method = transcoded_request["method"]
2113 # Jsonify the query params
2114 query_params = json.loads(
2115 json_format.MessageToJson(
2116 transcoded_request["query_params"],
2117 including_default_value_fields=False,
2118 use_integers_for_enums=True,
2119 )
2120 )
2121 query_params.update(self._get_unset_required_fields(query_params))
2123 query_params["$alt"] = "json;enum-encoding=int"
2125 # Send the request
2126 headers = dict(metadata)
2127 headers["Content-Type"] = "application/json"
2128 response = getattr(self._session, method)(
2129 "{host}{uri}".format(host=self._host, uri=uri),
2130 timeout=timeout,
2131 headers=headers,
2132 params=rest_helpers.flatten_query_params(query_params, strict=True),
2133 data=body,
2134 )
2136 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
2137 # subclass.
2138 if response.status_code >= 400:
2139 raise core_exceptions.from_http_response(response)
2141 # Return the response
2142 resp = iam_policy_pb2.TestIamPermissionsResponse()
2143 pb_resp = resp
2145 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
2146 resp = self._interceptor.post_test_iam_permissions(resp)
2147 return resp
2149 class _UpdateQueue(CloudTasksRestStub):
2150 def __hash__(self):
2151 return hash("UpdateQueue")
2153 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
2155 @classmethod
2156 def _get_unset_required_fields(cls, message_dict):
2157 return {
2158 k: v
2159 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
2160 if k not in message_dict
2161 }
2163 def __call__(
2164 self,
2165 request: cloudtasks.UpdateQueueRequest,
2166 *,
2167 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2168 timeout: Optional[float] = None,
2169 metadata: Sequence[Tuple[str, str]] = (),
2170 ) -> gct_queue.Queue:
2171 r"""Call the update queue method over HTTP.
2173 Args:
2174 request (~.cloudtasks.UpdateQueueRequest):
2175 The request object. Request message for
2176 [UpdateQueue][google.cloud.tasks.v2.CloudTasks.UpdateQueue].
2177 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2178 should be retried.
2179 timeout (float): The timeout for this request.
2180 metadata (Sequence[Tuple[str, str]]): Strings which should be
2181 sent along with the request as metadata.
2183 Returns:
2184 ~.gct_queue.Queue:
2185 A queue is a container of related
2186 tasks. Queues are configured to manage
2187 how those tasks are dispatched.
2188 Configurable properties include rate
2189 limits, retry options, queue types, and
2190 others.
2192 """
2194 http_options: List[Dict[str, str]] = [
2195 {
2196 "method": "patch",
2197 "uri": "/v2/{queue.name=projects/*/locations/*/queues/*}",
2198 "body": "queue",
2199 },
2200 ]
2201 request, metadata = self._interceptor.pre_update_queue(request, metadata)
2202 pb_request = cloudtasks.UpdateQueueRequest.pb(request)
2203 transcoded_request = path_template.transcode(http_options, pb_request)
2205 # Jsonify the request body
2207 body = json_format.MessageToJson(
2208 transcoded_request["body"],
2209 including_default_value_fields=False,
2210 use_integers_for_enums=True,
2211 )
2212 uri = transcoded_request["uri"]
2213 method = transcoded_request["method"]
2215 # Jsonify the query params
2216 query_params = json.loads(
2217 json_format.MessageToJson(
2218 transcoded_request["query_params"],
2219 including_default_value_fields=False,
2220 use_integers_for_enums=True,
2221 )
2222 )
2223 query_params.update(self._get_unset_required_fields(query_params))
2225 query_params["$alt"] = "json;enum-encoding=int"
2227 # Send the request
2228 headers = dict(metadata)
2229 headers["Content-Type"] = "application/json"
2230 response = getattr(self._session, method)(
2231 "{host}{uri}".format(host=self._host, uri=uri),
2232 timeout=timeout,
2233 headers=headers,
2234 params=rest_helpers.flatten_query_params(query_params, strict=True),
2235 data=body,
2236 )
2238 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
2239 # subclass.
2240 if response.status_code >= 400:
2241 raise core_exceptions.from_http_response(response)
2243 # Return the response
2244 resp = gct_queue.Queue()
2245 pb_resp = gct_queue.Queue.pb(resp)
2247 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
2248 resp = self._interceptor.post_update_queue(resp)
2249 return resp
2251 @property
2252 def create_queue(
2253 self,
2254 ) -> Callable[[cloudtasks.CreateQueueRequest], gct_queue.Queue]:
2255 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2256 # In C++ this would require a dynamic_cast
2257 return self._CreateQueue(self._session, self._host, self._interceptor) # type: ignore
2259 @property
2260 def create_task(self) -> Callable[[cloudtasks.CreateTaskRequest], gct_task.Task]:
2261 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2262 # In C++ this would require a dynamic_cast
2263 return self._CreateTask(self._session, self._host, self._interceptor) # type: ignore
2265 @property
2266 def delete_queue(
2267 self,
2268 ) -> Callable[[cloudtasks.DeleteQueueRequest], empty_pb2.Empty]:
2269 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2270 # In C++ this would require a dynamic_cast
2271 return self._DeleteQueue(self._session, self._host, self._interceptor) # type: ignore
2273 @property
2274 def delete_task(self) -> Callable[[cloudtasks.DeleteTaskRequest], empty_pb2.Empty]:
2275 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2276 # In C++ this would require a dynamic_cast
2277 return self._DeleteTask(self._session, self._host, self._interceptor) # type: ignore
2279 @property
2280 def get_iam_policy(
2281 self,
2282 ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
2283 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2284 # In C++ this would require a dynamic_cast
2285 return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
2287 @property
2288 def get_queue(self) -> Callable[[cloudtasks.GetQueueRequest], queue.Queue]:
2289 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2290 # In C++ this would require a dynamic_cast
2291 return self._GetQueue(self._session, self._host, self._interceptor) # type: ignore
2293 @property
2294 def get_task(self) -> Callable[[cloudtasks.GetTaskRequest], task.Task]:
2295 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2296 # In C++ this would require a dynamic_cast
2297 return self._GetTask(self._session, self._host, self._interceptor) # type: ignore
2299 @property
2300 def list_queues(
2301 self,
2302 ) -> Callable[[cloudtasks.ListQueuesRequest], cloudtasks.ListQueuesResponse]:
2303 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2304 # In C++ this would require a dynamic_cast
2305 return self._ListQueues(self._session, self._host, self._interceptor) # type: ignore
2307 @property
2308 def list_tasks(
2309 self,
2310 ) -> Callable[[cloudtasks.ListTasksRequest], cloudtasks.ListTasksResponse]:
2311 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2312 # In C++ this would require a dynamic_cast
2313 return self._ListTasks(self._session, self._host, self._interceptor) # type: ignore
2315 @property
2316 def pause_queue(self) -> Callable[[cloudtasks.PauseQueueRequest], queue.Queue]:
2317 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2318 # In C++ this would require a dynamic_cast
2319 return self._PauseQueue(self._session, self._host, self._interceptor) # type: ignore
2321 @property
2322 def purge_queue(self) -> Callable[[cloudtasks.PurgeQueueRequest], queue.Queue]:
2323 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2324 # In C++ this would require a dynamic_cast
2325 return self._PurgeQueue(self._session, self._host, self._interceptor) # type: ignore
2327 @property
2328 def resume_queue(self) -> Callable[[cloudtasks.ResumeQueueRequest], queue.Queue]:
2329 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2330 # In C++ this would require a dynamic_cast
2331 return self._ResumeQueue(self._session, self._host, self._interceptor) # type: ignore
2333 @property
2334 def run_task(self) -> Callable[[cloudtasks.RunTaskRequest], task.Task]:
2335 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2336 # In C++ this would require a dynamic_cast
2337 return self._RunTask(self._session, self._host, self._interceptor) # type: ignore
2339 @property
2340 def set_iam_policy(
2341 self,
2342 ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
2343 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2344 # In C++ this would require a dynamic_cast
2345 return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
2347 @property
2348 def test_iam_permissions(
2349 self,
2350 ) -> Callable[
2351 [iam_policy_pb2.TestIamPermissionsRequest],
2352 iam_policy_pb2.TestIamPermissionsResponse,
2353 ]:
2354 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2355 # In C++ this would require a dynamic_cast
2356 return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore
2358 @property
2359 def update_queue(
2360 self,
2361 ) -> Callable[[cloudtasks.UpdateQueueRequest], gct_queue.Queue]:
2362 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
2363 # In C++ this would require a dynamic_cast
2364 return self._UpdateQueue(self._session, self._host, self._interceptor) # type: ignore
2366 @property
2367 def kind(self) -> str:
2368 return "rest"
2370 def close(self):
2371 self._session.close()
2374__all__ = ("CloudTasksRestTransport",)