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