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