Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/google/cloud/tasks_v2/services/cloud_tasks/client.py: 40%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

511 statements  

1# -*- coding: utf-8 -*- 

2# Copyright 2025 Google LLC 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# 

8# http://www.apache.org/licenses/LICENSE-2.0 

9# 

10# Unless required by applicable law or agreed to in writing, software 

11# distributed under the License is distributed on an "AS IS" BASIS, 

12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

13# See the License for the specific language governing permissions and 

14# limitations under the License. 

15# 

16from collections import OrderedDict 

17from http import HTTPStatus 

18import json 

19import logging as std_logging 

20import os 

21import re 

22from typing import ( 

23 Callable, 

24 Dict, 

25 Mapping, 

26 MutableMapping, 

27 MutableSequence, 

28 Optional, 

29 Sequence, 

30 Tuple, 

31 Type, 

32 Union, 

33 cast, 

34) 

35import warnings 

36 

37from google.api_core import client_options as client_options_lib 

38from google.api_core import exceptions as core_exceptions 

39from google.api_core import gapic_v1 

40from google.api_core import retry as retries 

41from google.auth import credentials as ga_credentials # type: ignore 

42from google.auth.exceptions import MutualTLSChannelError # type: ignore 

43from google.auth.transport import mtls # type: ignore 

44from google.auth.transport.grpc import SslCredentials # type: ignore 

45from google.oauth2 import service_account # type: ignore 

46import google.protobuf 

47 

48from google.cloud.tasks_v2 import gapic_version as package_version 

49 

50try: 

51 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 

52except AttributeError: # pragma: NO COVER 

53 OptionalRetry = Union[retries.Retry, object, None] # type: ignore 

54 

55try: 

56 from google.api_core import client_logging # type: ignore 

57 

58 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

59except ImportError: # pragma: NO COVER 

60 CLIENT_LOGGING_SUPPORTED = False 

61 

62_LOGGER = std_logging.getLogger(__name__) 

63 

64from google.cloud.location import locations_pb2 # type: ignore 

65from google.iam.v1 import iam_policy_pb2 # type: ignore 

66from google.iam.v1 import policy_pb2 # type: ignore 

67from google.protobuf import duration_pb2 # type: ignore 

68from google.protobuf import field_mask_pb2 # type: ignore 

69from google.protobuf import timestamp_pb2 # type: ignore 

70 

71from google.cloud.tasks_v2.services.cloud_tasks import pagers 

72from google.cloud.tasks_v2.types import cloudtasks 

73from google.cloud.tasks_v2.types import queue 

74from google.cloud.tasks_v2.types import queue as gct_queue 

75from google.cloud.tasks_v2.types import target 

76from google.cloud.tasks_v2.types import task 

77from google.cloud.tasks_v2.types import task as gct_task 

78 

79from .transports.base import DEFAULT_CLIENT_INFO, CloudTasksTransport 

80from .transports.grpc import CloudTasksGrpcTransport 

81from .transports.grpc_asyncio import CloudTasksGrpcAsyncIOTransport 

82from .transports.rest import CloudTasksRestTransport 

83 

84 

85class CloudTasksClientMeta(type): 

86 """Metaclass for the CloudTasks client. 

87 

88 This provides class-level methods for building and retrieving 

89 support objects (e.g. transport) without polluting the client instance 

90 objects. 

91 """ 

92 

93 _transport_registry = OrderedDict() # type: Dict[str, Type[CloudTasksTransport]] 

94 _transport_registry["grpc"] = CloudTasksGrpcTransport 

95 _transport_registry["grpc_asyncio"] = CloudTasksGrpcAsyncIOTransport 

96 _transport_registry["rest"] = CloudTasksRestTransport 

97 

98 def get_transport_class( 

99 cls, 

100 label: Optional[str] = None, 

101 ) -> Type[CloudTasksTransport]: 

102 """Returns an appropriate transport class. 

103 

104 Args: 

105 label: The name of the desired transport. If none is 

106 provided, then the first transport in the registry is used. 

107 

108 Returns: 

109 The transport class to use. 

110 """ 

111 # If a specific transport is requested, return that one. 

112 if label: 

113 return cls._transport_registry[label] 

114 

115 # No transport is requested; return the default (that is, the first one 

116 # in the dictionary). 

117 return next(iter(cls._transport_registry.values())) 

118 

119 

120class CloudTasksClient(metaclass=CloudTasksClientMeta): 

121 """Cloud Tasks allows developers to manage the execution of 

122 background work in their applications. 

123 """ 

124 

125 @staticmethod 

126 def _get_default_mtls_endpoint(api_endpoint): 

127 """Converts api endpoint to mTLS endpoint. 

128 

129 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to 

130 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. 

131 Args: 

132 api_endpoint (Optional[str]): the api endpoint to convert. 

133 Returns: 

134 str: converted mTLS api endpoint. 

135 """ 

136 if not api_endpoint: 

137 return api_endpoint 

138 

139 mtls_endpoint_re = re.compile( 

140 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" 

141 ) 

142 

143 m = mtls_endpoint_re.match(api_endpoint) 

144 name, mtls, sandbox, googledomain = m.groups() 

145 if mtls or not googledomain: 

146 return api_endpoint 

147 

148 if sandbox: 

149 return api_endpoint.replace( 

150 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

151 ) 

152 

153 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") 

154 

155 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. 

156 DEFAULT_ENDPOINT = "cloudtasks.googleapis.com" 

157 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

158 DEFAULT_ENDPOINT 

159 ) 

160 

161 _DEFAULT_ENDPOINT_TEMPLATE = "cloudtasks.{UNIVERSE_DOMAIN}" 

162 _DEFAULT_UNIVERSE = "googleapis.com" 

163 

164 @classmethod 

165 def from_service_account_info(cls, info: dict, *args, **kwargs): 

166 """Creates an instance of this client using the provided credentials 

167 info. 

168 

169 Args: 

170 info (dict): The service account private key info. 

171 args: Additional arguments to pass to the constructor. 

172 kwargs: Additional arguments to pass to the constructor. 

173 

174 Returns: 

175 CloudTasksClient: The constructed client. 

176 """ 

177 credentials = service_account.Credentials.from_service_account_info(info) 

178 kwargs["credentials"] = credentials 

179 return cls(*args, **kwargs) 

180 

181 @classmethod 

182 def from_service_account_file(cls, filename: str, *args, **kwargs): 

183 """Creates an instance of this client using the provided credentials 

184 file. 

185 

186 Args: 

187 filename (str): The path to the service account private key json 

188 file. 

189 args: Additional arguments to pass to the constructor. 

190 kwargs: Additional arguments to pass to the constructor. 

191 

192 Returns: 

193 CloudTasksClient: The constructed client. 

194 """ 

195 credentials = service_account.Credentials.from_service_account_file(filename) 

196 kwargs["credentials"] = credentials 

197 return cls(*args, **kwargs) 

198 

199 from_service_account_json = from_service_account_file 

200 

201 @property 

202 def transport(self) -> CloudTasksTransport: 

203 """Returns the transport used by the client instance. 

204 

205 Returns: 

206 CloudTasksTransport: The transport used by the client 

207 instance. 

208 """ 

209 return self._transport 

210 

211 @staticmethod 

212 def queue_path( 

213 project: str, 

214 location: str, 

215 queue: str, 

216 ) -> str: 

217 """Returns a fully-qualified queue string.""" 

218 return "projects/{project}/locations/{location}/queues/{queue}".format( 

219 project=project, 

220 location=location, 

221 queue=queue, 

222 ) 

223 

224 @staticmethod 

225 def parse_queue_path(path: str) -> Dict[str, str]: 

226 """Parses a queue path into its component segments.""" 

227 m = re.match( 

228 r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)/queues/(?P<queue>.+?)$", 

229 path, 

230 ) 

231 return m.groupdict() if m else {} 

232 

233 @staticmethod 

234 def task_path( 

235 project: str, 

236 location: str, 

237 queue: str, 

238 task: str, 

239 ) -> str: 

240 """Returns a fully-qualified task string.""" 

241 return "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}".format( 

242 project=project, 

243 location=location, 

244 queue=queue, 

245 task=task, 

246 ) 

247 

248 @staticmethod 

249 def parse_task_path(path: str) -> Dict[str, str]: 

250 """Parses a task path into its component segments.""" 

251 m = re.match( 

252 r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)/queues/(?P<queue>.+?)/tasks/(?P<task>.+?)$", 

253 path, 

254 ) 

255 return m.groupdict() if m else {} 

256 

257 @staticmethod 

258 def common_billing_account_path( 

259 billing_account: str, 

260 ) -> str: 

261 """Returns a fully-qualified billing_account string.""" 

262 return "billingAccounts/{billing_account}".format( 

263 billing_account=billing_account, 

264 ) 

265 

266 @staticmethod 

267 def parse_common_billing_account_path(path: str) -> Dict[str, str]: 

268 """Parse a billing_account path into its component segments.""" 

269 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) 

270 return m.groupdict() if m else {} 

271 

272 @staticmethod 

273 def common_folder_path( 

274 folder: str, 

275 ) -> str: 

276 """Returns a fully-qualified folder string.""" 

277 return "folders/{folder}".format( 

278 folder=folder, 

279 ) 

280 

281 @staticmethod 

282 def parse_common_folder_path(path: str) -> Dict[str, str]: 

283 """Parse a folder path into its component segments.""" 

284 m = re.match(r"^folders/(?P<folder>.+?)$", path) 

285 return m.groupdict() if m else {} 

286 

287 @staticmethod 

288 def common_organization_path( 

289 organization: str, 

290 ) -> str: 

291 """Returns a fully-qualified organization string.""" 

292 return "organizations/{organization}".format( 

293 organization=organization, 

294 ) 

295 

296 @staticmethod 

297 def parse_common_organization_path(path: str) -> Dict[str, str]: 

298 """Parse a organization path into its component segments.""" 

299 m = re.match(r"^organizations/(?P<organization>.+?)$", path) 

300 return m.groupdict() if m else {} 

301 

302 @staticmethod 

303 def common_project_path( 

304 project: str, 

305 ) -> str: 

306 """Returns a fully-qualified project string.""" 

307 return "projects/{project}".format( 

308 project=project, 

309 ) 

310 

311 @staticmethod 

312 def parse_common_project_path(path: str) -> Dict[str, str]: 

313 """Parse a project path into its component segments.""" 

314 m = re.match(r"^projects/(?P<project>.+?)$", path) 

315 return m.groupdict() if m else {} 

316 

317 @staticmethod 

318 def common_location_path( 

319 project: str, 

320 location: str, 

321 ) -> str: 

322 """Returns a fully-qualified location string.""" 

323 return "projects/{project}/locations/{location}".format( 

324 project=project, 

325 location=location, 

326 ) 

327 

328 @staticmethod 

329 def parse_common_location_path(path: str) -> Dict[str, str]: 

330 """Parse a location path into its component segments.""" 

331 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) 

332 return m.groupdict() if m else {} 

333 

334 @classmethod 

335 def get_mtls_endpoint_and_cert_source( 

336 cls, client_options: Optional[client_options_lib.ClientOptions] = None 

337 ): 

338 """Deprecated. Return the API endpoint and client cert source for mutual TLS. 

339 

340 The client cert source is determined in the following order: 

341 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the 

342 client cert source is None. 

343 (2) if `client_options.client_cert_source` is provided, use the provided one; if the 

344 default client cert source exists, use the default one; otherwise the client cert 

345 source is None. 

346 

347 The API endpoint is determined in the following order: 

348 (1) if `client_options.api_endpoint` if provided, use the provided one. 

349 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the 

350 default mTLS endpoint; if the environment variable is "never", use the default API 

351 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise 

352 use the default API endpoint. 

353 

354 More details can be found at https://google.aip.dev/auth/4114. 

355 

356 Args: 

357 client_options (google.api_core.client_options.ClientOptions): Custom options for the 

358 client. Only the `api_endpoint` and `client_cert_source` properties may be used 

359 in this method. 

360 

361 Returns: 

362 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the 

363 client cert source to use. 

364 

365 Raises: 

366 google.auth.exceptions.MutualTLSChannelError: If any errors happen. 

367 """ 

368 

369 warnings.warn( 

370 "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", 

371 DeprecationWarning, 

372 ) 

373 if client_options is None: 

374 client_options = client_options_lib.ClientOptions() 

375 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") 

376 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") 

377 if use_client_cert not in ("true", "false"): 

378 raise ValueError( 

379 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" 

380 ) 

