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