1# -*- coding: utf-8 -*-
2# Copyright 2025 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#
16from collections import OrderedDict
17import logging as std_logging
18import re
19from typing import (
20 Callable,
21 Dict,
22 Mapping,
23 MutableMapping,
24 MutableSequence,
25 Optional,
26 Sequence,
27 Tuple,
28 Type,
29 Union,
30)
31
32from google.api_core import exceptions as core_exceptions
33from google.api_core import gapic_v1
34from google.api_core import retry_async as retries
35from google.api_core.client_options import ClientOptions
36from google.auth import credentials as ga_credentials # type: ignore
37from google.oauth2 import service_account # type: ignore
38import google.protobuf
39
40from google.cloud.tasks_v2 import gapic_version as package_version
41
42try:
43 OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None]
44except AttributeError: # pragma: NO COVER
45 OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore
46
47from google.cloud.location import locations_pb2 # type: ignore
48from google.iam.v1 import iam_policy_pb2 # type: ignore
49from google.iam.v1 import policy_pb2 # type: ignore
50from google.protobuf import duration_pb2 # type: ignore
51from google.protobuf import field_mask_pb2 # type: ignore
52from google.protobuf import timestamp_pb2 # type: ignore
53
54from google.cloud.tasks_v2.services.cloud_tasks import pagers
55from google.cloud.tasks_v2.types import cloudtasks
56from google.cloud.tasks_v2.types import queue
57from google.cloud.tasks_v2.types import queue as gct_queue
58from google.cloud.tasks_v2.types import target
59from google.cloud.tasks_v2.types import task
60from google.cloud.tasks_v2.types import task as gct_task
61
62from .client import CloudTasksClient
63from .transports.base import DEFAULT_CLIENT_INFO, CloudTasksTransport
64from .transports.grpc_asyncio import CloudTasksGrpcAsyncIOTransport
65
66try:
67 from google.api_core import client_logging # type: ignore
68
69 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
70except ImportError: # pragma: NO COVER
71 CLIENT_LOGGING_SUPPORTED = False
72
73_LOGGER = std_logging.getLogger(__name__)
74
75
76class CloudTasksAsyncClient:
77 """Cloud Tasks allows developers to manage the execution of
78 background work in their applications.
79 """
80
81 _client: CloudTasksClient
82
83 # Copy defaults from the synchronous client for use here.
84 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
85 DEFAULT_ENDPOINT = CloudTasksClient.DEFAULT_ENDPOINT
86 DEFAULT_MTLS_ENDPOINT = CloudTasksClient.DEFAULT_MTLS_ENDPOINT
87 _DEFAULT_ENDPOINT_TEMPLATE = CloudTasksClient._DEFAULT_ENDPOINT_TEMPLATE
88 _DEFAULT_UNIVERSE = CloudTasksClient._DEFAULT_UNIVERSE
89
90 queue_path = staticmethod(CloudTasksClient.queue_path)
91 parse_queue_path = staticmethod(CloudTasksClient.parse_queue_path)
92 task_path = staticmethod(CloudTasksClient.task_path)
93 parse_task_path = staticmethod(CloudTasksClient.parse_task_path)
94 common_billing_account_path = staticmethod(
95 CloudTasksClient.common_billing_account_path
96 )
97 parse_common_billing_account_path = staticmethod(
98 CloudTasksClient.parse_common_billing_account_path
99 )
100 common_folder_path = staticmethod(CloudTasksClient.common_folder_path)
101 parse_common_folder_path = staticmethod(CloudTasksClient.parse_common_folder_path)
102 common_organization_path = staticmethod(CloudTasksClient.common_organization_path)
103 parse_common_organization_path = staticmethod(
104 CloudTasksClient.parse_common_organization_path
105 )
106 common_project_path = staticmethod(CloudTasksClient.common_project_path)
107 parse_common_project_path = staticmethod(CloudTasksClient.parse_common_project_path)
108 common_location_path = staticmethod(CloudTasksClient.common_location_path)
109 parse_common_location_path = staticmethod(
110 CloudTasksClient.parse_common_location_path
111 )
112
113 @classmethod
114 def from_service_account_info(cls, info: dict, *args, **kwargs):
115 """Creates an instance of this client using the provided credentials
116 info.
117
118 Args:
119 info (dict): The service account private key info.
120 args: Additional arguments to pass to the constructor.
121 kwargs: Additional arguments to pass to the constructor.
122
123 Returns:
124 CloudTasksAsyncClient: The constructed client.
125 """
126 return CloudTasksClient.from_service_account_info.__func__(CloudTasksAsyncClient, info, *args, **kwargs) # type: ignore
127
128 @classmethod
129 def from_service_account_file(cls, filename: str, *args, **kwargs):
130 """Creates an instance of this client using the provided credentials
131 file.
132
133 Args:
134 filename (str): The path to the service account private key json
135 file.
136 args: Additional arguments to pass to the constructor.
137 kwargs: Additional arguments to pass to the constructor.
138
139 Returns:
140 CloudTasksAsyncClient: The constructed client.
141 """
142 return CloudTasksClient.from_service_account_file.__func__(CloudTasksAsyncClient, filename, *args, **kwargs) # type: ignore
143
144 from_service_account_json = from_service_account_file
145
146 @classmethod
147 def get_mtls_endpoint_and_cert_source(
148 cls, client_options: Optional[ClientOptions] = None
149 ):
150 """Return the API endpoint and client cert source for mutual TLS.
151
152 The client cert source is determined in the following order:
153 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
154 client cert source is None.
155 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
156 default client cert source exists, use the default one; otherwise the client cert
157 source is None.
158
159 The API endpoint is determined in the following order:
160 (1) if `client_options.api_endpoint` if provided, use the provided one.
161 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
162 default mTLS endpoint; if the environment variable is "never", use the default API
163 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
164 use the default API endpoint.
165
166 More details can be found at https://google.aip.dev/auth/4114.
167
168 Args:
169 client_options (google.api_core.client_options.ClientOptions): Custom options for the
170 client. Only the `api_endpoint` and `client_cert_source` properties may be used
171 in this method.
172
173 Returns:
174 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
175 client cert source to use.
176
177 Raises:
178 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
179 """
180 return CloudTasksClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
181
182 @property
183 def transport(self) -> CloudTasksTransport:
184 """Returns the transport used by the client instance.
185
186 Returns:
187 CloudTasksTransport: The transport used by the client instance.
188 """
189 return self._client.transport
190
191 @property
192 def api_endpoint(self):
193 """Return the API endpoint used by the client instance.
194
195 Returns:
196 str: The API endpoint used by the client instance.
197 """
198 return self._client._api_endpoint
199
200 @property
201 def universe_domain(self) -> str:
202 """Return the universe domain used by the client instance.
203
204 Returns:
205 str: The universe domain used
206 by the client instance.
207 """
208 return self._client._universe_domain
209
210 get_transport_class = CloudTasksClient.get_transport_class
211
212 def __init__(
213 self,
214 *,
215 credentials: Optional[ga_credentials.Credentials] = None,
216 transport: Optional[
217 Union[str, CloudTasksTransport, Callable[..., CloudTasksTransport]]
218 ] = "grpc_asyncio",
219 client_options: Optional[ClientOptions] = None,
220 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
221 ) -> None:
222 """Instantiates the cloud tasks async client.
223
224 Args:
225 credentials (Optional[google.auth.credentials.Credentials]): The
226 authorization credentials to attach to requests. These
227 credentials identify the application to the service; if none
228 are specified, the client will attempt to ascertain the
229 credentials from the environment.
230 transport (Optional[Union[str,CloudTasksTransport,Callable[..., CloudTasksTransport]]]):
231 The transport to use, or a Callable that constructs and returns a new transport to use.
232 If a Callable is given, it will be called with the same set of initialization
233 arguments as used in the CloudTasksTransport constructor.
234 If set to None, a transport is chosen automatically.
235 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
236 Custom options for the client.
237
238 1. The ``api_endpoint`` property can be used to override the
239 default endpoint provided by the client when ``transport`` is
240 not explicitly provided. Only if this property is not set and
241 ``transport`` was not explicitly provided, the endpoint is
242 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
243 variable, which have one of the following values:
244 "always" (always use the default mTLS endpoint), "never" (always
245 use the default regular endpoint) and "auto" (auto-switch to the
246 default mTLS endpoint if client certificate is present; this is
247 the default value).
248
249 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
250 is "true", then the ``client_cert_source`` property can be used
251 to provide a client certificate for mTLS transport. If
252 not provided, the default SSL client certificate will be used if
253 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
254 set, no client certificate will be used.
255
256 3. The ``universe_domain`` property can be used to override the
257 default "googleapis.com" universe. Note that ``api_endpoint``
258 property still takes precedence; and ``universe_domain`` is
259 currently not supported for mTLS.
260
261 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
262 The client info used to send a user-agent string along with
263 API requests. If ``None``, then default info will be used.
264 Generally, you only need to set this if you're developing
265 your own client library.
266
267 Raises:
268 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
269 creation failed for any reason.
270 """
271 self._client = CloudTasksClient(
272 credentials=credentials,
273 transport=transport,
274 client_options=client_options,
275 client_info=client_info,
276 )
277
278 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
279 std_logging.DEBUG
280 ): # pragma: NO COVER
281 _LOGGER.debug(
282 "Created client `google.cloud.tasks_v2.CloudTasksAsyncClient`.",
283 extra={
284 "serviceName": "google.cloud.tasks.v2.CloudTasks",
285 "universeDomain": getattr(
286 self._client._transport._credentials, "universe_domain", ""
287 ),
288 "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
289 "credentialsInfo": getattr(
290 self.transport._credentials, "get_cred_info", lambda: None
291 )(),
292 }
293 if hasattr(self._client._transport, "_credentials")
294 else {
295 "serviceName": "google.cloud.tasks.v2.CloudTasks",
296 "credentialsType": None,
297 },
298 )
299
300 async def list_queues(
301 self,
302 request: Optional[Union[cloudtasks.ListQueuesRequest, dict]] = None,
303 *,
304 parent: Optional[str] = None,
305 retry: OptionalRetry = gapic_v1.method.DEFAULT,
306 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
307 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
308 ) -> pagers.ListQueuesAsyncPager:
309 r"""Lists queues.
310
311 Queues are returned in lexicographical order.
312
313 .. code-block:: python
314
315 # This snippet has been automatically generated and should be regarded as a
316 # code template only.
317 # It will require modifications to work:
318 # - It may require correct/in-range values for request initialization.
319 # - It may require specifying regional endpoints when creating the service
320 # client as shown in:
321 # https://googleapis.dev/python/google-api-core/latest/client_options.html
322 from google.cloud import tasks_v2
323
324 async def sample_list_queues():
325 # Create a client
326 client = tasks_v2.CloudTasksAsyncClient()
327
328 # Initialize request argument(s)
329 request = tasks_v2.ListQueuesRequest(
330 parent="parent_value",
331 )
332
333 # Make the request
334 page_result = client.list_queues(request=request)
335
336 # Handle the response
337 async for response in page_result:
338 print(response)
339
340 Args:
341 request (Optional[Union[google.cloud.tasks_v2.types.ListQueuesRequest, dict]]):
342 The request object. Request message for
343 [ListQueues][google.cloud.tasks.v2.CloudTasks.ListQueues].
344 parent (:class:`str`):
345 Required. The location name. For example:
346 ``projects/PROJECT_ID/locations/LOCATION_ID``
347
348 This corresponds to the ``parent`` field
349 on the ``request`` instance; if ``request`` is provided, this
350 should not be set.
351 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
352 should be retried.
353 timeout (float): The timeout for this request.
354 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
355 sent along with the request as metadata. Normally, each value must be of type `str`,
356 but for metadata keys ending with the suffix `-bin`, the corresponding values must
357 be of type `bytes`.
358
359 Returns:
360 google.cloud.tasks_v2.services.cloud_tasks.pagers.ListQueuesAsyncPager:
361 Response message for
362 [ListQueues][google.cloud.tasks.v2.CloudTasks.ListQueues].
363
364 Iterating over this object will yield results and
365 resolve additional pages automatically.
366
367 """
368 # Create or coerce a protobuf request object.
369 # - Quick check: If we got a request object, we should *not* have
370 # gotten any keyword arguments that map to the request.
371 flattened_params = [parent]
372 has_flattened_params = (
373 len([param for param in flattened_params if param is not None]) > 0
374 )
375 if request is not None and has_flattened_params:
376 raise ValueError(
377 "If the `request` argument is set, then none of "
378 "the individual field arguments should be set."
379 )
380
381 # - Use the request object if provided (there's no risk of modifying the input as
382 # there are no flattened fields), or create one.
383 if not isinstance(request, cloudtasks.ListQueuesRequest):
384 request = cloudtasks.ListQueuesRequest(request)
385
386 # If we have keyword arguments corresponding to fields on the
387 # request, apply these.
388 if parent is not None:
389 request.parent = parent
390
391 # Wrap the RPC method; this adds retry and timeout information,
392 # and friendly error handling.
393 rpc = self._client._transport._wrapped_methods[
394 self._client._transport.list_queues
395 ]
396
397 # Certain fields should be provided within the metadata header;
398 # add these here.
399 metadata = tuple(metadata) + (
400 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
401 )
402
403 # Validate the universe domain.
404 self._client._validate_universe_domain()
405
406 # Send the request.
407 response = await rpc(
408 request,
409 retry=retry,
410 timeout=timeout,
411 metadata=metadata,
412 )
413
414 # This method is paged; wrap the response in a pager, which provides
415 # an `__aiter__` convenience method.
416 response = pagers.ListQueuesAsyncPager(
417 method=rpc,
418 request=request,
419 response=response,
420 retry=retry,
421 timeout=timeout,
422 metadata=metadata,
423 )
424
425 # Done; return the response.
426 return response
427
428 async def get_queue(
429 self,
430 request: Optional[Union[cloudtasks.GetQueueRequest, dict]] = None,
431 *,
432 name: Optional[str] = None,
433 retry: OptionalRetry = gapic_v1.method.DEFAULT,
434 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
435 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
436 ) -> queue.Queue:
437 r"""Gets a queue.
438
439 .. code-block:: python
440
441 # This snippet has been automatically generated and should be regarded as a
442 # code template only.
443 # It will require modifications to work:
444 # - It may require correct/in-range values for request initialization.
445 # - It may require specifying regional endpoints when creating the service
446 # client as shown in:
447 # https://googleapis.dev/python/google-api-core/latest/client_options.html
448 from google.cloud import tasks_v2
449
450 async def sample_get_queue():
451 # Create a client
452 client = tasks_v2.CloudTasksAsyncClient()
453
454 # Initialize request argument(s)
455 request = tasks_v2.GetQueueRequest(
456 name="name_value",
457 )
458
459 # Make the request
460 response = await client.get_queue(request=request)
461
462 # Handle the response
463 print(response)
464
465 Args:
466 request (Optional[Union[google.cloud.tasks_v2.types.GetQueueRequest, dict]]):
467 The request object. Request message for
468 [GetQueue][google.cloud.tasks.v2.CloudTasks.GetQueue].
469 name (:class:`str`):
470 Required. The resource name of the queue. For example:
471 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID``
472
473 This corresponds to the ``name`` field
474 on the ``request`` instance; if ``request`` is provided, this
475 should not be set.
476 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
477 should be retried.
478 timeout (float): The timeout for this request.
479 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
480 sent along with the request as metadata. Normally, each value must be of type `str`,
481 but for metadata keys ending with the suffix `-bin`, the corresponding values must
482 be of type `bytes`.
483
484 Returns:
485 google.cloud.tasks_v2.types.Queue:
486 A queue is a container of related
487 tasks. Queues are configured to manage
488 how those tasks are dispatched.
489 Configurable properties include rate
490 limits, retry options, queue types, and
491 others.
492
493 """
494 # Create or coerce a protobuf request object.
495 # - Quick check: If we got a request object, we should *not* have
496 # gotten any keyword arguments that map to the request.
497 flattened_params = [name]
498 has_flattened_params = (
499 len([param for param in flattened_params if param is not None]) > 0
500 )
501 if request is not None and has_flattened_params:
502 raise ValueError(
503 "If the `request` argument is set, then none of "
504 "the individual field arguments should be set."
505 )
506
507 # - Use the request object if provided (there's no risk of modifying the input as
508 # there are no flattened fields), or create one.
509 if not isinstance(request, cloudtasks.GetQueueRequest):
510 request = cloudtasks.GetQueueRequest(request)
511
512 # If we have keyword arguments corresponding to fields on the
513 # request, apply these.
514 if name is not None:
515 request.name = name
516
517 # Wrap the RPC method; this adds retry and timeout information,
518 # and friendly error handling.
519 rpc = self._client._transport._wrapped_methods[
520 self._client._transport.get_queue
521 ]
522
523 # Certain fields should be provided within the metadata header;
524 # add these here.
525 metadata = tuple(metadata) + (
526 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
527 )
528
529 # Validate the universe domain.
530 self._client._validate_universe_domain()
531
532 # Send the request.
533 response = await rpc(
534 request,
535 retry=retry,
536 timeout=timeout,
537 metadata=metadata,
538 )
539
540 # Done; return the response.
541 return response
542
543 async def create_queue(
544 self,
545 request: Optional[Union[cloudtasks.CreateQueueRequest, dict]] = None,
546 *,
547 parent: Optional[str] = None,
548 queue: Optional[gct_queue.Queue] = None,
549 retry: OptionalRetry = gapic_v1.method.DEFAULT,
550 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
551 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
552 ) -> gct_queue.Queue:
553 r"""Creates a queue.
554
555 Queues created with this method allow tasks to live for a
556 maximum of 31 days. After a task is 31 days old, the task will
557 be deleted regardless of whether it was dispatched or not.
558
559 WARNING: Using this method may have unintended side effects if
560 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file
561 to manage your queues. Read `Overview of Queue Management and
562 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__
563 before using this method.
564
565 .. code-block:: python
566
567 # This snippet has been automatically generated and should be regarded as a
568 # code template only.
569 # It will require modifications to work:
570 # - It may require correct/in-range values for request initialization.
571 # - It may require specifying regional endpoints when creating the service
572 # client as shown in:
573 # https://googleapis.dev/python/google-api-core/latest/client_options.html
574 from google.cloud import tasks_v2
575
576 async def sample_create_queue():
577 # Create a client
578 client = tasks_v2.CloudTasksAsyncClient()
579
580 # Initialize request argument(s)
581 request = tasks_v2.CreateQueueRequest(
582 parent="parent_value",
583 )
584
585 # Make the request
586 response = await client.create_queue(request=request)
587
588 # Handle the response
589 print(response)
590
591 Args:
592 request (Optional[Union[google.cloud.tasks_v2.types.CreateQueueRequest, dict]]):
593 The request object. Request message for
594 [CreateQueue][google.cloud.tasks.v2.CloudTasks.CreateQueue].
595 parent (:class:`str`):
596 Required. The location name in which the queue will be
597 created. For example:
598 ``projects/PROJECT_ID/locations/LOCATION_ID``
599
600 The list of allowed locations can be obtained by calling
601 Cloud Tasks' implementation of
602 [ListLocations][google.cloud.location.Locations.ListLocations].
603
604 This corresponds to the ``parent`` field
605 on the ``request`` instance; if ``request`` is provided, this
606 should not be set.
607 queue (:class:`google.cloud.tasks_v2.types.Queue`):
608 Required. The queue to create.
609
610 [Queue's name][google.cloud.tasks.v2.Queue.name] cannot
611 be the same as an existing queue.
612
613 This corresponds to the ``queue`` field
614 on the ``request`` instance; if ``request`` is provided, this
615 should not be set.
616 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
617 should be retried.
618 timeout (float): The timeout for this request.
619 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
620 sent along with the request as metadata. Normally, each value must be of type `str`,
621 but for metadata keys ending with the suffix `-bin`, the corresponding values must
622 be of type `bytes`.
623
624 Returns:
625 google.cloud.tasks_v2.types.Queue:
626 A queue is a container of related
627 tasks. Queues are configured to manage
628 how those tasks are dispatched.
629 Configurable properties include rate
630 limits, retry options, queue types, and
631 others.
632
633 """
634 # Create or coerce a protobuf request object.
635 # - Quick check: If we got a request object, we should *not* have
636 # gotten any keyword arguments that map to the request.
637 flattened_params = [parent, queue]
638 has_flattened_params = (
639 len([param for param in flattened_params if param is not None]) > 0
640 )
641 if request is not None and has_flattened_params:
642 raise ValueError(
643 "If the `request` argument is set, then none of "
644 "the individual field arguments should be set."
645 )
646
647 # - Use the request object if provided (there's no risk of modifying the input as
648 # there are no flattened fields), or create one.
649 if not isinstance(request, cloudtasks.CreateQueueRequest):
650 request = cloudtasks.CreateQueueRequest(request)
651
652 # If we have keyword arguments corresponding to fields on the
653 # request, apply these.
654 if parent is not None:
655 request.parent = parent
656 if queue is not None:
657 request.queue = queue
658
659 # Wrap the RPC method; this adds retry and timeout information,
660 # and friendly error handling.
661 rpc = self._client._transport._wrapped_methods[
662 self._client._transport.create_queue
663 ]
664
665 # Certain fields should be provided within the metadata header;
666 # add these here.
667 metadata = tuple(metadata) + (
668 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
669 )
670
671 # Validate the universe domain.
672 self._client._validate_universe_domain()
673
674 # Send the request.
675 response = await rpc(
676 request,
677 retry=retry,
678 timeout=timeout,
679 metadata=metadata,
680 )
681
682 # Done; return the response.
683 return response
684
685 async def update_queue(
686 self,
687 request: Optional[Union[cloudtasks.UpdateQueueRequest, dict]] = None,
688 *,
689 queue: Optional[gct_queue.Queue] = None,
690 update_mask: Optional[field_mask_pb2.FieldMask] = None,
691 retry: OptionalRetry = gapic_v1.method.DEFAULT,
692 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
693 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
694 ) -> gct_queue.Queue:
695 r"""Updates a queue.
696
697 This method creates the queue if it does not exist and updates
698 the queue if it does exist.
699
700 Queues created with this method allow tasks to live for a
701 maximum of 31 days. After a task is 31 days old, the task will
702 be deleted regardless of whether it was dispatched or not.
703
704 WARNING: Using this method may have unintended side effects if
705 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file
706 to manage your queues. Read `Overview of Queue Management and
707 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__
708 before using this method.
709
710 .. code-block:: python
711
712 # This snippet has been automatically generated and should be regarded as a
713 # code template only.
714 # It will require modifications to work:
715 # - It may require correct/in-range values for request initialization.
716 # - It may require specifying regional endpoints when creating the service
717 # client as shown in:
718 # https://googleapis.dev/python/google-api-core/latest/client_options.html
719 from google.cloud import tasks_v2
720
721 async def sample_update_queue():
722 # Create a client
723 client = tasks_v2.CloudTasksAsyncClient()
724
725 # Initialize request argument(s)
726 request = tasks_v2.UpdateQueueRequest(
727 )
728
729 # Make the request
730 response = await client.update_queue(request=request)
731
732 # Handle the response
733 print(response)
734
735 Args:
736 request (Optional[Union[google.cloud.tasks_v2.types.UpdateQueueRequest, dict]]):
737 The request object. Request message for
738 [UpdateQueue][google.cloud.tasks.v2.CloudTasks.UpdateQueue].
739 queue (:class:`google.cloud.tasks_v2.types.Queue`):
740 Required. The queue to create or update.
741
742 The queue's [name][google.cloud.tasks.v2.Queue.name]
743 must be specified.
744
745 Output only fields cannot be modified using UpdateQueue.
746 Any value specified for an output only field will be
747 ignored. The queue's
748 [name][google.cloud.tasks.v2.Queue.name] cannot be
749 changed.
750
751 This corresponds to the ``queue`` field
752 on the ``request`` instance; if ``request`` is provided, this
753 should not be set.
754 update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
755 A mask used to specify which fields
756 of the queue are being updated.
757 If empty, then all fields will be
758 updated.
759
760 This corresponds to the ``update_mask`` field
761 on the ``request`` instance; if ``request`` is provided, this
762 should not be set.
763 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
764 should be retried.
765 timeout (float): The timeout for this request.
766 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
767 sent along with the request as metadata. Normally, each value must be of type `str`,
768 but for metadata keys ending with the suffix `-bin`, the corresponding values must
769 be of type `bytes`.
770
771 Returns:
772 google.cloud.tasks_v2.types.Queue:
773 A queue is a container of related
774 tasks. Queues are configured to manage
775 how those tasks are dispatched.
776 Configurable properties include rate
777 limits, retry options, queue types, and
778 others.
779
780 """
781 # Create or coerce a protobuf request object.
782 # - Quick check: If we got a request object, we should *not* have
783 # gotten any keyword arguments that map to the request.
784 flattened_params = [queue, update_mask]
785 has_flattened_params = (
786 len([param for param in flattened_params if param is not None]) > 0
787 )
788 if request is not None and has_flattened_params:
789 raise ValueError(
790 "If the `request` argument is set, then none of "
791 "the individual field arguments should be set."
792 )
793
794 # - Use the request object if provided (there's no risk of modifying the input as
795 # there are no flattened fields), or create one.
796 if not isinstance(request, cloudtasks.UpdateQueueRequest):
797 request = cloudtasks.UpdateQueueRequest(request)
798
799 # If we have keyword arguments corresponding to fields on the
800 # request, apply these.
801 if queue is not None:
802 request.queue = queue
803 if update_mask is not None:
804 request.update_mask = update_mask
805
806 # Wrap the RPC method; this adds retry and timeout information,
807 # and friendly error handling.
808 rpc = self._client._transport._wrapped_methods[
809 self._client._transport.update_queue
810 ]
811
812 # Certain fields should be provided within the metadata header;
813 # add these here.
814 metadata = tuple(metadata) + (
815 gapic_v1.routing_header.to_grpc_metadata(
816 (("queue.name", request.queue.name),)
817 ),
818 )
819
820 # Validate the universe domain.
821 self._client._validate_universe_domain()
822
823 # Send the request.
824 response = await rpc(
825 request,
826 retry=retry,
827 timeout=timeout,
828 metadata=metadata,
829 )
830
831 # Done; return the response.
832 return response
833
834 async def delete_queue(
835 self,
836 request: Optional[Union[cloudtasks.DeleteQueueRequest, dict]] = None,
837 *,
838 name: Optional[str] = None,
839 retry: OptionalRetry = gapic_v1.method.DEFAULT,
840 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
841 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
842 ) -> None:
843 r"""Deletes a queue.
844
845 This command will delete the queue even if it has tasks in it.
846
847 Note: If you delete a queue, a queue with the same name can't be
848 created for 7 days.
849
850 WARNING: Using this method may have unintended side effects if
851 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file
852 to manage your queues. Read `Overview of Queue Management and
853 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__
854 before using this method.
855
856 .. code-block:: python
857
858 # This snippet has been automatically generated and should be regarded as a
859 # code template only.
860 # It will require modifications to work:
861 # - It may require correct/in-range values for request initialization.
862 # - It may require specifying regional endpoints when creating the service
863 # client as shown in:
864 # https://googleapis.dev/python/google-api-core/latest/client_options.html
865 from google.cloud import tasks_v2
866
867 async def sample_delete_queue():
868 # Create a client
869 client = tasks_v2.CloudTasksAsyncClient()
870
871 # Initialize request argument(s)
872 request = tasks_v2.DeleteQueueRequest(
873 name="name_value",
874 )
875
876 # Make the request
877 await client.delete_queue(request=request)
878
879 Args:
880 request (Optional[Union[google.cloud.tasks_v2.types.DeleteQueueRequest, dict]]):
881 The request object. Request message for
882 [DeleteQueue][google.cloud.tasks.v2.CloudTasks.DeleteQueue].
883 name (:class:`str`):
884 Required. The queue name. For example:
885 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID``
886
887 This corresponds to the ``name`` field
888 on the ``request`` instance; if ``request`` is provided, this
889 should not be set.
890 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
891 should be retried.
892 timeout (float): The timeout for this request.
893 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
894 sent along with the request as metadata. Normally, each value must be of type `str`,
895 but for metadata keys ending with the suffix `-bin`, the corresponding values must
896 be of type `bytes`.
897 """
898 # Create or coerce a protobuf request object.
899 # - Quick check: If we got a request object, we should *not* have
900 # gotten any keyword arguments that map to the request.
901 flattened_params = [name]
902 has_flattened_params = (
903 len([param for param in flattened_params if param is not None]) > 0
904 )
905 if request is not None and has_flattened_params:
906 raise ValueError(
907 "If the `request` argument is set, then none of "
908 "the individual field arguments should be set."
909 )
910
911 # - Use the request object if provided (there's no risk of modifying the input as
912 # there are no flattened fields), or create one.
913 if not isinstance(request, cloudtasks.DeleteQueueRequest):
914 request = cloudtasks.DeleteQueueRequest(request)
915
916 # If we have keyword arguments corresponding to fields on the
917 # request, apply these.
918 if name is not None:
919 request.name = name
920
921 # Wrap the RPC method; this adds retry and timeout information,
922 # and friendly error handling.
923 rpc = self._client._transport._wrapped_methods[
924 self._client._transport.delete_queue
925 ]
926
927 # Certain fields should be provided within the metadata header;
928 # add these here.
929 metadata = tuple(metadata) + (
930 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
931 )
932
933 # Validate the universe domain.
934 self._client._validate_universe_domain()
935
936 # Send the request.
937 await rpc(
938 request,
939 retry=retry,
940 timeout=timeout,
941 metadata=metadata,
942 )
943
944 async def purge_queue(
945 self,
946 request: Optional[Union[cloudtasks.PurgeQueueRequest, dict]] = None,
947 *,
948 name: Optional[str] = None,
949 retry: OptionalRetry = gapic_v1.method.DEFAULT,
950 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
951 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
952 ) -> queue.Queue:
953 r"""Purges a queue by deleting all of its tasks.
954
955 All tasks created before this method is called are
956 permanently deleted.
957
958 Purge operations can take up to one minute to take
959 effect. Tasks might be dispatched before the purge takes
960 effect. A purge is irreversible.
961
962 .. code-block:: python
963
964 # This snippet has been automatically generated and should be regarded as a
965 # code template only.
966 # It will require modifications to work:
967 # - It may require correct/in-range values for request initialization.
968 # - It may require specifying regional endpoints when creating the service
969 # client as shown in:
970 # https://googleapis.dev/python/google-api-core/latest/client_options.html
971 from google.cloud import tasks_v2
972
973 async def sample_purge_queue():
974 # Create a client
975 client = tasks_v2.CloudTasksAsyncClient()
976
977 # Initialize request argument(s)
978 request = tasks_v2.PurgeQueueRequest(
979 name="name_value",
980 )
981
982 # Make the request
983 response = await client.purge_queue(request=request)
984
985 # Handle the response
986 print(response)
987
988 Args:
989 request (Optional[Union[google.cloud.tasks_v2.types.PurgeQueueRequest, dict]]):
990 The request object. Request message for
991 [PurgeQueue][google.cloud.tasks.v2.CloudTasks.PurgeQueue].
992 name (:class:`str`):
993 Required. The queue name. For example:
994 ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID``
995
996 This corresponds to the ``name`` field
997 on the ``request`` instance; if ``request`` is provided, this
998 should not be set.
999 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1000 should be retried.
1001 timeout (float): The timeout for this request.
1002 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1003 sent along with the request as metadata. Normally, each value must be of type `str`,
1004 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1005 be of type `bytes`.
1006
1007 Returns:
1008 google.cloud.tasks_v2.types.Queue:
1009 A queue is a container of related
1010 tasks. Queues are configured to manage
1011 how those tasks are dispatched.
1012 Configurable properties include rate
1013 limits, retry options, queue types, and
1014 others.
1015
1016 """
1017 # Create or coerce a protobuf request object.
1018 # - Quick check: If we got a request object, we should *not* have
1019 # gotten any keyword arguments that map to the request.
1020 flattened_params = [name]
1021 has_flattened_params = (
1022 len([param for param in flattened_params if param is not None]) > 0
1023 )
1024 if request is not None and has_flattened_params:
1025 raise ValueError(
1026 "If the `request` argument is set, then none of "
1027 "the individual field arguments should be set."
1028 )
1029
1030 # - Use the request object if provided (there's no risk of modifying the input as
1031 # there are no flattened fields), or create one.
1032 if not isinstance(request, cloudtasks.PurgeQueueRequest):
1033 request = cloudtasks.PurgeQueueRequest(request)
1034
1035 # If we have keyword arguments corresponding to fields on the
1036 # request, apply these.
1037 if name is not None:
1038 request.name = name
1039
1040 # Wrap the RPC method; this adds retry and timeout information,
1041 # and friendly error handling.
1042 rpc = self._client._transport._wrapped_methods[
1043 self._client._transport.purge_queue
1044 ]
1045
1046 # Certain fields should be provided within the metadata header;
1047 # add these here.
1048 metadata = tuple(metadata) + (
1049 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1050 )
1051
1052 # Validate the universe domain.
1053 self._client._validate_universe_domain()
1054
1055 # Send the request.
1056 response = await rpc(
1057 request,
1058 retry=retry,
1059 timeout=timeout,
1060 metadata=metadata,
1061 )
1062
1063 # Done; return the response.
1064 return response
1065
1066 async def pause_queue(
1067 self,
1068 request: Optional[Union[cloudtasks.PauseQueueRequest, dict]] = None,
1069 *,
1070 name: Optional[str] = None,
1071 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1072 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1073 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1074 ) -> queue.Queue:
1075 r"""Pauses the queue.
1076
1077 If a queue is paused then the system will stop dispatching tasks
1078 until the queue is resumed via
1079 [ResumeQueue][google.cloud.tasks.v2.CloudTasks.ResumeQueue].
1080 Tasks can still be added when the queue is paused. A queue is
1081 paused if its [state][google.cloud.tasks.v2.Queue.state] is
1082 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED].
1083
1084 .. code-block:: python
1085
1086 # This snippet has been automatically generated and should be regarded as a
1087 # code template only.
1088 # It will require modifications to work:
1089 # - It may require correct/in-range values for request initialization.
1090 # - It may require specifying regional endpoints when creating the service
1091 # client as shown in:
1092 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1093 from google.cloud import tasks_v2
1094
1095 async def sample_pause_queue():
1096 # Create a client
1097 client = tasks_v2.CloudTasksAsyncClient()
1098
1099 # Initialize request argument(s)
1100 request = tasks_v2.PauseQueueRequest(
1101 name="name_value",
1102 )
1103
1104 # Make the request
1105 response = await client.pause_queue(request=request)
1106
1107 # Handle the response
1108 print(response)
1109
1110 Args:
1111 request (Optional[Union[google.cloud.tasks_v2.types.PauseQueueRequest, dict]]):
1112 The request object. Request message for
1113 [PauseQueue][google.cloud.tasks.v2.CloudTasks.PauseQueue].
1114 name (:class:`str`):
1115 Required. The queue name. For example:
1116 ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID``
1117
1118 This corresponds to the ``name`` field
1119 on the ``request`` instance; if ``request`` is provided, this
1120 should not be set.
1121 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1122 should be retried.
1123 timeout (float): The timeout for this request.
1124 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1125 sent along with the request as metadata. Normally, each value must be of type `str`,
1126 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1127 be of type `bytes`.
1128
1129 Returns:
1130 google.cloud.tasks_v2.types.Queue:
1131 A queue is a container of related
1132 tasks. Queues are configured to manage
1133 how those tasks are dispatched.
1134 Configurable properties include rate
1135 limits, retry options, queue types, and
1136 others.
1137
1138 """
1139 # Create or coerce a protobuf request object.
1140 # - Quick check: If we got a request object, we should *not* have
1141 # gotten any keyword arguments that map to the request.
1142 flattened_params = [name]
1143 has_flattened_params = (
1144 len([param for param in flattened_params if param is not None]) > 0
1145 )
1146 if request is not None and has_flattened_params:
1147 raise ValueError(
1148 "If the `request` argument is set, then none of "
1149 "the individual field arguments should be set."
1150 )
1151
1152 # - Use the request object if provided (there's no risk of modifying the input as
1153 # there are no flattened fields), or create one.
1154 if not isinstance(request, cloudtasks.PauseQueueRequest):
1155 request = cloudtasks.PauseQueueRequest(request)
1156
1157 # If we have keyword arguments corresponding to fields on the
1158 # request, apply these.
1159 if name is not None:
1160 request.name = name
1161
1162 # Wrap the RPC method; this adds retry and timeout information,
1163 # and friendly error handling.
1164 rpc = self._client._transport._wrapped_methods[
1165 self._client._transport.pause_queue
1166 ]
1167
1168 # Certain fields should be provided within the metadata header;
1169 # add these here.
1170 metadata = tuple(metadata) + (
1171 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1172 )
1173
1174 # Validate the universe domain.
1175 self._client._validate_universe_domain()
1176
1177 # Send the request.
1178 response = await rpc(
1179 request,
1180 retry=retry,
1181 timeout=timeout,
1182 metadata=metadata,
1183 )
1184
1185 # Done; return the response.
1186 return response
1187
1188 async def resume_queue(
1189 self,
1190 request: Optional[Union[cloudtasks.ResumeQueueRequest, dict]] = None,
1191 *,
1192 name: Optional[str] = None,
1193 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1194 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1195 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1196 ) -> queue.Queue:
1197 r"""Resume a queue.
1198
1199 This method resumes a queue after it has been
1200 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED] or
1201 [DISABLED][google.cloud.tasks.v2.Queue.State.DISABLED]. The
1202 state of a queue is stored in the queue's
1203 [state][google.cloud.tasks.v2.Queue.state]; after calling this
1204 method it will be set to
1205 [RUNNING][google.cloud.tasks.v2.Queue.State.RUNNING].
1206
1207 WARNING: Resuming many high-QPS queues at the same time can lead
1208 to target overloading. If you are resuming high-QPS queues,
1209 follow the 500/50/5 pattern described in `Managing Cloud Tasks
1210 Scaling
1211 Risks <https://cloud.google.com/tasks/docs/manage-cloud-task-scaling>`__.
1212
1213 .. code-block:: python
1214
1215 # This snippet has been automatically generated and should be regarded as a
1216 # code template only.
1217 # It will require modifications to work:
1218 # - It may require correct/in-range values for request initialization.
1219 # - It may require specifying regional endpoints when creating the service
1220 # client as shown in:
1221 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1222 from google.cloud import tasks_v2
1223
1224 async def sample_resume_queue():
1225 # Create a client
1226 client = tasks_v2.CloudTasksAsyncClient()
1227
1228 # Initialize request argument(s)
1229 request = tasks_v2.ResumeQueueRequest(
1230 name="name_value",
1231 )
1232
1233 # Make the request
1234 response = await client.resume_queue(request=request)
1235
1236 # Handle the response
1237 print(response)
1238
1239 Args:
1240 request (Optional[Union[google.cloud.tasks_v2.types.ResumeQueueRequest, dict]]):
1241 The request object. Request message for
1242 [ResumeQueue][google.cloud.tasks.v2.CloudTasks.ResumeQueue].
1243 name (:class:`str`):
1244 Required. The queue name. For example:
1245 ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID``
1246
1247 This corresponds to the ``name`` field
1248 on the ``request`` instance; if ``request`` is provided, this
1249 should not be set.
1250 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1251 should be retried.
1252 timeout (float): The timeout for this request.
1253 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1254 sent along with the request as metadata. Normally, each value must be of type `str`,
1255 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1256 be of type `bytes`.
1257
1258 Returns:
1259 google.cloud.tasks_v2.types.Queue:
1260 A queue is a container of related
1261 tasks. Queues are configured to manage
1262 how those tasks are dispatched.
1263 Configurable properties include rate
1264 limits, retry options, queue types, and
1265 others.
1266
1267 """
1268 # Create or coerce a protobuf request object.
1269 # - Quick check: If we got a request object, we should *not* have
1270 # gotten any keyword arguments that map to the request.
1271 flattened_params = [name]
1272 has_flattened_params = (
1273 len([param for param in flattened_params if param is not None]) > 0
1274 )
1275 if request is not None and has_flattened_params:
1276 raise ValueError(
1277 "If the `request` argument is set, then none of "
1278 "the individual field arguments should be set."
1279 )
1280
1281 # - Use the request object if provided (there's no risk of modifying the input as
1282 # there are no flattened fields), or create one.
1283 if not isinstance(request, cloudtasks.ResumeQueueRequest):
1284 request = cloudtasks.ResumeQueueRequest(request)
1285
1286 # If we have keyword arguments corresponding to fields on the
1287 # request, apply these.
1288 if name is not None:
1289 request.name = name
1290
1291 # Wrap the RPC method; this adds retry and timeout information,
1292 # and friendly error handling.
1293 rpc = self._client._transport._wrapped_methods[
1294 self._client._transport.resume_queue
1295 ]
1296
1297 # Certain fields should be provided within the metadata header;
1298 # add these here.
1299 metadata = tuple(metadata) + (
1300 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1301 )
1302
1303 # Validate the universe domain.
1304 self._client._validate_universe_domain()
1305
1306 # Send the request.
1307 response = await rpc(
1308 request,
1309 retry=retry,
1310 timeout=timeout,
1311 metadata=metadata,
1312 )
1313
1314 # Done; return the response.
1315 return response
1316
1317 async def get_iam_policy(
1318 self,
1319 request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None,
1320 *,
1321 resource: Optional[str] = None,
1322 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1323 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1324 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1325 ) -> policy_pb2.Policy:
1326 r"""Gets the access control policy for a
1327 [Queue][google.cloud.tasks.v2.Queue]. Returns an empty policy if
1328 the resource exists and does not have a policy set.
1329
1330 Authorization requires the following `Google
1331 IAM <https://cloud.google.com/iam>`__ permission on the
1332 specified resource parent:
1333
1334 - ``cloudtasks.queues.getIamPolicy``
1335
1336 .. code-block:: python
1337
1338 # This snippet has been automatically generated and should be regarded as a
1339 # code template only.
1340 # It will require modifications to work:
1341 # - It may require correct/in-range values for request initialization.
1342 # - It may require specifying regional endpoints when creating the service
1343 # client as shown in:
1344 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1345 from google.cloud import tasks_v2
1346 from google.iam.v1 import iam_policy_pb2 # type: ignore
1347
1348 async def sample_get_iam_policy():
1349 # Create a client
1350 client = tasks_v2.CloudTasksAsyncClient()
1351
1352 # Initialize request argument(s)
1353 request = iam_policy_pb2.GetIamPolicyRequest(
1354 resource="resource_value",
1355 )
1356
1357 # Make the request
1358 response = await client.get_iam_policy(request=request)
1359
1360 # Handle the response
1361 print(response)
1362
1363 Args:
1364 request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]):
1365 The request object. Request message for ``GetIamPolicy`` method.
1366 resource (:class:`str`):
1367 REQUIRED: The resource for which the
1368 policy is being requested. See the
1369 operation documentation for the
1370 appropriate value for this field.
1371
1372 This corresponds to the ``resource`` field
1373 on the ``request`` instance; if ``request`` is provided, this
1374 should not be set.
1375 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1376 should be retried.
1377 timeout (float): The timeout for this request.
1378 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1379 sent along with the request as metadata. Normally, each value must be of type `str`,
1380 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1381 be of type `bytes`.
1382
1383 Returns:
1384 google.iam.v1.policy_pb2.Policy:
1385 An Identity and Access Management (IAM) policy, which specifies access
1386 controls for Google Cloud resources.
1387
1388 A Policy is a collection of bindings. A binding binds
1389 one or more members, or principals, to a single role.
1390 Principals can be user accounts, service accounts,
1391 Google groups, and domains (such as G Suite). A role
1392 is a named list of permissions; each role can be an
1393 IAM predefined role or a user-created custom role.
1394
1395 For some types of Google Cloud resources, a binding
1396 can also specify a condition, which is a logical
1397 expression that allows access to a resource only if
1398 the expression evaluates to true. A condition can add
1399 constraints based on attributes of the request, the
1400 resource, or both. To learn which resources support
1401 conditions in their IAM policies, see the [IAM
1402 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
1403
1404 **JSON example:**
1405
1406 :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
1407
1408 **YAML example:**
1409
1410 :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
1411
1412 For a description of IAM and its features, see the
1413 [IAM
1414 documentation](\ https://cloud.google.com/iam/docs/).
1415
1416 """
1417 # Create or coerce a protobuf request object.
1418 # - Quick check: If we got a request object, we should *not* have
1419 # gotten any keyword arguments that map to the request.
1420 flattened_params = [resource]
1421 has_flattened_params = (
1422 len([param for param in flattened_params if param is not None]) > 0
1423 )
1424 if request is not None and has_flattened_params:
1425 raise ValueError(
1426 "If the `request` argument is set, then none of "
1427 "the individual field arguments should be set."
1428 )
1429
1430 # - The request isn't a proto-plus wrapped type,
1431 # so it must be constructed via keyword expansion.
1432 if isinstance(request, dict):
1433 request = iam_policy_pb2.GetIamPolicyRequest(**request)
1434 elif not request:
1435 request = iam_policy_pb2.GetIamPolicyRequest(resource=resource)
1436
1437 # Wrap the RPC method; this adds retry and timeout information,
1438 # and friendly error handling.
1439 rpc = self._client._transport._wrapped_methods[
1440 self._client._transport.get_iam_policy
1441 ]
1442
1443 # Certain fields should be provided within the metadata header;
1444 # add these here.
1445 metadata = tuple(metadata) + (
1446 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1447 )
1448
1449 # Validate the universe domain.
1450 self._client._validate_universe_domain()
1451
1452 # Send the request.
1453 response = await rpc(
1454 request,
1455 retry=retry,
1456 timeout=timeout,
1457 metadata=metadata,
1458 )
1459
1460 # Done; return the response.
1461 return response
1462
1463 async def set_iam_policy(
1464 self,
1465 request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None,
1466 *,
1467 resource: Optional[str] = None,
1468 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1469 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1470 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1471 ) -> policy_pb2.Policy:
1472 r"""Sets the access control policy for a
1473 [Queue][google.cloud.tasks.v2.Queue]. Replaces any existing
1474 policy.
1475
1476 Note: The Cloud Console does not check queue-level IAM
1477 permissions yet. Project-level permissions are required to use
1478 the Cloud Console.
1479
1480 Authorization requires the following `Google
1481 IAM <https://cloud.google.com/iam>`__ permission on the
1482 specified resource parent:
1483
1484 - ``cloudtasks.queues.setIamPolicy``
1485
1486 .. code-block:: python
1487
1488 # This snippet has been automatically generated and should be regarded as a
1489 # code template only.
1490 # It will require modifications to work:
1491 # - It may require correct/in-range values for request initialization.
1492 # - It may require specifying regional endpoints when creating the service
1493 # client as shown in:
1494 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1495 from google.cloud import tasks_v2
1496 from google.iam.v1 import iam_policy_pb2 # type: ignore
1497
1498 async def sample_set_iam_policy():
1499 # Create a client
1500 client = tasks_v2.CloudTasksAsyncClient()
1501
1502 # Initialize request argument(s)
1503 request = iam_policy_pb2.SetIamPolicyRequest(
1504 resource="resource_value",
1505 )
1506
1507 # Make the request
1508 response = await client.set_iam_policy(request=request)
1509
1510 # Handle the response
1511 print(response)
1512
1513 Args:
1514 request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]):
1515 The request object. Request message for ``SetIamPolicy`` method.
1516 resource (:class:`str`):
1517 REQUIRED: The resource for which the
1518 policy is being specified. See the
1519 operation documentation for the
1520 appropriate value for this field.
1521
1522 This corresponds to the ``resource`` field
1523 on the ``request`` instance; if ``request`` is provided, this
1524 should not be set.
1525 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1526 should be retried.
1527 timeout (float): The timeout for this request.
1528 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1529 sent along with the request as metadata. Normally, each value must be of type `str`,
1530 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1531 be of type `bytes`.
1532
1533 Returns:
1534 google.iam.v1.policy_pb2.Policy:
1535 An Identity and Access Management (IAM) policy, which specifies access
1536 controls for Google Cloud resources.
1537
1538 A Policy is a collection of bindings. A binding binds
1539 one or more members, or principals, to a single role.
1540 Principals can be user accounts, service accounts,
1541 Google groups, and domains (such as G Suite). A role
1542 is a named list of permissions; each role can be an
1543 IAM predefined role or a user-created custom role.
1544
1545 For some types of Google Cloud resources, a binding
1546 can also specify a condition, which is a logical
1547 expression that allows access to a resource only if
1548 the expression evaluates to true. A condition can add
1549 constraints based on attributes of the request, the
1550 resource, or both. To learn which resources support
1551 conditions in their IAM policies, see the [IAM
1552 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
1553
1554 **JSON example:**
1555
1556 :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
1557
1558 **YAML example:**
1559
1560 :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
1561
1562 For a description of IAM and its features, see the
1563 [IAM
1564 documentation](\ https://cloud.google.com/iam/docs/).
1565
1566 """
1567 # Create or coerce a protobuf request object.
1568 # - Quick check: If we got a request object, we should *not* have
1569 # gotten any keyword arguments that map to the request.
1570 flattened_params = [resource]
1571 has_flattened_params = (
1572 len([param for param in flattened_params if param is not None]) > 0
1573 )
1574 if request is not None and has_flattened_params:
1575 raise ValueError(
1576 "If the `request` argument is set, then none of "
1577 "the individual field arguments should be set."
1578 )
1579
1580 # - The request isn't a proto-plus wrapped type,
1581 # so it must be constructed via keyword expansion.
1582 if isinstance(request, dict):
1583 request = iam_policy_pb2.SetIamPolicyRequest(**request)
1584 elif not request:
1585 request = iam_policy_pb2.SetIamPolicyRequest(resource=resource)
1586
1587 # Wrap the RPC method; this adds retry and timeout information,
1588 # and friendly error handling.
1589 rpc = self._client._transport._wrapped_methods[
1590 self._client._transport.set_iam_policy
1591 ]
1592
1593 # Certain fields should be provided within the metadata header;
1594 # add these here.
1595 metadata = tuple(metadata) + (
1596 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1597 )
1598
1599 # Validate the universe domain.
1600 self._client._validate_universe_domain()
1601
1602 # Send the request.
1603 response = await rpc(
1604 request,
1605 retry=retry,
1606 timeout=timeout,
1607 metadata=metadata,
1608 )
1609
1610 # Done; return the response.
1611 return response
1612
1613 async def test_iam_permissions(
1614 self,
1615 request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None,
1616 *,
1617 resource: Optional[str] = None,
1618 permissions: Optional[MutableSequence[str]] = None,
1619 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1620 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1621 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1622 ) -> iam_policy_pb2.TestIamPermissionsResponse:
1623 r"""Returns permissions that a caller has on a
1624 [Queue][google.cloud.tasks.v2.Queue]. If the resource does not
1625 exist, this will return an empty set of permissions, not a
1626 [NOT_FOUND][google.rpc.Code.NOT_FOUND] error.
1627
1628 Note: This operation is designed to be used for building
1629 permission-aware UIs and command-line tools, not for
1630 authorization checking. This operation may "fail open" without
1631 warning.
1632
1633 .. code-block:: python
1634
1635 # This snippet has been automatically generated and should be regarded as a
1636 # code template only.
1637 # It will require modifications to work:
1638 # - It may require correct/in-range values for request initialization.
1639 # - It may require specifying regional endpoints when creating the service
1640 # client as shown in:
1641 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1642 from google.cloud import tasks_v2
1643 from google.iam.v1 import iam_policy_pb2 # type: ignore
1644
1645 async def sample_test_iam_permissions():
1646 # Create a client
1647 client = tasks_v2.CloudTasksAsyncClient()
1648
1649 # Initialize request argument(s)
1650 request = iam_policy_pb2.TestIamPermissionsRequest(
1651 resource="resource_value",
1652 permissions=['permissions_value1', 'permissions_value2'],
1653 )
1654
1655 # Make the request
1656 response = await client.test_iam_permissions(request=request)
1657
1658 # Handle the response
1659 print(response)
1660
1661 Args:
1662 request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]):
1663 The request object. Request message for ``TestIamPermissions`` method.
1664 resource (:class:`str`):
1665 REQUIRED: The resource for which the
1666 policy detail is being requested. See
1667 the operation documentation for the
1668 appropriate value for this field.
1669
1670 This corresponds to the ``resource`` field
1671 on the ``request`` instance; if ``request`` is provided, this
1672 should not be set.
1673 permissions (:class:`MutableSequence[str]`):
1674 The set of permissions to check for the ``resource``.
1675 Permissions with wildcards (such as '*' or 'storage.*')
1676 are not allowed. For more information see `IAM
1677 Overview <https://cloud.google.com/iam/docs/overview#permissions>`__.
1678
1679 This corresponds to the ``permissions`` field
1680 on the ``request`` instance; if ``request`` is provided, this
1681 should not be set.
1682 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1683 should be retried.
1684 timeout (float): The timeout for this request.
1685 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1686 sent along with the request as metadata. Normally, each value must be of type `str`,
1687 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1688 be of type `bytes`.
1689
1690 Returns:
1691 google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse:
1692 Response message for TestIamPermissions method.
1693 """
1694 # Create or coerce a protobuf request object.
1695 # - Quick check: If we got a request object, we should *not* have
1696 # gotten any keyword arguments that map to the request.
1697 flattened_params = [resource, permissions]
1698 has_flattened_params = (
1699 len([param for param in flattened_params if param is not None]) > 0
1700 )
1701 if request is not None and has_flattened_params:
1702 raise ValueError(
1703 "If the `request` argument is set, then none of "
1704 "the individual field arguments should be set."
1705 )
1706
1707 # - The request isn't a proto-plus wrapped type,
1708 # so it must be constructed via keyword expansion.
1709 if isinstance(request, dict):
1710 request = iam_policy_pb2.TestIamPermissionsRequest(**request)
1711 elif not request:
1712 request = iam_policy_pb2.TestIamPermissionsRequest(
1713 resource=resource, permissions=permissions
1714 )
1715
1716 # Wrap the RPC method; this adds retry and timeout information,
1717 # and friendly error handling.
1718 rpc = self._client._transport._wrapped_methods[
1719 self._client._transport.test_iam_permissions
1720 ]
1721
1722 # Certain fields should be provided within the metadata header;
1723 # add these here.
1724 metadata = tuple(metadata) + (
1725 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1726 )
1727
1728 # Validate the universe domain.
1729 self._client._validate_universe_domain()
1730
1731 # Send the request.
1732 response = await rpc(
1733 request,
1734 retry=retry,
1735 timeout=timeout,
1736 metadata=metadata,
1737 )
1738
1739 # Done; return the response.
1740 return response
1741
1742 async def list_tasks(
1743 self,
1744 request: Optional[Union[cloudtasks.ListTasksRequest, dict]] = None,
1745 *,
1746 parent: Optional[str] = None,
1747 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1748 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1749 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1750 ) -> pagers.ListTasksAsyncPager:
1751 r"""Lists the tasks in a queue.
1752
1753 By default, only the
1754 [BASIC][google.cloud.tasks.v2.Task.View.BASIC] view is retrieved
1755 due to performance considerations;
1756 [response_view][google.cloud.tasks.v2.ListTasksRequest.response_view]
1757 controls the subset of information which is returned.
1758
1759 The tasks may be returned in any order. The ordering may change
1760 at any time.
1761
1762 .. code-block:: python
1763
1764 # This snippet has been automatically generated and should be regarded as a
1765 # code template only.
1766 # It will require modifications to work:
1767 # - It may require correct/in-range values for request initialization.
1768 # - It may require specifying regional endpoints when creating the service
1769 # client as shown in:
1770 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1771 from google.cloud import tasks_v2
1772
1773 async def sample_list_tasks():
1774 # Create a client
1775 client = tasks_v2.CloudTasksAsyncClient()
1776
1777 # Initialize request argument(s)
1778 request = tasks_v2.ListTasksRequest(
1779 parent="parent_value",
1780 )
1781
1782 # Make the request
1783 page_result = client.list_tasks(request=request)
1784
1785 # Handle the response
1786 async for response in page_result:
1787 print(response)
1788
1789 Args:
1790 request (Optional[Union[google.cloud.tasks_v2.types.ListTasksRequest, dict]]):
1791 The request object. Request message for listing tasks using
1792 [ListTasks][google.cloud.tasks.v2.CloudTasks.ListTasks].
1793 parent (:class:`str`):
1794 Required. The queue name. For example:
1795 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID``
1796
1797 This corresponds to the ``parent`` field
1798 on the ``request`` instance; if ``request`` is provided, this
1799 should not be set.
1800 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1801 should be retried.
1802 timeout (float): The timeout for this request.
1803 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1804 sent along with the request as metadata. Normally, each value must be of type `str`,
1805 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1806 be of type `bytes`.
1807
1808 Returns:
1809 google.cloud.tasks_v2.services.cloud_tasks.pagers.ListTasksAsyncPager:
1810 Response message for listing tasks using
1811 [ListTasks][google.cloud.tasks.v2.CloudTasks.ListTasks].
1812
1813 Iterating over this object will yield results and
1814 resolve additional pages automatically.
1815
1816 """
1817 # Create or coerce a protobuf request object.
1818 # - Quick check: If we got a request object, we should *not* have
1819 # gotten any keyword arguments that map to the request.
1820 flattened_params = [parent]
1821 has_flattened_params = (
1822 len([param for param in flattened_params if param is not None]) > 0
1823 )
1824 if request is not None and has_flattened_params:
1825 raise ValueError(
1826 "If the `request` argument is set, then none of "
1827 "the individual field arguments should be set."
1828 )
1829
1830 # - Use the request object if provided (there's no risk of modifying the input as
1831 # there are no flattened fields), or create one.
1832 if not isinstance(request, cloudtasks.ListTasksRequest):
1833 request = cloudtasks.ListTasksRequest(request)
1834
1835 # If we have keyword arguments corresponding to fields on the
1836 # request, apply these.
1837 if parent is not None:
1838 request.parent = parent
1839
1840 # Wrap the RPC method; this adds retry and timeout information,
1841 # and friendly error handling.
1842 rpc = self._client._transport._wrapped_methods[
1843 self._client._transport.list_tasks
1844 ]
1845
1846 # Certain fields should be provided within the metadata header;
1847 # add these here.
1848 metadata = tuple(metadata) + (
1849 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
1850 )
1851
1852 # Validate the universe domain.
1853 self._client._validate_universe_domain()
1854
1855 # Send the request.
1856 response = await rpc(
1857 request,
1858 retry=retry,
1859 timeout=timeout,
1860 metadata=metadata,
1861 )
1862
1863 # This method is paged; wrap the response in a pager, which provides
1864 # an `__aiter__` convenience method.
1865 response = pagers.ListTasksAsyncPager(
1866 method=rpc,
1867 request=request,
1868 response=response,
1869 retry=retry,
1870 timeout=timeout,
1871 metadata=metadata,
1872 )
1873
1874 # Done; return the response.
1875 return response
1876
1877 async def get_task(
1878 self,
1879 request: Optional[Union[cloudtasks.GetTaskRequest, dict]] = None,
1880 *,
1881 name: Optional[str] = None,
1882 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1883 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1884 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1885 ) -> task.Task:
1886 r"""Gets a task.
1887
1888 .. code-block:: python
1889
1890 # This snippet has been automatically generated and should be regarded as a
1891 # code template only.
1892 # It will require modifications to work:
1893 # - It may require correct/in-range values for request initialization.
1894 # - It may require specifying regional endpoints when creating the service
1895 # client as shown in:
1896 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1897 from google.cloud import tasks_v2
1898
1899 async def sample_get_task():
1900 # Create a client
1901 client = tasks_v2.CloudTasksAsyncClient()
1902
1903 # Initialize request argument(s)
1904 request = tasks_v2.GetTaskRequest(
1905 name="name_value",
1906 )
1907
1908 # Make the request
1909 response = await client.get_task(request=request)
1910
1911 # Handle the response
1912 print(response)
1913
1914 Args:
1915 request (Optional[Union[google.cloud.tasks_v2.types.GetTaskRequest, dict]]):
1916 The request object. Request message for getting a task using
1917 [GetTask][google.cloud.tasks.v2.CloudTasks.GetTask].
1918 name (:class:`str`):
1919 Required. The task name. For example:
1920 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID``
1921
1922 This corresponds to the ``name`` field
1923 on the ``request`` instance; if ``request`` is provided, this
1924 should not be set.
1925 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1926 should be retried.
1927 timeout (float): The timeout for this request.
1928 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1929 sent along with the request as metadata. Normally, each value must be of type `str`,
1930 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1931 be of type `bytes`.
1932
1933 Returns:
1934 google.cloud.tasks_v2.types.Task:
1935 A unit of scheduled work.
1936 """
1937 # Create or coerce a protobuf request object.
1938 # - Quick check: If we got a request object, we should *not* have
1939 # gotten any keyword arguments that map to the request.
1940 flattened_params = [name]
1941 has_flattened_params = (
1942 len([param for param in flattened_params if param is not None]) > 0
1943 )
1944 if request is not None and has_flattened_params:
1945 raise ValueError(
1946 "If the `request` argument is set, then none of "
1947 "the individual field arguments should be set."
1948 )
1949
1950 # - Use the request object if provided (there's no risk of modifying the input as
1951 # there are no flattened fields), or create one.
1952 if not isinstance(request, cloudtasks.GetTaskRequest):
1953 request = cloudtasks.GetTaskRequest(request)
1954
1955 # If we have keyword arguments corresponding to fields on the
1956 # request, apply these.
1957 if name is not None:
1958 request.name = name
1959
1960 # Wrap the RPC method; this adds retry and timeout information,
1961 # and friendly error handling.
1962 rpc = self._client._transport._wrapped_methods[self._client._transport.get_task]
1963
1964 # Certain fields should be provided within the metadata header;
1965 # add these here.
1966 metadata = tuple(metadata) + (
1967 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1968 )
1969
1970 # Validate the universe domain.
1971 self._client._validate_universe_domain()
1972
1973 # Send the request.
1974 response = await rpc(
1975 request,
1976 retry=retry,
1977 timeout=timeout,
1978 metadata=metadata,
1979 )
1980
1981 # Done; return the response.
1982 return response
1983
1984 async def create_task(
1985 self,
1986 request: Optional[Union[cloudtasks.CreateTaskRequest, dict]] = None,
1987 *,
1988 parent: Optional[str] = None,
1989 task: Optional[gct_task.Task] = None,
1990 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1991 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1992 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1993 ) -> gct_task.Task:
1994 r"""Creates a task and adds it to a queue.
1995
1996 Tasks cannot be updated after creation; there is no UpdateTask
1997 command.
1998
1999 - The maximum task size is 100KB.
2000
2001 .. code-block:: python
2002
2003 # This snippet has been automatically generated and should be regarded as a
2004 # code template only.
2005 # It will require modifications to work:
2006 # - It may require correct/in-range values for request initialization.
2007 # - It may require specifying regional endpoints when creating the service
2008 # client as shown in:
2009 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2010 from google.cloud import tasks_v2
2011
2012 async def sample_create_task():
2013 # Create a client
2014 client = tasks_v2.CloudTasksAsyncClient()
2015
2016 # Initialize request argument(s)
2017 request = tasks_v2.CreateTaskRequest(
2018 parent="parent_value",
2019 )
2020
2021 # Make the request
2022 response = await client.create_task(request=request)
2023
2024 # Handle the response
2025 print(response)
2026
2027 Args:
2028 request (Optional[Union[google.cloud.tasks_v2.types.CreateTaskRequest, dict]]):
2029 The request object. Request message for
2030 [CreateTask][google.cloud.tasks.v2.CloudTasks.CreateTask].
2031 parent (:class:`str`):
2032 Required. The queue name. For example:
2033 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID``
2034
2035 The queue must already exist.
2036
2037 This corresponds to the ``parent`` field
2038 on the ``request`` instance; if ``request`` is provided, this
2039 should not be set.
2040 task (:class:`google.cloud.tasks_v2.types.Task`):
2041 Required. The task to add.
2042
2043 Task names have the following format:
2044 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID``.
2045 The user can optionally specify a task
2046 [name][google.cloud.tasks.v2.Task.name]. If a name is
2047 not specified then the system will generate a random
2048 unique task id, which will be set in the task returned
2049 in the [response][google.cloud.tasks.v2.Task.name].
2050
2051 If
2052 [schedule_time][google.cloud.tasks.v2.Task.schedule_time]
2053 is not set or is in the past then Cloud Tasks will set
2054 it to the current time.
2055
2056 Task De-duplication:
2057
2058 Explicitly specifying a task ID enables task
2059 de-duplication. If a task's ID is identical to that of
2060 an existing task or a task that was deleted or executed
2061 recently then the call will fail with
2062 [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS]. If the
2063 task's queue was created using Cloud Tasks, then another
2064 task with the same name can't be created for ~1hour
2065 after the original task was deleted or executed. If the
2066 task's queue was created using queue.yaml or queue.xml,
2067 then another task with the same name can't be created
2068 for ~9days after the original task was deleted or
2069 executed.
2070
2071 Because there is an extra lookup cost to identify
2072 duplicate task names, these
2073 [CreateTask][google.cloud.tasks.v2.CloudTasks.CreateTask]
2074 calls have significantly increased latency. Using hashed
2075 strings for the task id or for the prefix of the task id
2076 is recommended. Choosing task ids that are sequential or
2077 have sequential prefixes, for example using a timestamp,
2078 causes an increase in latency and error rates in all
2079 task commands. The infrastructure relies on an
2080 approximately uniform distribution of task ids to store
2081 and serve tasks efficiently.
2082
2083 This corresponds to the ``task`` field
2084 on the ``request`` instance; if ``request`` is provided, this
2085 should not be set.
2086 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
2087 should be retried.
2088 timeout (float): The timeout for this request.
2089 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2090 sent along with the request as metadata. Normally, each value must be of type `str`,
2091 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2092 be of type `bytes`.
2093
2094 Returns:
2095 google.cloud.tasks_v2.types.Task:
2096 A unit of scheduled work.
2097 """
2098 # Create or coerce a protobuf request object.
2099 # - Quick check: If we got a request object, we should *not* have
2100 # gotten any keyword arguments that map to the request.
2101 flattened_params = [parent, task]
2102 has_flattened_params = (
2103 len([param for param in flattened_params if param is not None]) > 0
2104 )
2105 if request is not None and has_flattened_params:
2106 raise ValueError(
2107 "If the `request` argument is set, then none of "
2108 "the individual field arguments should be set."
2109 )
2110
2111 # - Use the request object if provided (there's no risk of modifying the input as
2112 # there are no flattened fields), or create one.
2113 if not isinstance(request, cloudtasks.CreateTaskRequest):
2114 request = cloudtasks.CreateTaskRequest(request)
2115
2116 # If we have keyword arguments corresponding to fields on the
2117 # request, apply these.
2118 if parent is not None:
2119 request.parent = parent
2120 if task is not None:
2121 request.task = task
2122
2123 # Wrap the RPC method; this adds retry and timeout information,
2124 # and friendly error handling.
2125 rpc = self._client._transport._wrapped_methods[
2126 self._client._transport.create_task
2127 ]
2128
2129 # Certain fields should be provided within the metadata header;
2130 # add these here.
2131 metadata = tuple(metadata) + (
2132 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
2133 )
2134
2135 # Validate the universe domain.
2136 self._client._validate_universe_domain()
2137
2138 # Send the request.
2139 response = await rpc(
2140 request,
2141 retry=retry,
2142 timeout=timeout,
2143 metadata=metadata,
2144 )
2145
2146 # Done; return the response.
2147 return response
2148
2149 async def delete_task(
2150 self,
2151 request: Optional[Union[cloudtasks.DeleteTaskRequest, dict]] = None,
2152 *,
2153 name: Optional[str] = None,
2154 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2155 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2156 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2157 ) -> None:
2158 r"""Deletes a task.
2159
2160 A task can be deleted if it is scheduled or dispatched.
2161 A task cannot be deleted if it has executed successfully
2162 or permanently failed.
2163
2164 .. code-block:: python
2165
2166 # This snippet has been automatically generated and should be regarded as a
2167 # code template only.
2168 # It will require modifications to work:
2169 # - It may require correct/in-range values for request initialization.
2170 # - It may require specifying regional endpoints when creating the service
2171 # client as shown in:
2172 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2173 from google.cloud import tasks_v2
2174
2175 async def sample_delete_task():
2176 # Create a client
2177 client = tasks_v2.CloudTasksAsyncClient()
2178
2179 # Initialize request argument(s)
2180 request = tasks_v2.DeleteTaskRequest(
2181 name="name_value",
2182 )
2183
2184 # Make the request
2185 await client.delete_task(request=request)
2186
2187 Args:
2188 request (Optional[Union[google.cloud.tasks_v2.types.DeleteTaskRequest, dict]]):
2189 The request object. Request message for deleting a task using
2190 [DeleteTask][google.cloud.tasks.v2.CloudTasks.DeleteTask].
2191 name (:class:`str`):
2192 Required. The task name. For example:
2193 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID``
2194
2195 This corresponds to the ``name`` field
2196 on the ``request`` instance; if ``request`` is provided, this
2197 should not be set.
2198 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
2199 should be retried.
2200 timeout (float): The timeout for this request.
2201 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2202 sent along with the request as metadata. Normally, each value must be of type `str`,
2203 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2204 be of type `bytes`.
2205 """
2206 # Create or coerce a protobuf request object.
2207 # - Quick check: If we got a request object, we should *not* have
2208 # gotten any keyword arguments that map to the request.
2209 flattened_params = [name]
2210 has_flattened_params = (
2211 len([param for param in flattened_params if param is not None]) > 0
2212 )
2213 if request is not None and has_flattened_params:
2214 raise ValueError(
2215 "If the `request` argument is set, then none of "
2216 "the individual field arguments should be set."
2217 )
2218
2219 # - Use the request object if provided (there's no risk of modifying the input as
2220 # there are no flattened fields), or create one.
2221 if not isinstance(request, cloudtasks.DeleteTaskRequest):
2222 request = cloudtasks.DeleteTaskRequest(request)
2223
2224 # If we have keyword arguments corresponding to fields on the
2225 # request, apply these.
2226 if name is not None:
2227 request.name = name
2228
2229 # Wrap the RPC method; this adds retry and timeout information,
2230 # and friendly error handling.
2231 rpc = self._client._transport._wrapped_methods[
2232 self._client._transport.delete_task
2233 ]
2234
2235 # Certain fields should be provided within the metadata header;
2236 # add these here.
2237 metadata = tuple(metadata) + (
2238 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
2239 )
2240
2241 # Validate the universe domain.
2242 self._client._validate_universe_domain()
2243
2244 # Send the request.
2245 await rpc(
2246 request,
2247 retry=retry,
2248 timeout=timeout,
2249 metadata=metadata,
2250 )
2251
2252 async def run_task(
2253 self,
2254 request: Optional[Union[cloudtasks.RunTaskRequest, dict]] = None,
2255 *,
2256 name: Optional[str] = None,
2257 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2258 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2259 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2260 ) -> task.Task:
2261 r"""Forces a task to run now.
2262
2263 When this method is called, Cloud Tasks will dispatch the task,
2264 even if the task is already running, the queue has reached its
2265 [RateLimits][google.cloud.tasks.v2.RateLimits] or is
2266 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED].
2267
2268 This command is meant to be used for manual debugging. For
2269 example, [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] can
2270 be used to retry a failed task after a fix has been made or to
2271 manually force a task to be dispatched now.
2272
2273 The dispatched task is returned. That is, the task that is
2274 returned contains the [status][Task.status] after the task is
2275 dispatched but before the task is received by its target.
2276
2277 If Cloud Tasks receives a successful response from the task's
2278 target, then the task will be deleted; otherwise the task's
2279 [schedule_time][google.cloud.tasks.v2.Task.schedule_time] will
2280 be reset to the time that
2281 [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] was called
2282 plus the retry delay specified in the queue's
2283 [RetryConfig][google.cloud.tasks.v2.RetryConfig].
2284
2285 [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] returns
2286 [NOT_FOUND][google.rpc.Code.NOT_FOUND] when it is called on a
2287 task that has already succeeded or permanently failed.
2288
2289 .. code-block:: python
2290
2291 # This snippet has been automatically generated and should be regarded as a
2292 # code template only.
2293 # It will require modifications to work:
2294 # - It may require correct/in-range values for request initialization.
2295 # - It may require specifying regional endpoints when creating the service
2296 # client as shown in:
2297 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2298 from google.cloud import tasks_v2
2299
2300 async def sample_run_task():
2301 # Create a client
2302 client = tasks_v2.CloudTasksAsyncClient()
2303
2304 # Initialize request argument(s)
2305 request = tasks_v2.RunTaskRequest(
2306 name="name_value",
2307 )
2308
2309 # Make the request
2310 response = await client.run_task(request=request)
2311
2312 # Handle the response
2313 print(response)
2314
2315 Args:
2316 request (Optional[Union[google.cloud.tasks_v2.types.RunTaskRequest, dict]]):
2317 The request object. Request message for forcing a task to run now using
2318 [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask].
2319 name (:class:`str`):
2320 Required. The task name. For example:
2321 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID``
2322
2323 This corresponds to the ``name`` field
2324 on the ``request`` instance; if ``request`` is provided, this
2325 should not be set.
2326 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
2327 should be retried.
2328 timeout (float): The timeout for this request.
2329 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2330 sent along with the request as metadata. Normally, each value must be of type `str`,
2331 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2332 be of type `bytes`.
2333
2334 Returns:
2335 google.cloud.tasks_v2.types.Task:
2336 A unit of scheduled work.
2337 """
2338 # Create or coerce a protobuf request object.
2339 # - Quick check: If we got a request object, we should *not* have
2340 # gotten any keyword arguments that map to the request.
2341 flattened_params = [name]
2342 has_flattened_params = (
2343 len([param for param in flattened_params if param is not None]) > 0
2344 )
2345 if request is not None and has_flattened_params:
2346 raise ValueError(
2347 "If the `request` argument is set, then none of "
2348 "the individual field arguments should be set."
2349 )
2350
2351 # - Use the request object if provided (there's no risk of modifying the input as
2352 # there are no flattened fields), or create one.
2353 if not isinstance(request, cloudtasks.RunTaskRequest):
2354 request = cloudtasks.RunTaskRequest(request)
2355
2356 # If we have keyword arguments corresponding to fields on the
2357 # request, apply these.
2358 if name is not None:
2359 request.name = name
2360
2361 # Wrap the RPC method; this adds retry and timeout information,
2362 # and friendly error handling.
2363 rpc = self._client._transport._wrapped_methods[self._client._transport.run_task]
2364
2365 # Certain fields should be provided within the metadata header;
2366 # add these here.
2367 metadata = tuple(metadata) + (
2368 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
2369 )
2370
2371 # Validate the universe domain.
2372 self._client._validate_universe_domain()
2373
2374 # Send the request.
2375 response = await rpc(
2376 request,
2377 retry=retry,
2378 timeout=timeout,
2379 metadata=metadata,
2380 )
2381
2382 # Done; return the response.
2383 return response
2384
2385 async def get_location(
2386 self,
2387 request: Optional[locations_pb2.GetLocationRequest] = None,
2388 *,
2389 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2390 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2391 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2392 ) -> locations_pb2.Location:
2393 r"""Gets information about a location.
2394
2395 Args:
2396 request (:class:`~.location_pb2.GetLocationRequest`):
2397 The request object. Request message for
2398 `GetLocation` method.
2399 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
2400 if any, should be retried.
2401 timeout (float): The timeout for this request.
2402 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2403 sent along with the request as metadata. Normally, each value must be of type `str`,
2404 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2405 be of type `bytes`.
2406 Returns:
2407 ~.location_pb2.Location:
2408 Location object.
2409 """
2410 # Create or coerce a protobuf request object.
2411 # The request isn't a proto-plus wrapped type,
2412 # so it must be constructed via keyword expansion.
2413 if isinstance(request, dict):
2414 request = locations_pb2.GetLocationRequest(**request)
2415
2416 # Wrap the RPC method; this adds retry and timeout information,
2417 # and friendly error handling.
2418 rpc = self.transport._wrapped_methods[self._client._transport.get_location]
2419
2420 # Certain fields should be provided within the metadata header;
2421 # add these here.
2422 metadata = tuple(metadata) + (
2423 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
2424 )
2425
2426 # Validate the universe domain.
2427 self._client._validate_universe_domain()
2428
2429 # Send the request.
2430 response = await rpc(
2431 request,
2432 retry=retry,
2433 timeout=timeout,
2434 metadata=metadata,
2435 )
2436
2437 # Done; return the response.
2438 return response
2439
2440 async def list_locations(
2441 self,
2442 request: Optional[locations_pb2.ListLocationsRequest] = None,
2443 *,
2444 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2445 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2446 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2447 ) -> locations_pb2.ListLocationsResponse:
2448 r"""Lists information about the supported locations for this service.
2449
2450 Args:
2451 request (:class:`~.location_pb2.ListLocationsRequest`):
2452 The request object. Request message for
2453 `ListLocations` method.
2454 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
2455 if any, should be retried.
2456 timeout (float): The timeout for this request.
2457 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2458 sent along with the request as metadata. Normally, each value must be of type `str`,
2459 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2460 be of type `bytes`.
2461 Returns:
2462 ~.location_pb2.ListLocationsResponse:
2463 Response message for ``ListLocations`` method.
2464 """
2465 # Create or coerce a protobuf request object.
2466 # The request isn't a proto-plus wrapped type,
2467 # so it must be constructed via keyword expansion.
2468 if isinstance(request, dict):
2469 request = locations_pb2.ListLocationsRequest(**request)
2470
2471 # Wrap the RPC method; this adds retry and timeout information,
2472 # and friendly error handling.
2473 rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
2474
2475 # Certain fields should be provided within the metadata header;
2476 # add these here.
2477 metadata = tuple(metadata) + (
2478 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
2479 )
2480
2481 # Validate the universe domain.
2482 self._client._validate_universe_domain()
2483
2484 # Send the request.
2485 response = await rpc(
2486 request,
2487 retry=retry,
2488 timeout=timeout,
2489 metadata=metadata,
2490 )
2491
2492 # Done; return the response.
2493 return response
2494
2495 async def __aenter__(self) -> "CloudTasksAsyncClient":
2496 return self
2497
2498 async def __aexit__(self, exc_type, exc, tb):
2499 await self.transport.close()
2500
2501
2502DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
2503 gapic_version=package_version.__version__
2504)
2505
2506if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER
2507 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
2508
2509
2510__all__ = ("CloudTasksAsyncClient",)