381 if use_mtls_endpoint not in ("auto", "never", "always"): 

382 raise MutualTLSChannelError( 

383 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" 

384 ) 

385 

386 # Figure out the client cert source to use. 

387 client_cert_source = None 

388 if use_client_cert == "true": 

389 if client_options.client_cert_source: 

390 client_cert_source = client_options.client_cert_source 

391 elif mtls.has_default_client_cert_source(): 

392 client_cert_source = mtls.default_client_cert_source() 

393 

394 # Figure out which api endpoint to use. 

395 if client_options.api_endpoint is not None: 

396 api_endpoint = client_options.api_endpoint 

397 elif use_mtls_endpoint == "always" or ( 

398 use_mtls_endpoint == "auto" and client_cert_source 

399 ): 

400 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

401 else: 

402 api_endpoint = cls.DEFAULT_ENDPOINT 

403 

404 return api_endpoint, client_cert_source 

405 

406 @staticmethod 

407 def _read_environment_variables(): 

408 """Returns the environment variables used by the client. 

409 

410 Returns: 

411 Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, 

412 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. 

413 

414 Raises: 

415 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not 

416 any of ["true", "false"]. 

417 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT 

418 is not any of ["auto", "never", "always"]. 

419 """ 

420 use_client_cert = os.getenv( 

421 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" 

422 ).lower() 

423 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() 

424 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") 

425 if use_client_cert not in ("true", "false"): 

426 raise ValueError( 

427 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" 

428 ) 

429 if use_mtls_endpoint not in ("auto", "never", "always"): 

430 raise MutualTLSChannelError( 

431 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" 

432 ) 

433 return use_client_cert == "true", use_mtls_endpoint, universe_domain_env 

434 

435 @staticmethod 

436 def _get_client_cert_source(provided_cert_source, use_cert_flag): 

437 """Return the client cert source to be used by the client. 

438 

439 Args: 

440 provided_cert_source (bytes): The client certificate source provided. 

441 use_cert_flag (bool): A flag indicating whether to use the client certificate. 

442 

443 Returns: 

444 bytes or None: The client cert source to be used by the client. 

445 """ 

446 client_cert_source = None 

447 if use_cert_flag: 

448 if provided_cert_source: 

449 client_cert_source = provided_cert_source 

450 elif mtls.has_default_client_cert_source(): 

451 client_cert_source = mtls.default_client_cert_source() 

452 return client_cert_source 

453 

454 @staticmethod 

455 def _get_api_endpoint( 

456 api_override, client_cert_source, universe_domain, use_mtls_endpoint 

457 ): 

458 """Return the API endpoint used by the client. 

459 

460 Args: 

461 api_override (str): The API endpoint override. If specified, this is always 

462 the return value of this function and the other arguments are not used. 

463 client_cert_source (bytes): The client certificate source used by the client. 

464 universe_domain (str): The universe domain used by the client. 

465 use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. 

466 Possible values are "always", "auto", or "never". 

467 

468 Returns: 

469 str: The API endpoint to be used by the client. 

470 """ 

471 if api_override is not None: 

472 api_endpoint = api_override 

473 elif use_mtls_endpoint == "always" or ( 

474 use_mtls_endpoint == "auto" and client_cert_source 

475 ): 

476 _default_universe = CloudTasksClient._DEFAULT_UNIVERSE 

477 if universe_domain != _default_universe: 

478 raise MutualTLSChannelError( 

479 f"mTLS is not supported in any universe other than {_default_universe}." 

480 ) 

481 api_endpoint = CloudTasksClient.DEFAULT_MTLS_ENDPOINT 

482 else: 

483 api_endpoint = CloudTasksClient._DEFAULT_ENDPOINT_TEMPLATE.format( 

484 UNIVERSE_DOMAIN=universe_domain 

485 ) 

486 return api_endpoint 

487 

488 @staticmethod 

489 def _get_universe_domain( 

490 client_universe_domain: Optional[str], universe_domain_env: Optional[str] 

491 ) -> str: 

492 """Return the universe domain used by the client. 

493 

494 Args: 

495 client_universe_domain (Optional[str]): The universe domain configured via the client options. 

496 universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. 

497 

498 Returns: 

499 str: The universe domain to be used by the client. 

500 

501 Raises: 

502 ValueError: If the universe domain is an empty string. 

503 """ 

504 universe_domain = CloudTasksClient._DEFAULT_UNIVERSE 

505 if client_universe_domain is not None: 

506 universe_domain = client_universe_domain 

507 elif universe_domain_env is not None: 

508 universe_domain = universe_domain_env 

509 if len(universe_domain.strip()) == 0: 

510 raise ValueError("Universe Domain cannot be an empty string.") 

511 return universe_domain 

512 

513 def _validate_universe_domain(self): 

514 """Validates client's and credentials' universe domains are consistent. 

515 

516 Returns: 

517 bool: True iff the configured universe domain is valid. 

518 

519 Raises: 

520 ValueError: If the configured universe domain is not valid. 

521 """ 

522 

523 # NOTE (b/349488459): universe validation is disabled until further notice. 

524 return True 

525 

526 def _add_cred_info_for_auth_errors( 

527 self, error: core_exceptions.GoogleAPICallError 

528 ) -> None: 

529 """Adds credential info string to error details for 401/403/404 errors. 

530 

531 Args: 

532 error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. 

533 """ 

534 if error.code not in [ 

535 HTTPStatus.UNAUTHORIZED, 

536 HTTPStatus.FORBIDDEN, 

537 HTTPStatus.NOT_FOUND, 

538 ]: 

539 return 

540 

541 cred = self._transport._credentials 

542 

543 # get_cred_info is only available in google-auth>=2.35.0 

544 if not hasattr(cred, "get_cred_info"): 

545 return 

546 

547 # ignore the type check since pypy test fails when get_cred_info 

548 # is not available 

549 cred_info = cred.get_cred_info() # type: ignore 

550 if cred_info and hasattr(error._details, "append"): 

551 error._details.append(json.dumps(cred_info)) 

552 

553 @property 

554 def api_endpoint(self): 

555 """Return the API endpoint used by the client instance. 

556 

557 Returns: 

558 str: The API endpoint used by the client instance. 

559 """ 

560 return self._api_endpoint 

561 

562 @property 

563 def universe_domain(self) -> str: 

564 """Return the universe domain used by the client instance. 

565 

566 Returns: 

567 str: The universe domain used by the client instance. 

568 """ 

569 return self._universe_domain 

570 

571 def __init__( 

572 self, 

573 *, 

574 credentials: Optional[ga_credentials.Credentials] = None, 

575 transport: Optional[ 

576 Union[str, CloudTasksTransport, Callable[..., CloudTasksTransport]] 

577 ] = None, 

578 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, 

579 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

580 ) -> None: 

581 """Instantiates the cloud tasks client. 

582 

583 Args: 

584 credentials (Optional[google.auth.credentials.Credentials]): The 

585 authorization credentials to attach to requests. These 

586 credentials identify the application to the service; if none 

587 are specified, the client will attempt to ascertain the 

588 credentials from the environment. 

589 transport (Optional[Union[str,CloudTasksTransport,Callable[..., CloudTasksTransport]]]): 

590 The transport to use, or a Callable that constructs and returns a new transport. 

591 If a Callable is given, it will be called with the same set of initialization 

592 arguments as used in the CloudTasksTransport constructor. 

593 If set to None, a transport is chosen automatically. 

594 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 

595 Custom options for the client. 

596 

597 1. The ``api_endpoint`` property can be used to override the 

598 default endpoint provided by the client when ``transport`` is 

599 not explicitly provided. Only if this property is not set and 

600 ``transport`` was not explicitly provided, the endpoint is 

601 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

602 variable, which have one of the following values: 

603 "always" (always use the default mTLS endpoint), "never" (always 

604 use the default regular endpoint) and "auto" (auto-switch to the 

605 default mTLS endpoint if client certificate is present; this is 

606 the default value). 

607 

608 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

609 is "true", then the ``client_cert_source`` property can be used 

610 to provide a client certificate for mTLS transport. If 

611 not provided, the default SSL client certificate will be used if 

612 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

613 set, no client certificate will be used. 

614 

615 3. The ``universe_domain`` property can be used to override the 

616 default "googleapis.com" universe. Note that the ``api_endpoint`` 

617 property still takes precedence; and ``universe_domain`` is 

618 currently not supported for mTLS. 

619 

620 client_info (google.api_core.gapic_v1.client_info.ClientInfo): 

621 The client info used to send a user-agent string along with 

622 API requests. If ``None``, then default info will be used. 

623 Generally, you only need to set this if you're developing 

624 your own client library. 

625 

626 Raises: 

627 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport 

628 creation failed for any reason. 

629 """ 

630 self._client_options = client_options 

631 if isinstance(self._client_options, dict): 

632 self._client_options = client_options_lib.from_dict(self._client_options) 

633 if self._client_options is None: 

634 self._client_options = client_options_lib.ClientOptions() 

635 self._client_options = cast( 

636 client_options_lib.ClientOptions, self._client_options 

637 ) 

638 

639 universe_domain_opt = getattr(self._client_options, "universe_domain", None) 

640 

641 ( 

642 self._use_client_cert, 

643 self._use_mtls_endpoint, 

644 self._universe_domain_env, 

645 ) = CloudTasksClient._read_environment_variables() 

646 self._client_cert_source = CloudTasksClient._get_client_cert_source( 

647 self._client_options.client_cert_source, self._use_client_cert 

648 ) 

649 self._universe_domain = CloudTasksClient._get_universe_domain( 

650 universe_domain_opt, self._universe_domain_env 

651 ) 

652 self._api_endpoint = None # updated below, depending on `transport` 

653 

654 # Initialize the universe domain validation. 

655 self._is_universe_domain_valid = False 

656 

657 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER 

658 # Setup logging. 

659 client_logging.initialize_logging() 

660 

661 api_key_value = getattr(self._client_options, "api_key", None) 

662 if api_key_value and credentials: 

663 raise ValueError( 

664 "client_options.api_key and credentials are mutually exclusive" 

665 ) 

666 

667 # Save or instantiate the transport. 

668 # Ordinarily, we provide the transport, but allowing a custom transport 

669 # instance provides an extensibility point for unusual situations. 

670 transport_provided = isinstance(transport, CloudTasksTransport) 

671 if transport_provided: 

672 # transport is a CloudTasksTransport instance. 

673 if credentials or self._client_options.credentials_file or api_key_value: 

674 raise ValueError( 

675 "When providing a transport instance, " 

676 "provide its credentials directly." 

677 ) 

678 if self._client_options.scopes: 

679 raise ValueError( 

680 "When providing a transport instance, provide its scopes " 

681 "directly." 

682 ) 

683 self._transport = cast(CloudTasksTransport, transport) 

684 self._api_endpoint = self._transport.host 

685 

686 self._api_endpoint = self._api_endpoint or CloudTasksClient._get_api_endpoint( 

687 self._client_options.api_endpoint, 

688 self._client_cert_source, 

689 self._universe_domain, 

690 self._use_mtls_endpoint, 

691 ) 

692 

693 if not transport_provided: 

694 import google.auth._default # type: ignore 

695 

696 if api_key_value and hasattr( 

697 google.auth._default, "get_api_key_credentials" 

698 ): 

699 credentials = google.auth._default.get_api_key_credentials( 

700 api_key_value 

701 ) 

702 

703 transport_init: Union[ 

704 Type[CloudTasksTransport], Callable[..., CloudTasksTransport] 

705 ] = ( 

706 CloudTasksClient.get_transport_class(transport) 

707 if isinstance(transport, str) or transport is None 

708 else cast(Callable[..., CloudTasksTransport], transport) 

709 ) 

710 # initialize with the provided callable or the passed in class 

711 self._transport = transport_init( 

712 credentials=credentials, 

713 credentials_file=self._client_options.credentials_file, 

714 host=self._api_endpoint, 

715 scopes=self._client_options.scopes, 

716 client_cert_source_for_mtls=self._client_cert_source, 

717 quota_project_id=self._client_options.quota_project_id, 

718 client_info=client_info, 

719 always_use_jwt_access=True, 

720 api_audience=self._client_options.api_audience, 

721 ) 

722 

723 if "async" not in str(self._transport): 

724 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

725 std_logging.DEBUG 

726 ): # pragma: NO COVER 

727 _LOGGER.debug( 

728 "Created client `google.cloud.tasks_v2.CloudTasksClient`.", 

729 extra={ 

730 "serviceName": "google.cloud.tasks.v2.CloudTasks", 

731 "universeDomain": getattr( 

732 self._transport._credentials, "universe_domain", "" 

733 ), 

734 "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", 

735 "credentialsInfo": getattr( 

736 self.transport._credentials, "get_cred_info", lambda: None 

737 )(), 

738 } 

739 if hasattr(self._transport, "_credentials") 

740 else { 

741 "serviceName": "google.cloud.tasks.v2.CloudTasks", 

742 "credentialsType": None, 

743 }, 

744 ) 

745 

746 def list_queues( 

747 self, 

748 request: Optional[Union[cloudtasks.ListQueuesRequest, dict]] = None, 

749 *, 

750 parent: Optional[str] = None, 

751 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

752 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

753 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

754 ) -> pagers.ListQueuesPager: 

755 r"""Lists queues. 

756 

757 Queues are returned in lexicographical order. 

758 

759 .. code-block:: python 

760 

761 # This snippet has been automatically generated and should be regarded as a 

762 # code template only. 

763 # It will require modifications to work: 

764 # - It may require correct/in-range values for request initialization. 

765 # - It may require specifying regional endpoints when creating the service 

766 # client as shown in: 

767 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

768 from google.cloud import tasks_v2 

769 

770 def sample_list_queues(): 

771 # Create a client 

772 client = tasks_v2.CloudTasksClient() 

773 

774 # Initialize request argument(s) 

775 request = tasks_v2.ListQueuesRequest( 

776 parent="parent_value", 

777 ) 

778 

779 # Make the request 

780 page_result = client.list_queues(request=request) 

781 

782 # Handle the response 

783 for response in page_result: 

784 print(response) 

785 

786 Args: 

787 request (Union[google.cloud.tasks_v2.types.ListQueuesRequest, dict]): 

788 The request object. Request message for 

789 [ListQueues][google.cloud.tasks.v2.CloudTasks.ListQueues]. 

790 parent (str): 

791 Required. The location name. For example: 

792 ``projects/PROJECT_ID/locations/LOCATION_ID`` 

793 

794 This corresponds to the ``parent`` 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, Union[str, bytes]]]): Key/value pairs which should be 

801 sent along with the request as metadata. Normally, each value must be of type `str`, 

802 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

803 be of type `bytes`. 

804 

805 Returns: 

806 google.cloud.tasks_v2.services.cloud_tasks.pagers.ListQueuesPager: 

807 Response message for 

808 [ListQueues][google.cloud.tasks.v2.CloudTasks.ListQueues]. 

809 

810 Iterating over this object will yield results and 

811 resolve additional pages automatically. 

812 

813 """ 

814 # Create or coerce a protobuf request object. 

815 # - Quick check: If we got a request object, we should *not* have 

816 # gotten any keyword arguments that map to the request. 

817 flattened_params = [parent] 

818 has_flattened_params = ( 

819 len([param for param in flattened_params if param is not None]) > 0 

820 ) 

821 if request is not None and has_flattened_params: 

822 raise ValueError( 

823 "If the `request` argument is set, then none of " 

824 "the individual field arguments should be set." 

825 ) 

826 

827 # - Use the request object if provided (there's no risk of modifying the input as 

828 # there are no flattened fields), or create one. 

829 if not isinstance(request, cloudtasks.ListQueuesRequest): 

830 request = cloudtasks.ListQueuesRequest(request) 

831 # If we have keyword arguments corresponding to fields on the 

832 # request, apply these. 

833 if parent is not None: 

834 request.parent = parent 

835 

836 # Wrap the RPC method; this adds retry and timeout information, 

837 # and friendly error handling. 

838 rpc = self._transport._wrapped_methods[self._transport.list_queues] 

839 

840 # Certain fields should be provided within the metadata header; 

841 # add these here. 

842 metadata = tuple(metadata) + ( 

843 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), 

844 ) 

845 

846 # Validate the universe domain. 

847 self._validate_universe_domain() 

848 

849 # Send the request. 

850 response = rpc( 

851 request, 

852 retry=retry, 

853 timeout=timeout, 

854 metadata=metadata, 

855 ) 

856 

857 # This method is paged; wrap the response in a pager, which provides 

858 # an `__iter__` convenience method. 

859 response = pagers.ListQueuesPager( 

860 method=rpc, 

861 request=request, 

862 response=response, 

863 retry=retry, 

864 timeout=timeout, 

865 metadata=metadata, 

866 ) 

867 

868 # Done; return the response. 

869 return response 

870 

871 def get_queue( 

872 self, 

873 request: Optional[Union[cloudtasks.GetQueueRequest, dict]] = None, 

874 *, 

875 name: Optional[str] = None, 

876 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

877 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

878 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

879 ) -> queue.Queue: 

880 r"""Gets a queue. 

881 

882 .. code-block:: python 

883 

884 # This snippet has been automatically generated and should be regarded as a 

885 # code template only. 

886 # It will require modifications to work: 

887 # - It may require correct/in-range values for request initialization. 

888 # - It may require specifying regional endpoints when creating the service 

889 # client as shown in: 

890 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

891 from google.cloud import tasks_v2 

892 

893 def sample_get_queue(): 

894 # Create a client 

895 client = tasks_v2.CloudTasksClient() 

896 

897 # Initialize request argument(s) 

898 request = tasks_v2.GetQueueRequest( 

899 name="name_value", 

900 ) 

901 

902 # Make the request 

903 response = client.get_queue(request=request) 

904 

905 # Handle the response 

906 print(response) 

907 

908 Args: 

909 request (Union[google.cloud.tasks_v2.types.GetQueueRequest, dict]): 

910 The request object. Request message for 

911 [GetQueue][google.cloud.tasks.v2.CloudTasks.GetQueue]. 

912 name (str): 

913 Required. The resource name of the queue. For example: 

914 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`` 

915 

916 This corresponds to the ``name`` field 

917 on the ``request`` instance; if ``request`` is provided, this 

918 should not be set. 

919 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

920 should be retried. 

921 timeout (float): The timeout for this request. 

922 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

923 sent along with the request as metadata. Normally, each value must be of type `str`, 

924 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

925 be of type `bytes`. 

926 

927 Returns: 

928 google.cloud.tasks_v2.types.Queue: 

929 A queue is a container of related 

930 tasks. Queues are configured to manage 

931 how those tasks are dispatched. 

932 Configurable properties include rate 

933 limits, retry options, queue types, and 

934 others. 

935 

936 """ 

937 # Create or coerce a protobuf request object. 

938 # - Quick check: If we got a request object, we should *not* have 

939 # gotten any keyword arguments that map to the request. 

940 flattened_params = [name] 

941 has_flattened_params = ( 

942 len([param for param in flattened_params if param is not None]) > 0 

943 ) 

944 if request is not None and has_flattened_params: 

945 raise ValueError( 

946 "If the `request` argument is set, then none of " 

947 "the individual field arguments should be set." 

948 ) 

949 

950 # - Use the request object if provided (there's no risk of modifying the input as 

951 # there are no flattened fields), or create one. 

952 if not isinstance(request, cloudtasks.GetQueueRequest): 

953 request = cloudtasks.GetQueueRequest(request) 

954 # If we have keyword arguments corresponding to fields on the 

955 # request, apply these. 

956 if name is not None: 

957 request.name = name 

958 

959 # Wrap the RPC method; this adds retry and timeout information, 

960 # and friendly error handling. 

961 rpc = self._transport._wrapped_methods[self._transport.get_queue] 

962 

963 # Certain fields should be provided within the metadata header; 

964 # add these here. 

965 metadata = tuple(metadata) + ( 

966 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

967 ) 

968 

969 # Validate the universe domain. 

970 self._validate_universe_domain() 

971 

972 # Send the request. 

973 response = rpc( 

974 request, 

975 retry=retry, 

976 timeout=timeout, 

977 metadata=metadata, 

978 ) 

979 

980 # Done; return the response. 

981 return response 

982 

983 def create_queue( 

984 self, 

985 request: Optional[Union[cloudtasks.CreateQueueRequest, dict]] = None, 

986 *, 

987 parent: Optional[str] = None, 

988 queue: Optional[gct_queue.Queue] = None, 

989 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

990 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

991 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

992 ) -> gct_queue.Queue: 

993 r"""Creates a queue. 

994 

995 Queues created with this method allow tasks to live for a 

996 maximum of 31 days. After a task is 31 days old, the task will 

997 be deleted regardless of whether it was dispatched or not. 

998 

999 WARNING: Using this method may have unintended side effects if 

1000 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file 

1001 to manage your queues. Read `Overview of Queue Management and 

1002 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__ 

1003 before using this method. 

1004 

1005 .. code-block:: python 

1006 

1007 # This snippet has been automatically generated and should be regarded as a 

1008 # code template only. 

1009 # It will require modifications to work: 

1010 # - It may require correct/in-range values for request initialization. 

1011 # - It may require specifying regional endpoints when creating the service 

1012 # client as shown in: 

1013 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1014 from google.cloud import tasks_v2 

1015 

1016 def sample_create_queue(): 

1017 # Create a client 

1018 client = tasks_v2.CloudTasksClient() 

1019 

1020 # Initialize request argument(s) 

1021 request = tasks_v2.CreateQueueRequest( 

1022 parent="parent_value", 

1023 ) 

1024 

1025 # Make the request 

1026 response = client.create_queue(request=request) 

1027 

1028 # Handle the response 

1029 print(response) 

1030 

1031 Args: 

1032 request (Union[google.cloud.tasks_v2.types.CreateQueueRequest, dict]): 

1033 The request object. Request message for 

1034 [CreateQueue][google.cloud.tasks.v2.CloudTasks.CreateQueue]. 

1035 parent (str): 

1036 Required. The location name in which the queue will be 

1037 created. For example: 

1038 ``projects/PROJECT_ID/locations/LOCATION_ID`` 

1039 

1040 The list of allowed locations can be obtained by calling 

1041 Cloud Tasks' implementation of 

1042 [ListLocations][google.cloud.location.Locations.ListLocations]. 

1043 

1044 This corresponds to the ``parent`` field 

1045 on the ``request`` instance; if ``request`` is provided, this 

1046 should not be set. 

1047 queue (google.cloud.tasks_v2.types.Queue): 

1048 Required. The queue to create. 

1049 

1050 [Queue's name][google.cloud.tasks.v2.Queue.name] cannot 

1051 be the same as an existing queue. 

1052 

1053 This corresponds to the ``queue`` field 

1054 on the ``request`` instance; if ``request`` is provided, this 

1055 should not be set. 

1056 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1057 should be retried. 

1058 timeout (float): The timeout for this request. 

1059 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1060 sent along with the request as metadata. Normally, each value must be of type `str`, 

1061 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1062 be of type `bytes`. 

1063 

1064 Returns: 

1065 google.cloud.tasks_v2.types.Queue: 

1066 A queue is a container of related 

1067 tasks. Queues are configured to manage 

1068 how those tasks are dispatched. 

1069 Configurable properties include rate 

1070 limits, retry options, queue types, and 

1071 others. 

1072 

1073 """ 

1074 # Create or coerce a protobuf request object. 

1075 # - Quick check: If we got a request object, we should *not* have 

1076 # gotten any keyword arguments that map to the request. 

1077 flattened_params = [parent, queue] 

1078 has_flattened_params = ( 

1079 len([param for param in flattened_params if param is not None]) > 0 

1080 ) 

1081 if request is not None and has_flattened_params: 

1082 raise ValueError( 

1083 "If the `request` argument is set, then none of " 

1084 "the individual field arguments should be set." 

1085 ) 

1086 

1087 # - Use the request object if provided (there's no risk of modifying the input as 

1088 # there are no flattened fields), or create one. 

1089 if not isinstance(request, cloudtasks.CreateQueueRequest): 

1090 request = cloudtasks.CreateQueueRequest(request) 

1091 # If we have keyword arguments corresponding to fields on the 

1092 # request, apply these. 

1093 if parent is not None: 

1094 request.parent = parent 

1095 if queue is not None: 

1096 request.queue = queue 

1097 

1098 # Wrap the RPC method; this adds retry and timeout information, 

1099 # and friendly error handling. 

1100 rpc = self._transport._wrapped_methods[self._transport.create_queue] 

1101 

1102 # Certain fields should be provided within the metadata header; 

1103 # add these here. 

1104 metadata = tuple(metadata) + ( 

1105 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), 

1106 ) 

1107 

1108 # Validate the universe domain. 

1109 self._validate_universe_domain() 

1110 

1111 # Send the request. 

1112 response = rpc( 

1113 request, 

1114 retry=retry, 

1115 timeout=timeout, 

1116 metadata=metadata, 

1117 ) 

1118 

1119 # Done; return the response. 

1120 return response 

1121 

1122 def update_queue( 

1123 self, 

1124 request: Optional[Union[cloudtasks.UpdateQueueRequest, dict]] = None, 

1125 *, 

1126 queue: Optional[gct_queue.Queue] = None, 

1127 update_mask: Optional[field_mask_pb2.FieldMask] = None, 

1128 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1129 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1130 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1131 ) -> gct_queue.Queue: 

1132 r"""Updates a queue. 

1133 

1134 This method creates the queue if it does not exist and updates 

1135 the queue if it does exist. 

1136 

1137 Queues created with this method allow tasks to live for a 

1138 maximum of 31 days. After a task is 31 days old, the task will 

1139 be deleted regardless of whether it was dispatched or not. 

1140 

1141 WARNING: Using this method may have unintended side effects if 

1142 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file 

1143 to manage your queues. Read `Overview of Queue Management and 

1144 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__ 

1145 before using this method. 

1146 

1147 .. code-block:: python 

1148 

1149 # This snippet has been automatically generated and should be regarded as a 

1150 # code template only. 

1151 # It will require modifications to work: 

1152 # - It may require correct/in-range values for request initialization. 

1153 # - It may require specifying regional endpoints when creating the service 

1154 # client as shown in: 

1155 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1156 from google.cloud import tasks_v2 

1157 

1158 def sample_update_queue(): 

1159 # Create a client 

1160 client = tasks_v2.CloudTasksClient() 

1161 

1162 # Initialize request argument(s) 

1163 request = tasks_v2.UpdateQueueRequest( 

1164 ) 

1165 

1166 # Make the request 

1167 response = client.update_queue(request=request) 

1168 

1169 # Handle the response 

1170 print(response) 

1171 

1172 Args: 

1173 request (Union[google.cloud.tasks_v2.types.UpdateQueueRequest, dict]): 

1174 The request object. Request message for 

1175 [UpdateQueue][google.cloud.tasks.v2.CloudTasks.UpdateQueue]. 

1176 queue (google.cloud.tasks_v2.types.Queue): 

1177 Required. The queue to create or update. 

1178 

1179 The queue's [name][google.cloud.tasks.v2.Queue.name] 

1180 must be specified. 

1181 

1182 Output only fields cannot be modified using UpdateQueue. 

1183 Any value specified for an output only field will be 

1184 ignored. The queue's 

1185 [name][google.cloud.tasks.v2.Queue.name] cannot be 

1186 changed. 

1187 

1188 This corresponds to the ``queue`` field 

1189 on the ``request`` instance; if ``request`` is provided, this 

1190 should not be set. 

1191 update_mask (google.protobuf.field_mask_pb2.FieldMask): 

1192 A mask used to specify which fields 

1193 of the queue are being updated. 

1194 If empty, then all fields will be 

1195 updated. 

1196 

1197 This corresponds to the ``update_mask`` field 

1198 on the ``request`` instance; if ``request`` is provided, this 

1199 should not be set. 

1200 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1201 should be retried. 

1202 timeout (float): The timeout for this request. 

1203 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1204 sent along with the request as metadata. Normally, each value must be of type `str`, 

1205 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1206 be of type `bytes`. 

1207 

1208 Returns: 

1209 google.cloud.tasks_v2.types.Queue: 

1210 A queue is a container of related 

1211 tasks. Queues are configured to manage 

1212 how those tasks are dispatched. 

1213 Configurable properties include rate 

1214 limits, retry options, queue types, and 

1215 others. 

1216 

1217 """ 

1218 # Create or coerce a protobuf request object. 

1219 # - Quick check: If we got a request object, we should *not* have 

1220 # gotten any keyword arguments that map to the request. 

1221 flattened_params = [queue, update_mask] 

1222 has_flattened_params = ( 

1223 len([param for param in flattened_params if param is not None]) > 0 

1224 ) 

1225 if request is not None and has_flattened_params: 

1226 raise ValueError( 

1227 "If the `request` argument is set, then none of " 

1228 "the individual field arguments should be set." 

1229 ) 

1230 

1231 # - Use the request object if provided (there's no risk of modifying the input as 

1232 # there are no flattened fields), or create one. 

1233 if not isinstance(request, cloudtasks.UpdateQueueRequest): 

1234 request = cloudtasks.UpdateQueueRequest(request) 

1235 # If we have keyword arguments corresponding to fields on the 

1236 # request, apply these. 

1237 if queue is not None: 

1238 request.queue = queue 

1239 if update_mask is not None: 

1240 request.update_mask = update_mask 

1241 

1242 # Wrap the RPC method; this adds retry and timeout information, 

1243 # and friendly error handling. 

1244 rpc = self._transport._wrapped_methods[self._transport.update_queue] 

1245 

1246 # Certain fields should be provided within the metadata header; 

1247 # add these here. 

1248 metadata = tuple(metadata) + ( 

1249 gapic_v1.routing_header.to_grpc_metadata( 

1250 (("queue.name", request.queue.name),) 

1251 ), 

1252 ) 

1253 

1254 # Validate the universe domain. 

1255 self._validate_universe_domain() 

1256 

1257 # Send the request. 

1258 response = rpc( 

1259 request, 

1260 retry=retry, 

1261 timeout=timeout, 

1262 metadata=metadata, 

1263 ) 

1264 

1265 # Done; return the response. 

1266 return response 

1267 

1268 def delete_queue( 

1269 self, 

1270 request: Optional[Union[cloudtasks.DeleteQueueRequest, dict]] = None, 

1271 *, 

1272 name: Optional[str] = None, 

1273 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1274 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1275 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1276 ) -> None: 

1277 r"""Deletes a queue. 

1278 

1279 This command will delete the queue even if it has tasks in it. 

1280 

1281 Note: If you delete a queue, a queue with the same name can't be 

1282 created for 7 days. 

1283 

1284 WARNING: Using this method may have unintended side effects if 

1285 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file 

1286 to manage your queues. Read `Overview of Queue Management and 

1287 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__ 

1288 before using this method. 

1289 

1290 .. code-block:: python 

1291 

1292 # This snippet has been automatically generated and should be regarded as a 

1293 # code template only. 

1294 # It will require modifications to work: 

1295 # - It may require correct/in-range values for request initialization. 

1296 # - It may require specifying regional endpoints when creating the service 

1297 # client as shown in: 

1298 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1299 from google.cloud import tasks_v2 

1300 

1301 def sample_delete_queue(): 

1302 # Create a client 

1303 client = tasks_v2.CloudTasksClient() 

1304 

1305 # Initialize request argument(s) 

1306 request = tasks_v2.DeleteQueueRequest( 

1307 name="name_value", 

1308 ) 

1309 

1310 # Make the request 

1311 client.delete_queue(request=request) 

1312 

1313 Args: 

1314 request (Union[google.cloud.tasks_v2.types.DeleteQueueRequest, dict]): 

1315 The request object. Request message for 

1316 [DeleteQueue][google.cloud.tasks.v2.CloudTasks.DeleteQueue]. 

1317 name (str): 

1318 Required. The queue name. For example: 

1319 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`` 

1320 

1321 This corresponds to the ``name`` field 

1322 on the ``request`` instance; if ``request`` is provided, this 

1323 should not be set. 

1324 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1325 should be retried. 

1326 timeout (float): The timeout for this request. 

1327 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1328 sent along with the request as metadata. Normally, each value must be of type `str`, 

1329 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1330 be of type `bytes`. 

1331 """ 

1332 # Create or coerce a protobuf request object. 

1333 # - Quick check: If we got a request object, we should *not* have 

1334 # gotten any keyword arguments that map to the request. 

1335 flattened_params = [name] 

1336 has_flattened_params = ( 

1337 len([param for param in flattened_params if param is not None]) > 0 

1338 ) 

1339 if request is not None and has_flattened_params: 

1340 raise ValueError( 

1341 "If the `request` argument is set, then none of " 

1342 "the individual field arguments should be set." 

1343 ) 

1344 

1345 # - Use the request object if provided (there's no risk of modifying the input as 

1346 # there are no flattened fields), or create one. 

1347 if not isinstance(request, cloudtasks.DeleteQueueRequest): 

1348 request = cloudtasks.DeleteQueueRequest(request) 

1349 # If we have keyword arguments corresponding to fields on the 

1350 # request, apply these. 

1351 if name is not None: 

1352 request.name = name 

1353 

1354 # Wrap the RPC method; this adds retry and timeout information, 

1355 # and friendly error handling. 

1356 rpc = self._transport._wrapped_methods[self._transport.delete_queue] 

1357 

1358 # Certain fields should be provided within the metadata header; 

1359 # add these here. 

1360 metadata = tuple(metadata) + ( 

1361 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

1362 ) 

1363 

1364 # Validate the universe domain. 

1365 self._validate_universe_domain() 

1366 

1367 # Send the request. 

1368 rpc( 

1369 request, 

1370 retry=retry, 

1371 timeout=timeout, 

1372 metadata=metadata, 

1373 ) 

1374 

1375 def purge_queue( 

1376 self, 

1377 request: Optional[Union[cloudtasks.PurgeQueueRequest, dict]] = None, 

1378 *, 

1379 name: Optional[str] = None, 

1380 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1381 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1382 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1383 ) -> queue.Queue: 

1384 r"""Purges a queue by deleting all of its tasks. 

1385 

1386 All tasks created before this method is called are 

1387 permanently deleted. 

1388 

1389 Purge operations can take up to one minute to take 

1390 effect. Tasks might be dispatched before the purge takes 

1391 effect. A purge is irreversible. 

1392 

1393 .. code-block:: python 

1394 

1395 # This snippet has been automatically generated and should be regarded as a 

1396 # code template only. 

1397 # It will require modifications to work: 

1398 # - It may require correct/in-range values for request initialization. 

1399 # - It may require specifying regional endpoints when creating the service 

1400 # client as shown in: 

1401 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1402 from google.cloud import tasks_v2 

1403 

1404 def sample_purge_queue(): 

1405 # Create a client 

1406 client = tasks_v2.CloudTasksClient() 

1407 

1408 # Initialize request argument(s) 

1409 request = tasks_v2.PurgeQueueRequest( 

1410 name="name_value", 

1411 ) 

1412 

1413 # Make the request 

1414 response = client.purge_queue(request=request) 

1415 

1416 # Handle the response 

1417 print(response) 

1418 

1419 Args: 

1420 request (Union[google.cloud.tasks_v2.types.PurgeQueueRequest, dict]): 

1421 The request object. Request message for 

1422 [PurgeQueue][google.cloud.tasks.v2.CloudTasks.PurgeQueue]. 

1423 name (str): 

1424 Required. The queue name. For example: 

1425 ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` 

1426 

1427 This corresponds to the ``name`` field 

1428 on the ``request`` instance; if ``request`` is provided, this 

1429 should not be set. 

1430 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1431 should be retried. 

1432 timeout (float): The timeout for this request. 

1433 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1434 sent along with the request as metadata. Normally, each value must be of type `str`, 

1435 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1436 be of type `bytes`. 

1437 

1438 Returns: 

1439 google.cloud.tasks_v2.types.Queue: 

1440 A queue is a container of related 

1441 tasks. Queues are configured to manage 

1442 how those tasks are dispatched. 

1443 Configurable properties include rate 

1444 limits, retry options, queue types, and 

1445 others. 

1446 

1447 """ 

1448 # Create or coerce a protobuf request object. 

1449 # - Quick check: If we got a request object, we should *not* have 

1450 # gotten any keyword arguments that map to the request. 

1451 flattened_params = [name] 

1452 has_flattened_params = ( 

1453 len([param for param in flattened_params if param is not None]) > 0 

1454 ) 

1455 if request is not None and has_flattened_params: 

1456 raise ValueError( 

1457 "If the `request` argument is set, then none of " 

1458 "the individual field arguments should be set." 

1459 ) 

1460 

1461 # - Use the request object if provided (there's no risk of modifying the input as 

1462 # there are no flattened fields), or create one. 

1463 if not isinstance(request, cloudtasks.PurgeQueueRequest): 

1464 request = cloudtasks.PurgeQueueRequest(request) 

1465 # If we have keyword arguments corresponding to fields on the 

1466 # request, apply these. 

1467 if name is not None: 

1468 request.name = name 

1469 

1470 # Wrap the RPC method; this adds retry and timeout information, 

1471 # and friendly error handling. 

1472 rpc = self._transport._wrapped_methods[self._transport.purge_queue] 

1473 

1474 # Certain fields should be provided within the metadata header; 

1475 # add these here. 

1476 metadata = tuple(metadata) + ( 

1477 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

1478 ) 

1479 

1480 # Validate the universe domain. 

1481 self._validate_universe_domain() 

1482 

1483 # Send the request. 

1484 response = rpc( 

1485 request, 

1486 retry=retry, 

1487 timeout=timeout, 

1488 metadata=metadata, 

1489 ) 

1490 

1491 # Done; return the response. 

1492 return response 

1493 

1494 def pause_queue( 

1495 self, 

1496 request: Optional[Union[cloudtasks.PauseQueueRequest, dict]] = None, 

1497 *, 

1498 name: Optional[str] = None, 

1499 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1500 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1501 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1502 ) -> queue.Queue: 

1503 r"""Pauses the queue. 

1504 

1505 If a queue is paused then the system will stop dispatching tasks 

1506 until the queue is resumed via 

1507 [ResumeQueue][google.cloud.tasks.v2.CloudTasks.ResumeQueue]. 

1508 Tasks can still be added when the queue is paused. A queue is 

1509 paused if its [state][google.cloud.tasks.v2.Queue.state] is 

1510 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED]. 

1511 

1512 .. code-block:: python 

1513 

1514 # This snippet has been automatically generated and should be regarded as a 

1515 # code template only. 

1516 # It will require modifications to work: 

1517 # - It may require correct/in-range values for request initialization. 

1518 # - It may require specifying regional endpoints when creating the service 

1519 # client as shown in: 

1520 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1521 from google.cloud import tasks_v2 

1522 

1523 def sample_pause_queue(): 

1524 # Create a client 

1525 client = tasks_v2.CloudTasksClient() 

1526 

1527 # Initialize request argument(s) 

1528 request = tasks_v2.PauseQueueRequest( 

1529 name="name_value", 

1530 ) 

1531 

1532 # Make the request 

1533 response = client.pause_queue(request=request) 

1534 

1535 # Handle the response 

1536 print(response) 

1537 

1538 Args: 

1539 request (Union[google.cloud.tasks_v2.types.PauseQueueRequest, dict]): 

1540 The request object. Request message for 

1541 [PauseQueue][google.cloud.tasks.v2.CloudTasks.PauseQueue]. 

1542 name (str): 

1543 Required. The queue name. For example: 

1544 ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` 

1545 

1546 This corresponds to the ``name`` field 

1547 on the ``request`` instance; if ``request`` is provided, this 

1548 should not be set. 

1549 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1550 should be retried. 

1551 timeout (float): The timeout for this request. 

1552 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1553 sent along with the request as metadata. Normally, each value must be of type `str`, 

1554 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1555 be of type `bytes`. 

1556 

1557 Returns: 

1558 google.cloud.tasks_v2.types.Queue: 

1559 A queue is a container of related 

1560 tasks. Queues are configured to manage 

1561 how those tasks are dispatched. 

1562 Configurable properties include rate 

1563 limits, retry options, queue types, and 

1564 others. 

1565 

1566 """ 

1567 # Create or coerce a protobuf request object. 

1568 # - Quick check: If we got a request object, we should *not* have 

1569 # gotten any keyword arguments that map to the request. 

1570 flattened_params = [name] 

1571 has_flattened_params = ( 

1572 len([param for param in flattened_params if param is not None]) > 0 

1573 ) 

1574 if request is not None and has_flattened_params: 

1575 raise ValueError( 

1576 "If the `request` argument is set, then none of " 

1577 "the individual field arguments should be set." 

1578 ) 

1579 

1580 # - Use the request object if provided (there's no risk of modifying the input as 

1581 # there are no flattened fields), or create one. 

1582 if not isinstance(request, cloudtasks.PauseQueueRequest): 

1583 request = cloudtasks.PauseQueueRequest(request) 

1584 # If we have keyword arguments corresponding to fields on the 

1585 # request, apply these. 

1586 if name is not None: 

1587 request.name = name 

1588 

1589 # Wrap the RPC method; this adds retry and timeout information, 

1590 # and friendly error handling. 

1591 rpc = self._transport._wrapped_methods[self._transport.pause_queue] 

1592 

1593 # Certain fields should be provided within the metadata header; 

1594 # add these here. 

1595 metadata = tuple(metadata) + ( 

1596 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

1597 ) 

1598 

1599 # Validate the universe domain. 

1600 self._validate_universe_domain() 

1601 

1602 # Send the request. 

1603 response = rpc( 

1604 request, 

1605 retry=retry, 

1606 timeout=timeout, 

1607 metadata=metadata, 

1608 ) 

1609 

1610 # Done; return the response. 

1611 return response 

1612 

1613 def resume_queue( 

1614 self, 

1615 request: Optional[Union[cloudtasks.ResumeQueueRequest, dict]] = None, 

1616 *, 

1617 name: Optional[str] = None, 

1618 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1619 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1620 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1621 ) -> queue.Queue: 

1622 r"""Resume a queue. 

1623 

1624 This method resumes a queue after it has been 

1625 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED] or 

1626 [DISABLED][google.cloud.tasks.v2.Queue.State.DISABLED]. The 

1627 state of a queue is stored in the queue's 

1628 [state][google.cloud.tasks.v2.Queue.state]; after calling this 

1629 method it will be set to 

1630 [RUNNING][google.cloud.tasks.v2.Queue.State.RUNNING]. 

1631 

1632 WARNING: Resuming many high-QPS queues at the same time can lead 

1633 to target overloading. If you are resuming high-QPS queues, 

1634 follow the 500/50/5 pattern described in `Managing Cloud Tasks 

1635 Scaling 

1636 Risks <https://cloud.google.com/tasks/docs/manage-cloud-task-scaling>`__. 

1637 

1638 .. code-block:: python 

1639 

1640 # This snippet has been automatically generated and should be regarded as a 

1641 # code template only. 

1642 # It will require modifications to work: 

1643 # - It may require correct/in-range values for request initialization. 

1644 # - It may require specifying regional endpoints when creating the service 

1645 # client as shown in: 

1646 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1647 from google.cloud import tasks_v2 

1648 

1649 def sample_resume_queue(): 

1650 # Create a client 

1651 client = tasks_v2.CloudTasksClient() 

1652 

1653 # Initialize request argument(s) 

1654 request = tasks_v2.ResumeQueueRequest( 

1655 name="name_value", 

1656 ) 

1657 

1658 # Make the request 

1659 response = client.resume_queue(request=request) 

1660 

1661 # Handle the response 

1662 print(response) 

1663 

1664 Args: 

1665 request (Union[google.cloud.tasks_v2.types.ResumeQueueRequest, dict]): 

1666 The request object. Request message for 

1667 [ResumeQueue][google.cloud.tasks.v2.CloudTasks.ResumeQueue]. 

1668 name (str): 

1669 Required. The queue name. For example: 

1670 ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` 

1671 

1672 This corresponds to the ``name`` field 

1673 on the ``request`` instance; if ``request`` is provided, this 

1674 should not be set. 

1675 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1676 should be retried. 

1677 timeout (float): The timeout for this request. 

1678 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1679 sent along with the request as metadata. Normally, each value must be of type `str`, 

1680 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1681 be of type `bytes`. 

1682 

1683 Returns: 

1684 google.cloud.tasks_v2.types.Queue: 

1685 A queue is a container of related 

1686 tasks. Queues are configured to manage 

1687 how those tasks are dispatched. 

1688 Configurable properties include rate 

1689 limits, retry options, queue types, and 

1690 others. 

1691 

1692 """ 

1693 # Create or coerce a protobuf request object. 

1694 # - Quick check: If we got a request object, we should *not* have 

1695 # gotten any keyword arguments that map to the request. 

1696 flattened_params = [name] 

1697 has_flattened_params = ( 

1698 len([param for param in flattened_params if param is not None]) > 0 

1699 ) 

1700 if request is not None and has_flattened_params: 

1701 raise ValueError( 

1702 "If the `request` argument is set, then none of " 

1703 "the individual field arguments should be set." 

1704 ) 

1705 

1706 # - Use the request object if provided (there's no risk of modifying the input as 

1707 # there are no flattened fields), or create one. 

1708 if not isinstance(request, cloudtasks.ResumeQueueRequest): 

1709 request = cloudtasks.ResumeQueueRequest(request) 

1710 # If we have keyword arguments corresponding to fields on the 

1711 # request, apply these. 

1712 if name is not None: 

1713 request.name = name 

1714 

1715 # Wrap the RPC method; this adds retry and timeout information, 

1716 # and friendly error handling. 

1717 rpc = self._transport._wrapped_methods[self._transport.resume_queue] 

1718 

1719 # Certain fields should be provided within the metadata header; 

1720 # add these here. 

1721 metadata = tuple(metadata) + ( 

1722 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

1723 ) 

1724 

1725 # Validate the universe domain. 

1726 self._validate_universe_domain() 

1727 

1728 # Send the request. 

1729 response = rpc( 

1730 request, 

1731 retry=retry, 

1732 timeout=timeout, 

1733 metadata=metadata, 

1734 ) 

1735 

1736 # Done; return the response. 

1737 return response 

1738 

1739 def get_iam_policy( 

1740 self, 

1741 request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, 

1742 *, 

1743 resource: Optional[str] = None, 

1744 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1745 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1746 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1747 ) -> policy_pb2.Policy: 

1748 r"""Gets the access control policy for a 

1749 [Queue][google.cloud.tasks.v2.Queue]. Returns an empty policy if 

1750 the resource exists and does not have a policy set. 

1751 

1752 Authorization requires the following `Google 

1753 IAM <https://cloud.google.com/iam>`__ permission on the 

1754 specified resource parent: 

1755 

1756 - ``cloudtasks.queues.getIamPolicy`` 

1757 

1758 .. code-block:: python 

1759 

1760 # This snippet has been automatically generated and should be regarded as a 

1761 # code template only. 

1762 # It will require modifications to work: 

1763 # - It may require correct/in-range values for request initialization. 

1764 # - It may require specifying regional endpoints when creating the service 

1765 # client as shown in: 

1766 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1767 from google.cloud import tasks_v2 

1768 from google.iam.v1 import iam_policy_pb2 # type: ignore 

1769 

1770 def sample_get_iam_policy(): 

1771 # Create a client 

1772 client = tasks_v2.CloudTasksClient() 

1773 

1774 # Initialize request argument(s) 

1775 request = iam_policy_pb2.GetIamPolicyRequest( 

1776 resource="resource_value", 

1777 ) 

1778 

1779 # Make the request 

1780 response = client.get_iam_policy(request=request) 

1781 

1782 # Handle the response 

1783 print(response) 

1784 

1785 Args: 

1786 request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): 

1787 The request object. Request message for ``GetIamPolicy`` method. 

1788 resource (str): 

1789 REQUIRED: The resource for which the 

1790 policy is being requested. See the 

1791 operation documentation for the 

1792 appropriate value for this field. 

1793 

1794 This corresponds to the ``resource`` field 

1795 on the ``request`` instance; if ``request`` is provided, this 

1796 should not be set. 

1797 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1798 should be retried. 

1799 timeout (float): The timeout for this request. 

1800 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1801 sent along with the request as metadata. Normally, each value must be of type `str`, 

1802 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1803 be of type `bytes`. 

1804 

1805 Returns: 

1806 google.iam.v1.policy_pb2.Policy: 

1807 An Identity and Access Management (IAM) policy, which specifies access 

1808 controls for Google Cloud resources. 

1809 

1810 A Policy is a collection of bindings. A binding binds 

1811 one or more members, or principals, to a single role. 

1812 Principals can be user accounts, service accounts, 

1813 Google groups, and domains (such as G Suite). A role 

1814 is a named list of permissions; each role can be an 

1815 IAM predefined role or a user-created custom role. 

1816 

1817 For some types of Google Cloud resources, a binding 

1818 can also specify a condition, which is a logical 

1819 expression that allows access to a resource only if 

1820 the expression evaluates to true. A condition can add 

1821 constraints based on attributes of the request, the 

1822 resource, or both. To learn which resources support 

1823 conditions in their IAM policies, see the [IAM 

1824 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). 

1825 

1826 **JSON example:** 

1827 

1828 :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` 

1829 

1830 **YAML example:** 

1831 

1832 :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` 

1833 

1834 For a description of IAM and its features, see the 

1835 [IAM 

1836 documentation](\ https://cloud.google.com/iam/docs/). 

1837 

1838 """ 

1839 # Create or coerce a protobuf request object. 

1840 # - Quick check: If we got a request object, we should *not* have 

1841 # gotten any keyword arguments that map to the request. 

1842 flattened_params = [resource] 

1843 has_flattened_params = ( 

1844 len([param for param in flattened_params if param is not None]) > 0 

1845 ) 

1846 if request is not None and has_flattened_params: 

1847 raise ValueError( 

1848 "If the `request` argument is set, then none of " 

1849 "the individual field arguments should be set." 

1850 ) 

1851 

1852 if isinstance(request, dict): 

1853 # - The request isn't a proto-plus wrapped type, 

1854 # so it must be constructed via keyword expansion. 

1855 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

1856 elif not request: 

1857 # Null request, just make one. 

1858 request = iam_policy_pb2.GetIamPolicyRequest() 

1859 if resource is not None: 

1860 request.resource = resource 

1861 

1862 # Wrap the RPC method; this adds retry and timeout information, 

1863 # and friendly error handling. 

1864 rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] 

1865 

1866 # Certain fields should be provided within the metadata header; 

1867 # add these here. 

1868 metadata = tuple(metadata) + ( 

1869 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

1870 ) 

1871 

1872 # Validate the universe domain. 

1873 self._validate_universe_domain() 

1874 

1875 # Send the request. 

1876 response = rpc( 

1877 request, 

1878 retry=retry, 

1879 timeout=timeout, 

1880 metadata=metadata, 

1881 ) 

1882 

1883 # Done; return the response. 

1884 return response 

1885 

1886 def set_iam_policy( 

1887 self, 

1888 request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, 

1889 *, 

1890 resource: Optional[str] = None, 

1891 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1892 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1893 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1894 ) -> policy_pb2.Policy: 

1895 r"""Sets the access control policy for a 

1896 [Queue][google.cloud.tasks.v2.Queue]. Replaces any existing 

1897 policy. 

1898 

1899 Note: The Cloud Console does not check queue-level IAM 

1900 permissions yet. Project-level permissions are required to use 

1901 the Cloud Console. 

1902 

1903 Authorization requires the following `Google 

1904 IAM <https://cloud.google.com/iam>`__ permission on the 

1905 specified resource parent: 

1906 

1907 - ``cloudtasks.queues.setIamPolicy`` 

1908 

1909 .. code-block:: python 

1910 

1911 # This snippet has been automatically generated and should be regarded as a 

1912 # code template only. 

1913 # It will require modifications to work: 

1914 # - It may require correct/in-range values for request initialization. 

1915 # - It may require specifying regional endpoints when creating the service 

1916 # client as shown in: 

1917 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1918 from google.cloud import tasks_v2 

1919 from google.iam.v1 import iam_policy_pb2 # type: ignore 

1920 

1921 def sample_set_iam_policy(): 

1922 # Create a client 

1923 client = tasks_v2.CloudTasksClient() 

1924 

1925 # Initialize request argument(s) 

1926 request = iam_policy_pb2.SetIamPolicyRequest( 

1927 resource="resource_value", 

1928 ) 

1929 

1930 # Make the request 

1931 response = client.set_iam_policy(request=request) 

1932 

1933 # Handle the response 

1934 print(response) 

1935 

1936 Args: 

1937 request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): 

1938 The request object. Request message for ``SetIamPolicy`` method. 

1939 resource (str): 

1940 REQUIRED: The resource for which the 

1941 policy is being specified. See the 

1942 operation documentation for the 

1943 appropriate value for this field. 

1944 

1945 This corresponds to the ``resource`` field 

1946 on the ``request`` instance; if ``request`` is provided, this 

1947 should not be set. 

1948 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1949 should be retried. 

1950 timeout (float): The timeout for this request. 

1951 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1952 sent along with the request as metadata. Normally, each value must be of type `str`, 

1953 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1954 be of type `bytes`. 

1955 

1956 Returns: 

1957 google.iam.v1.policy_pb2.Policy: 

1958 An Identity and Access Management (IAM) policy, which specifies access 

1959 controls for Google Cloud resources. 

1960 

1961 A Policy is a collection of bindings. A binding binds 

1962 one or more members, or principals, to a single role. 

1963 Principals can be user accounts, service accounts, 

1964 Google groups, and domains (such as G Suite). A role 

1965 is a named list of permissions; each role can be an 

1966 IAM predefined role or a user-created custom role. 

1967 

1968 For some types of Google Cloud resources, a binding 

1969 can also specify a condition, which is a logical 

1970 expression that allows access to a resource only if 

1971 the expression evaluates to true. A condition can add 

1972 constraints based on attributes of the request, the 

1973 resource, or both. To learn which resources support 

1974 conditions in their IAM policies, see the [IAM 

1975 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). 

1976 

1977 **JSON example:** 

1978 

1979 :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` 

1980 

1981 **YAML example:** 

1982 

1983 :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` 

1984 

1985 For a description of IAM and its features, see the 

1986 [IAM 

1987 documentation](\ https://cloud.google.com/iam/docs/). 

1988 

1989 """ 

1990 # Create or coerce a protobuf request object. 

1991 # - Quick check: If we got a request object, we should *not* have 

1992 # gotten any keyword arguments that map to the request. 

1993 flattened_params = [resource] 

1994 has_flattened_params = ( 

1995 len([param for param in flattened_params if param is not None]) > 0 

1996 ) 

1997 if request is not None and has_flattened_params: 

1998 raise ValueError( 

1999 "If the `request` argument is set, then none of " 

2000 "the individual field arguments should be set." 

2001 ) 

2002 

2003 if isinstance(request, dict): 

2004 # - The request isn't a proto-plus wrapped type, 

2005 # so it must be constructed via keyword expansion. 

2006 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

2007 elif not request: 

2008 # Null request, just make one. 

2009 request = iam_policy_pb2.SetIamPolicyRequest() 

2010 if resource is not None: 

2011 request.resource = resource 

2012 

2013 # Wrap the RPC method; this adds retry and timeout information, 

2014 # and friendly error handling. 

2015 rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] 

2016 

2017 # Certain fields should be provided within the metadata header; 

2018 # add these here. 

2019 metadata = tuple(metadata) + ( 

2020 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

2021 ) 

2022 

2023 # Validate the universe domain. 

2024 self._validate_universe_domain() 

2025 

2026 # Send the request. 

2027 response = rpc( 

2028 request, 

2029 retry=retry, 

2030 timeout=timeout, 

2031 metadata=metadata, 

2032 ) 

2033 

2034 # Done; return the response. 

2035 return response 

2036 

2037 def test_iam_permissions( 

2038 self, 

2039 request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, 

2040 *, 

2041 resource: Optional[str] = None, 

2042 permissions: Optional[MutableSequence[str]] = None, 

2043 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2044 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2045 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2046 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

2047 r"""Returns permissions that a caller has on a 

2048 [Queue][google.cloud.tasks.v2.Queue]. If the resource does not 

2049 exist, this will return an empty set of permissions, not a 

2050 [NOT_FOUND][google.rpc.Code.NOT_FOUND] error. 

2051 

2052 Note: This operation is designed to be used for building 

2053 permission-aware UIs and command-line tools, not for 

2054 authorization checking. This operation may "fail open" without 

2055 warning. 

2056 

2057 .. code-block:: python 

2058 

2059 # This snippet has been automatically generated and should be regarded as a 

2060 # code template only. 

2061 # It will require modifications to work: 

2062 # - It may require correct/in-range values for request initialization. 

2063 # - It may require specifying regional endpoints when creating the service 

2064 # client as shown in: 

2065 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2066 from google.cloud import tasks_v2 

2067 from google.iam.v1 import iam_policy_pb2 # type: ignore 

2068 

2069 def sample_test_iam_permissions(): 

2070 # Create a client 

2071 client = tasks_v2.CloudTasksClient() 

2072 

2073 # Initialize request argument(s) 

2074 request = iam_policy_pb2.TestIamPermissionsRequest( 

2075 resource="resource_value", 

2076 permissions=['permissions_value1', 'permissions_value2'], 

2077 ) 

2078 

2079 # Make the request 

2080 response = client.test_iam_permissions(request=request) 

2081 

2082 # Handle the response 

2083 print(response) 

2084 

2085 Args: 

2086 request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): 

2087 The request object. Request message for ``TestIamPermissions`` method. 

2088 resource (str): 

2089 REQUIRED: The resource for which the 

2090 policy detail is being requested. See 

2091 the operation documentation for the 

2092 appropriate value for this field. 

2093 

2094 This corresponds to the ``resource`` field 

2095 on the ``request`` instance; if ``request`` is provided, this 

2096 should not be set. 

2097 permissions (MutableSequence[str]): 

2098 The set of permissions to check for the ``resource``. 

2099 Permissions with wildcards (such as '*' or 'storage.*') 

2100 are not allowed. For more information see `IAM 

2101 Overview <https://cloud.google.com/iam/docs/overview#permissions>`__. 

2102 

2103 This corresponds to the ``permissions`` field 

2104 on the ``request`` instance; if ``request`` is provided, this 

2105 should not be set. 

2106 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2107 should be retried. 

2108 timeout (float): The timeout for this request. 

2109 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2110 sent along with the request as metadata. Normally, each value must be of type `str`, 

2111 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2112 be of type `bytes`. 

2113 

2114 Returns: 

2115 google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: 

2116 Response message for TestIamPermissions method. 

2117 """ 

2118 # Create or coerce a protobuf request object. 

2119 # - Quick check: If we got a request object, we should *not* have 

2120 # gotten any keyword arguments that map to the request. 

2121 flattened_params = [resource, permissions] 

2122 has_flattened_params = ( 

2123 len([param for param in flattened_params if param is not None]) > 0 

2124 ) 

2125 if request is not None and has_flattened_params: 

2126 raise ValueError( 

2127 "If the `request` argument is set, then none of " 

2128 "the individual field arguments should be set." 

2129 ) 

2130 

2131 if isinstance(request, dict): 

2132 # - The request isn't a proto-plus wrapped type, 

2133 # so it must be constructed via keyword expansion. 

2134 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

2135 elif not request: 

2136 # Null request, just make one. 

2137 request = iam_policy_pb2.TestIamPermissionsRequest() 

2138 if resource is not None: 

2139 request.resource = resource 

2140 if permissions: 

2141 request.permissions.extend(permissions) 

2142 

2143 # Wrap the RPC method; this adds retry and timeout information, 

2144 # and friendly error handling. 

2145 rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] 

2146 

2147 # Certain fields should be provided within the metadata header; 

2148 # add these here. 

2149 metadata = tuple(metadata) + ( 

2150 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

2151 ) 

2152 

2153 # Validate the universe domain. 

2154 self._validate_universe_domain() 

2155 

2156 # Send the request. 

2157 response = rpc( 

2158 request, 

2159 retry=retry, 

2160 timeout=timeout, 

2161 metadata=metadata, 

2162 ) 

2163 

2164 # Done; return the response. 

2165 return response 

2166 

2167 def list_tasks( 

2168 self, 

2169 request: Optional[Union[cloudtasks.ListTasksRequest, dict]] = None, 

2170 *, 

2171 parent: Optional[str] = None, 

2172 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2173 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2174 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2175 ) -> pagers.ListTasksPager: 

2176 r"""Lists the tasks in a queue. 

2177 

2178 By default, only the 

2179 [BASIC][google.cloud.tasks.v2.Task.View.BASIC] view is retrieved 

2180 due to performance considerations; 

2181 [response_view][google.cloud.tasks.v2.ListTasksRequest.response_view] 

2182 controls the subset of information which is returned. 

2183 

2184 The tasks may be returned in any order. The ordering may change 

2185 at any time. 

2186 

2187 .. code-block:: python 

2188 

2189 # This snippet has been automatically generated and should be regarded as a 

2190 # code template only. 

2191 # It will require modifications to work: 

2192 # - It may require correct/in-range values for request initialization. 

2193 # - It may require specifying regional endpoints when creating the service 

2194 # client as shown in: 

2195 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2196 from google.cloud import tasks_v2 

2197 

2198 def sample_list_tasks(): 

2199 # Create a client 

2200 client = tasks_v2.CloudTasksClient() 

2201 

2202 # Initialize request argument(s) 

2203 request = tasks_v2.ListTasksRequest( 

2204 parent="parent_value", 

2205 ) 

2206 

2207 # Make the request 

2208 page_result = client.list_tasks(request=request) 

2209 

2210 # Handle the response 

2211 for response in page_result: 

2212 print(response) 

2213 

2214 Args: 

2215 request (Union[google.cloud.tasks_v2.types.ListTasksRequest, dict]): 

2216 The request object. Request message for listing tasks using 

2217 [ListTasks][google.cloud.tasks.v2.CloudTasks.ListTasks]. 

2218 parent (str): 

2219 Required. The queue name. For example: 

2220 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`` 

2221 

2222 This corresponds to the ``parent`` field 

2223 on the ``request`` instance; if ``request`` is provided, this 

2224 should not be set. 

2225 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2226 should be retried. 

2227 timeout (float): The timeout for this request. 

2228 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2229 sent along with the request as metadata. Normally, each value must be of type `str`, 

2230 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2231 be of type `bytes`. 

2232 

2233 Returns: 

2234 google.cloud.tasks_v2.services.cloud_tasks.pagers.ListTasksPager: 

2235 Response message for listing tasks using 

2236 [ListTasks][google.cloud.tasks.v2.CloudTasks.ListTasks]. 

2237 

2238 Iterating over this object will yield results and 

2239 resolve additional pages automatically. 

2240 

2241 """ 

2242 # Create or coerce a protobuf request object. 

2243 # - Quick check: If we got a request object, we should *not* have 

2244 # gotten any keyword arguments that map to the request. 

2245 flattened_params = [parent] 

2246 has_flattened_params = ( 

2247 len([param for param in flattened_params if param is not None]) > 0 

2248 ) 

2249 if request is not None and has_flattened_params: 

2250 raise ValueError( 

2251 "If the `request` argument is set, then none of " 

2252 "the individual field arguments should be set." 

2253 ) 

2254 

2255 # - Use the request object if provided (there's no risk of modifying the input as 

2256 # there are no flattened fields), or create one. 

2257 if not isinstance(request, cloudtasks.ListTasksRequest): 

2258 request = cloudtasks.ListTasksRequest(request) 

2259 # If we have keyword arguments corresponding to fields on the 

2260 # request, apply these. 

2261 if parent is not None: 

2262 request.parent = parent 

2263 

2264 # Wrap the RPC method; this adds retry and timeout information, 

2265 # and friendly error handling. 

2266 rpc = self._transport._wrapped_methods[self._transport.list_tasks] 

2267 

2268 # Certain fields should be provided within the metadata header; 

2269 # add these here. 

2270 metadata = tuple(metadata) + ( 

2271 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), 

2272 ) 

2273 

2274 # Validate the universe domain. 

2275 self._validate_universe_domain() 

2276 

2277 # Send the request. 

2278 response = rpc( 

2279 request, 

2280 retry=retry, 

2281 timeout=timeout, 

2282 metadata=metadata, 

2283 ) 

2284 

2285 # This method is paged; wrap the response in a pager, which provides 

2286 # an `__iter__` convenience method. 

2287 response = pagers.ListTasksPager( 

2288 method=rpc, 

2289 request=request, 

2290 response=response, 

2291 retry=retry, 

2292 timeout=timeout, 

2293 metadata=metadata, 

2294 ) 

2295 

2296 # Done; return the response. 

2297 return response 

2298 

2299 def get_task( 

2300 self, 

2301 request: Optional[Union[cloudtasks.GetTaskRequest, dict]] = None, 

2302 *, 

2303 name: Optional[str] = None, 

2304 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2305 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2306 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2307 ) -> task.Task: 

2308 r"""Gets a task. 

2309 

2310 .. code-block:: python 

2311 

2312 # This snippet has been automatically generated and should be regarded as a 

2313 # code template only. 

2314 # It will require modifications to work: 

2315 # - It may require correct/in-range values for request initialization. 

2316 # - It may require specifying regional endpoints when creating the service 

2317 # client as shown in: 

2318 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2319 from google.cloud import tasks_v2 

2320 

2321 def sample_get_task(): 

2322 # Create a client 

2323 client = tasks_v2.CloudTasksClient() 

2324 

2325 # Initialize request argument(s) 

2326 request = tasks_v2.GetTaskRequest( 

2327 name="name_value", 

2328 ) 

2329 

2330 # Make the request 

2331 response = client.get_task(request=request) 

2332 

2333 # Handle the response 

2334 print(response) 

2335 

2336 Args: 

2337 request (Union[google.cloud.tasks_v2.types.GetTaskRequest, dict]): 

2338 The request object. Request message for getting a task using 

2339 [GetTask][google.cloud.tasks.v2.CloudTasks.GetTask]. 

2340 name (str): 

2341 Required. The task name. For example: 

2342 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`` 

2343 

2344 This corresponds to the ``name`` field 

2345 on the ``request`` instance; if ``request`` is provided, this 

2346 should not be set. 

2347 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2348 should be retried. 

2349 timeout (float): The timeout for this request. 

2350 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2351 sent along with the request as metadata. Normally, each value must be of type `str`, 

2352 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2353 be of type `bytes`. 

2354 

2355 Returns: 

2356 google.cloud.tasks_v2.types.Task: 

2357 A unit of scheduled work. 

2358 """ 

2359 # Create or coerce a protobuf request object. 

2360 # - Quick check: If we got a request object, we should *not* have 

2361 # gotten any keyword arguments that map to the request. 

2362 flattened_params = [name] 

2363 has_flattened_params = ( 

2364 len([param for param in flattened_params if param is not None]) > 0 

2365 ) 

2366 if request is not None and has_flattened_params: 

2367 raise ValueError( 

2368 "If the `request` argument is set, then none of " 

2369 "the individual field arguments should be set." 

2370 ) 

2371 

2372 # - Use the request object if provided (there's no risk of modifying the input as 

2373 # there are no flattened fields), or create one. 

2374 if not isinstance(request, cloudtasks.GetTaskRequest): 

2375 request = cloudtasks.GetTaskRequest(request) 

2376 # If we have keyword arguments corresponding to fields on the 

2377 # request, apply these. 

2378 if name is not None: 

2379 request.name = name 

2380 

2381 # Wrap the RPC method; this adds retry and timeout information, 

2382 # and friendly error handling. 

2383 rpc = self._transport._wrapped_methods[self._transport.get_task] 

2384 

2385 # Certain fields should be provided within the metadata header; 

2386 # add these here. 

2387 metadata = tuple(metadata) + ( 

2388 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

2389 ) 

2390 

2391 # Validate the universe domain. 

2392 self._validate_universe_domain() 

2393 

2394 # Send the request. 

2395 response = rpc( 

2396 request, 

2397 retry=retry, 

2398 timeout=timeout, 

2399 metadata=metadata, 

2400 ) 

2401 

2402 # Done; return the response. 

2403 return response 

2404 

2405 def create_task( 

2406 self, 

2407 request: Optional[Union[cloudtasks.CreateTaskRequest, dict]] = None, 

2408 *, 

2409 parent: Optional[str] = None, 

2410 task: Optional[gct_task.Task] = None, 

2411 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2412 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2413 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2414 ) -> gct_task.Task: 

2415 r"""Creates a task and adds it to a queue. 

2416 

2417 Tasks cannot be updated after creation; there is no UpdateTask 

2418 command. 

2419 

2420 - The maximum task size is 100KB. 

2421 

2422 .. code-block:: python 

2423 

2424 # This snippet has been automatically generated and should be regarded as a 

2425 # code template only. 

2426 # It will require modifications to work: 

2427 # - It may require correct/in-range values for request initialization. 

2428 # - It may require specifying regional endpoints when creating the service 

2429 # client as shown in: 

2430 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2431 from google.cloud import tasks_v2 

2432 

2433 def sample_create_task(): 

2434 # Create a client 

2435 client = tasks_v2.CloudTasksClient() 

2436 

2437 # Initialize request argument(s) 

2438 request = tasks_v2.CreateTaskRequest( 

2439 parent="parent_value", 

2440 ) 

2441 

2442 # Make the request 

2443 response = client.create_task(request=request) 

2444 

2445 # Handle the response 

2446 print(response) 

2447 

2448 Args: 

2449 request (Union[google.cloud.tasks_v2.types.CreateTaskRequest, dict]): 

2450 The request object. Request message for 

2451 [CreateTask][google.cloud.tasks.v2.CloudTasks.CreateTask]. 

2452 parent (str): 

2453 Required. The queue name. For example: 

2454 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`` 

2455 

2456 The queue must already exist. 

2457 

2458 This corresponds to the ``parent`` field 

2459 on the ``request`` instance; if ``request`` is provided, this 

2460 should not be set. 

2461 task (google.cloud.tasks_v2.types.Task): 

2462 Required. The task to add. 

2463 

2464 Task names have the following format: 

2465 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID``. 

2466 The user can optionally specify a task 

2467 [name][google.cloud.tasks.v2.Task.name]. If a name is 

2468 not specified then the system will generate a random 

2469 unique task id, which will be set in the task returned 

2470 in the [response][google.cloud.tasks.v2.Task.name]. 

2471 

2472 If 

2473 [schedule_time][google.cloud.tasks.v2.Task.schedule_time] 

2474 is not set or is in the past then Cloud Tasks will set 

2475 it to the current time. 

2476 

2477 Task De-duplication: 

2478 

2479 Explicitly specifying a task ID enables task 

2480 de-duplication. If a task's ID is identical to that of 

2481 an existing task or a task that was deleted or executed 

2482 recently then the call will fail with 

2483 [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS]. If the 

2484 task's queue was created using Cloud Tasks, then another 

2485 task with the same name can't be created for ~1hour 

2486 after the original task was deleted or executed. If the 

2487 task's queue was created using queue.yaml or queue.xml, 

2488 then another task with the same name can't be created 

2489 for ~9days after the original task was deleted or 

2490 executed. 

2491 

2492 Because there is an extra lookup cost to identify 

2493 duplicate task names, these 

2494 [CreateTask][google.cloud.tasks.v2.CloudTasks.CreateTask] 

2495 calls have significantly increased latency. Using hashed 

2496 strings for the task id or for the prefix of the task id 

2497 is recommended. Choosing task ids that are sequential or 

2498 have sequential prefixes, for example using a timestamp, 

2499 causes an increase in latency and error rates in all 

2500 task commands. The infrastructure relies on an 

2501 approximately uniform distribution of task ids to store 

2502 and serve tasks efficiently. 

2503 

2504 This corresponds to the ``task`` field 

2505 on the ``request`` instance; if ``request`` is provided, this 

2506 should not be set. 

2507 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2508 should be retried. 

2509 timeout (float): The timeout for this request. 

2510 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2511 sent along with the request as metadata. Normally, each value must be of type `str`, 

2512 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2513 be of type `bytes`. 

2514 

2515 Returns: 

2516 google.cloud.tasks_v2.types.Task: 

2517 A unit of scheduled work. 

2518 """ 

2519 # Create or coerce a protobuf request object. 

2520 # - Quick check: If we got a request object, we should *not* have 

2521 # gotten any keyword arguments that map to the request. 

2522 flattened_params = [parent, task] 

2523 has_flattened_params = ( 

2524 len([param for param in flattened_params if param is not None]) > 0 

2525 ) 

2526 if request is not None and has_flattened_params: 

2527 raise ValueError( 

2528 "If the `request` argument is set, then none of " 

2529 "the individual field arguments should be set." 

2530 ) 

2531 

2532 # - Use the request object if provided (there's no risk of modifying the input as 

2533 # there are no flattened fields), or create one. 

2534 if not isinstance(request, cloudtasks.CreateTaskRequest): 

2535 request = cloudtasks.CreateTaskRequest(request) 

2536 # If we have keyword arguments corresponding to fields on the 

2537 # request, apply these. 

2538 if parent is not None: 

2539 request.parent = parent 

2540 if task is not None: 

2541 request.task = task 

2542 

2543 # Wrap the RPC method; this adds retry and timeout information, 

2544 # and friendly error handling. 

2545 rpc = self._transport._wrapped_methods[self._transport.create_task] 

2546 

2547 # Certain fields should be provided within the metadata header; 

2548 # add these here. 

2549 metadata = tuple(metadata) + ( 

2550 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), 

2551 ) 

2552 

2553 # Validate the universe domain. 

2554 self._validate_universe_domain() 

2555 

2556 # Send the request. 

2557 response = rpc( 

2558 request, 

2559 retry=retry, 

2560 timeout=timeout, 

2561 metadata=metadata, 

2562 ) 

2563 

2564 # Done; return the response. 

2565 return response 

2566 

2567 def delete_task( 

2568 self, 

2569 request: Optional[Union[cloudtasks.DeleteTaskRequest, dict]] = None, 

2570 *, 

2571 name: Optional[str] = None, 

2572 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2573 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2574 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2575 ) -> None: 

2576 r"""Deletes a task. 

2577 

2578 A task can be deleted if it is scheduled or dispatched. 

2579 A task cannot be deleted if it has executed successfully 

2580 or permanently failed. 

2581 

2582 .. code-block:: python 

2583 

2584 # This snippet has been automatically generated and should be regarded as a 

2585 # code template only. 

2586 # It will require modifications to work: 

2587 # - It may require correct/in-range values for request initialization. 

2588 # - It may require specifying regional endpoints when creating the service 

2589 # client as shown in: 

2590 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2591 from google.cloud import tasks_v2 

2592 

2593 def sample_delete_task(): 

2594 # Create a client 

2595 client = tasks_v2.CloudTasksClient() 

2596 

2597 # Initialize request argument(s) 

2598 request = tasks_v2.DeleteTaskRequest( 

2599 name="name_value", 

2600 ) 

2601 

2602 # Make the request 

2603 client.delete_task(request=request) 

2604 

2605 Args: 

2606 request (Union[google.cloud.tasks_v2.types.DeleteTaskRequest, dict]): 

2607 The request object. Request message for deleting a task using 

2608 [DeleteTask][google.cloud.tasks.v2.CloudTasks.DeleteTask]. 

2609 name (str): 

2610 Required. The task name. For example: 

2611 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`` 

2612 

2613 This corresponds to the ``name`` field 

2614 on the ``request`` instance; if ``request`` is provided, this 

2615 should not be set. 

2616 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2617 should be retried. 

2618 timeout (float): The timeout for this request. 

2619 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2620 sent along with the request as metadata. Normally, each value must be of type `str`, 

2621 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2622 be of type `bytes`. 

2623 """ 

2624 # Create or coerce a protobuf request object. 

2625 # - Quick check: If we got a request object, we should *not* have 

2626 # gotten any keyword arguments that map to the request. 

2627 flattened_params = [name] 

2628 has_flattened_params = ( 

2629 len([param for param in flattened_params if param is not None]) > 0 

2630 ) 

2631 if request is not None and has_flattened_params: 

2632 raise ValueError( 

2633 "If the `request` argument is set, then none of " 

2634 "the individual field arguments should be set." 

2635 ) 

2636 

2637 # - Use the request object if provided (there's no risk of modifying the input as 

2638 # there are no flattened fields), or create one. 

2639 if not isinstance(request, cloudtasks.DeleteTaskRequest): 

2640 request = cloudtasks.DeleteTaskRequest(request) 

2641 # If we have keyword arguments corresponding to fields on the 

2642 # request, apply these. 

2643 if name is not None: 

2644 request.name = name 

2645 

2646 # Wrap the RPC method; this adds retry and timeout information, 

2647 # and friendly error handling. 

2648 rpc = self._transport._wrapped_methods[self._transport.delete_task] 

2649 

2650 # Certain fields should be provided within the metadata header; 

2651 # add these here. 

2652 metadata = tuple(metadata) + ( 

2653 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

2654 ) 

2655 

2656 # Validate the universe domain. 

2657 self._validate_universe_domain() 

2658 

2659 # Send the request. 

2660 rpc( 

2661 request, 

2662 retry=retry, 

2663 timeout=timeout, 

2664 metadata=metadata, 

2665 ) 

2666 

2667 def run_task( 

2668 self, 

2669 request: Optional[Union[cloudtasks.RunTaskRequest, dict]] = None, 

2670 *, 

2671 name: Optional[str] = None, 

2672 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2673 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2674 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2675 ) -> task.Task: 

2676 r"""Forces a task to run now. 

2677 

2678 When this method is called, Cloud Tasks will dispatch the task, 

2679 even if the task is already running, the queue has reached its 

2680 [RateLimits][google.cloud.tasks.v2.RateLimits] or is 

2681 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED]. 

2682 

2683 This command is meant to be used for manual debugging. For 

2684 example, [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] can 

2685 be used to retry a failed task after a fix has been made or to 

2686 manually force a task to be dispatched now. 

2687 

2688 The dispatched task is returned. That is, the task that is 

2689 returned contains the [status][Task.status] after the task is 

2690 dispatched but before the task is received by its target. 

2691 

2692 If Cloud Tasks receives a successful response from the task's 

2693 target, then the task will be deleted; otherwise the task's 

2694 [schedule_time][google.cloud.tasks.v2.Task.schedule_time] will 

2695 be reset to the time that 

2696 [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] was called 

2697 plus the retry delay specified in the queue's 

2698 [RetryConfig][google.cloud.tasks.v2.RetryConfig]. 

2699 

2700 [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] returns 

2701 [NOT_FOUND][google.rpc.Code.NOT_FOUND] when it is called on a 

2702 task that has already succeeded or permanently failed. 

2703 

2704 .. code-block:: python 

2705 

2706 # This snippet has been automatically generated and should be regarded as a 

2707 # code template only. 

2708 # It will require modifications to work: 

2709 # - It may require correct/in-range values for request initialization. 

2710 # - It may require specifying regional endpoints when creating the service 

2711 # client as shown in: 

2712 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2713 from google.cloud import tasks_v2 

2714 

2715 def sample_run_task(): 

2716 # Create a client 

2717 client = tasks_v2.CloudTasksClient() 

2718 

2719 # Initialize request argument(s) 

2720 request = tasks_v2.RunTaskRequest( 

2721 name="name_value", 

2722 ) 

2723 

2724 # Make the request 

2725 response = client.run_task(request=request) 

2726 

2727 # Handle the response 

2728 print(response) 

2729 

2730 Args: 

2731 request (Union[google.cloud.tasks_v2.types.RunTaskRequest, dict]): 

2732 The request object. Request message for forcing a task to run now using 

2733 [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask]. 

2734 name (str): 

2735 Required. The task name. For example: 

2736 ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`` 

2737 

2738 This corresponds to the ``name`` field 

2739 on the ``request`` instance; if ``request`` is provided, this 

2740 should not be set. 

2741 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2742 should be retried. 

2743 timeout (float): The timeout for this request. 

2744 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2745 sent along with the request as metadata. Normally, each value must be of type `str`, 

2746 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2747 be of type `bytes`. 

2748 

2749 Returns: 

2750 google.cloud.tasks_v2.types.Task: 

2751 A unit of scheduled work. 

2752 """ 

2753 # Create or coerce a protobuf request object. 

2754 # - Quick check: If we got a request object, we should *not* have 

2755 # gotten any keyword arguments that map to the request. 

2756 flattened_params = [name] 

2757 has_flattened_params = ( 

2758 len([param for param in flattened_params if param is not None]) > 0 

2759 ) 

2760 if request is not None and has_flattened_params: 

2761 raise ValueError( 

2762 "If the `request` argument is set, then none of " 

2763 "the individual field arguments should be set." 

2764 ) 

2765 

2766 # - Use the request object if provided (there's no risk of modifying the input as 

2767 # there are no flattened fields), or create one. 

2768 if not isinstance(request, cloudtasks.RunTaskRequest): 

2769 request = cloudtasks.RunTaskRequest(request) 

2770 # If we have keyword arguments corresponding to fields on the 

2771 # request, apply these. 

2772 if name is not None: 

2773 request.name = name 

2774 

2775 # Wrap the RPC method; this adds retry and timeout information, 

2776 # and friendly error handling. 

2777 rpc = self._transport._wrapped_methods[self._transport.run_task] 

2778 

2779 # Certain fields should be provided within the metadata header; 

2780 # add these here. 

2781 metadata = tuple(metadata) + ( 

2782 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

2783 ) 

2784 

2785 # Validate the universe domain. 

2786 self._validate_universe_domain() 

2787 

2788 # Send the request. 

2789 response = rpc( 

2790 request, 

2791 retry=retry, 

2792 timeout=timeout, 

2793 metadata=metadata, 

2794 ) 

2795 

2796 # Done; return the response. 

2797 return response 

2798 

2799 def __enter__(self) -> "CloudTasksClient": 

2800 return self 

2801 

2802 def __exit__(self, type, value, traceback): 

2803 """Releases underlying transport's resources. 

2804 

2805 .. warning:: 

2806 ONLY use as a context manager if the transport is NOT shared 

2807 with other clients! Exiting the with block will CLOSE the transport 

2808 and may cause errors in other clients! 

2809 """ 

2810 self.transport.close() 

2811 

2812 def get_location( 

2813 self, 

2814 request: Optional[locations_pb2.GetLocationRequest] = None, 

2815 *, 

2816 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2817 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2818 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2819 ) -> locations_pb2.Location: 

2820 r"""Gets information about a location. 

2821 

2822 Args: 

2823 request (:class:`~.location_pb2.GetLocationRequest`): 

2824 The request object. Request message for 

2825 `GetLocation` method. 

2826 retry (google.api_core.retry.Retry): Designation of what errors, 

2827 if any, should be retried. 

2828 timeout (float): The timeout for this request. 

2829 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2830 sent along with the request as metadata. Normally, each value must be of type `str`, 

2831 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2832 be of type `bytes`. 

2833 Returns: 

2834 ~.location_pb2.Location: 

2835 Location object. 

2836 """ 

2837 # Create or coerce a protobuf request object. 

2838 # The request isn't a proto-plus wrapped type, 

2839 # so it must be constructed via keyword expansion. 

2840 if isinstance(request, dict): 

2841 request = locations_pb2.GetLocationRequest(**request) 

2842 

2843 # Wrap the RPC method; this adds retry and timeout information, 

2844 # and friendly error handling. 

2845 rpc = self._transport._wrapped_methods[self._transport.get_location] 

2846 

2847 # Certain fields should be provided within the metadata header; 

2848 # add these here. 

2849 metadata = tuple(metadata) + ( 

2850 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

2851 ) 

2852 

2853 # Validate the universe domain. 

2854 self._validate_universe_domain() 

2855 

2856 try: 

2857 # Send the request. 

2858 response = rpc( 

2859 request, 

2860 retry=retry, 

2861 timeout=timeout, 

2862 metadata=metadata, 

2863 ) 

2864 

2865 # Done; return the response. 

2866 return response 

2867 except core_exceptions.GoogleAPICallError as e: 

2868 self._add_cred_info_for_auth_errors(e) 

2869 raise e 

2870 

2871 def list_locations( 

2872 self, 

2873 request: Optional[locations_pb2.ListLocationsRequest] = None, 

2874 *, 

2875 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2876 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2877 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2878 ) -> locations_pb2.ListLocationsResponse: 

2879 r"""Lists information about the supported locations for this service. 

2880 

2881 Args: 

2882 request (:class:`~.location_pb2.ListLocationsRequest`): 

2883 The request object. Request message for 

2884 `ListLocations` method. 

2885 retry (google.api_core.retry.Retry): Designation of what errors, 

2886 if any, should be retried. 

2887 timeout (float): The timeout for this request. 

2888 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2889 sent along with the request as metadata. Normally, each value must be of type `str`, 

2890 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2891 be of type `bytes`. 

2892 Returns: 

2893 ~.location_pb2.ListLocationsResponse: 

2894 Response message for ``ListLocations`` method. 

2895 """ 

2896 # Create or coerce a protobuf request object. 

2897 # The request isn't a proto-plus wrapped type, 

2898 # so it must be constructed via keyword expansion. 

2899 if isinstance(request, dict): 

2900 request = locations_pb2.ListLocationsRequest(**request) 

2901 

2902 # Wrap the RPC method; this adds retry and timeout information, 

2903 # and friendly error handling. 

2904 rpc = self._transport._wrapped_methods[self._transport.list_locations] 

2905 

2906 # Certain fields should be provided within the metadata header; 

2907 # add these here. 

2908 metadata = tuple(metadata) + ( 

2909 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

2910 ) 

2911 

2912 # Validate the universe domain. 

2913 self._validate_universe_domain() 

2914 

2915 try: 

2916 # Send the request. 

2917 response = rpc( 

2918 request, 

2919 retry=retry, 

2920 timeout=timeout, 

2921 metadata=metadata, 

2922 ) 

2923 

2924 # Done; return the response. 

2925 return response 

2926 except core_exceptions.GoogleAPICallError as e: 

2927 self._add_cred_info_for_auth_errors(e) 

2928 raise e 

2929 

2930 

2931DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

2932 gapic_version=package_version.__version__ 

2933) 

2934 

2935if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER 

2936 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

2937 

2938__all__ = ("CloudTasksClient",)