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

509 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 @staticmethod 

165 def _use_client_cert_effective(): 

166 """Returns whether client certificate should be used for mTLS if the 

167 google-auth version supports should_use_client_cert automatic mTLS enablement. 

168 

169 Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. 

170 

171 Returns: 

172 bool: whether client certificate should be used for mTLS 

173 Raises: 

174 ValueError: (If using a version of google-auth without should_use_client_cert and 

175 GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) 

176 """ 

177 # check if google-auth version supports should_use_client_cert for automatic mTLS enablement 

178 if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER 

179 return mtls.should_use_client_cert() 

180 else: # pragma: NO COVER 

181 # if unsupported, fallback to reading from env var 

182 use_client_cert_str = os.getenv( 

183 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" 

184 ).lower() 

185 if use_client_cert_str not in ("true", "false"): 

186 raise ValueError( 

187 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" 

188 " either `true` or `false`" 

189 ) 

190 return use_client_cert_str == "true" 

191 

192 @classmethod 

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

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

195 info. 

196 

197 Args: 

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

199 args: Additional arguments to pass to the constructor. 

200 kwargs: Additional arguments to pass to the constructor. 

201 

202 Returns: 

203 CloudTasksClient: The constructed client. 

204 """ 

205 credentials = service_account.Credentials.from_service_account_info(info) 

206 kwargs["credentials"] = credentials 

207 return cls(*args, **kwargs) 

208 

209 @classmethod 

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

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

212 file. 

213 

214 Args: 

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

216 file. 

217 args: Additional arguments to pass to the constructor. 

218 kwargs: Additional arguments to pass to the constructor. 

219 

220 Returns: 

221 CloudTasksClient: The constructed client. 

222 """ 

223 credentials = service_account.Credentials.from_service_account_file(filename) 

224 kwargs["credentials"] = credentials 

225 return cls(*args, **kwargs) 

226 

227 from_service_account_json = from_service_account_file 

228 

229 @property 

230 def transport(self) -> CloudTasksTransport: 

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

232 

233 Returns: 

234 CloudTasksTransport: The transport used by the client 

235 instance. 

236 """ 

237 return self._transport 

238 

239 @staticmethod 

240 def queue_path( 

241 project: str, 

242 location: str, 

243 queue: str, 

244 ) -> str: 

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

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

247 project=project, 

248 location=location, 

249 queue=queue, 

250 ) 

251 

252 @staticmethod 

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

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

255 m = re.match( 

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

257 path, 

258 ) 

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

260 

261 @staticmethod 

262 def task_path( 

263 project: str, 

264 location: str, 

265 queue: str, 

266 task: str, 

267 ) -> str: 

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

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

270 project=project, 

271 location=location, 

272 queue=queue, 

273 task=task, 

274 ) 

275 

276 @staticmethod 

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

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

279 m = re.match( 

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

281 path, 

282 ) 

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

284 

285 @staticmethod 

286 def common_billing_account_path( 

287 billing_account: str, 

288 ) -> str: 

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

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

291 billing_account=billing_account, 

292 ) 

293 

294 @staticmethod 

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

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

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

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

299 

300 @staticmethod 

301 def common_folder_path( 

302 folder: str, 

303 ) -> str: 

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

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

306 folder=folder, 

307 ) 

308 

309 @staticmethod 

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

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

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

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

314 

315 @staticmethod 

316 def common_organization_path( 

317 organization: str, 

318 ) -> str: 

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

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

321 organization=organization, 

322 ) 

323 

324 @staticmethod 

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

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

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

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

329 

330 @staticmethod 

331 def common_project_path( 

332 project: str, 

333 ) -> str: 

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

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

336 project=project, 

337 ) 

338 

339 @staticmethod 

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

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

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

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

344 

345 @staticmethod 

346 def common_location_path( 

347 project: str, 

348 location: str, 

349 ) -> str: 

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

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

352 project=project, 

353 location=location, 

354 ) 

355 

356 @staticmethod 

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

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

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

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

361 

362 @classmethod 

363 def get_mtls_endpoint_and_cert_source( 

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

365 ): 

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

367 

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

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

370 client cert source is None. 

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

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

373 source is None. 

374 

375 The API endpoint is determined in the following order: 

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

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

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

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

380 use the default API endpoint. 

381 

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

383 

384 Args: 

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

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

387 in this method. 

388 

389 Returns: 

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

391 client cert source to use. 

392 

393 Raises: 

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

395 """ 

396 

397 warnings.warn( 

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

399 DeprecationWarning, 

400 ) 

401 if client_options is None: 

402 client_options = client_options_lib.ClientOptions() 

403 use_client_cert = CloudTasksClient._use_client_cert_effective() 

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

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

406 raise MutualTLSChannelError( 

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

408 ) 

409 

410 # Figure out the client cert source to use. 

411 client_cert_source = None 

412 if use_client_cert: 

413 if client_options.client_cert_source: 

414 client_cert_source = client_options.client_cert_source 

415 elif mtls.has_default_client_cert_source(): 

416 client_cert_source = mtls.default_client_cert_source() 

417 

418 # Figure out which api endpoint to use. 

419 if client_options.api_endpoint is not None: 

420 api_endpoint = client_options.api_endpoint 

421 elif use_mtls_endpoint == "always" or ( 

422 use_mtls_endpoint == "auto" and client_cert_source 

423 ): 

424 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

425 else: 

426 api_endpoint = cls.DEFAULT_ENDPOINT 

427 

428 return api_endpoint, client_cert_source 

429 

430 @staticmethod 

431 def _read_environment_variables(): 

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

433 

434 Returns: 

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

436 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. 

437 

438 Raises: 

439 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not 

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

441 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT 

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

443 """ 

444 use_client_cert = CloudTasksClient._use_client_cert_effective() 

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

446 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") 

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

448 raise MutualTLSChannelError( 

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

450 ) 

451 return use_client_cert, use_mtls_endpoint, universe_domain_env 

452 

453 @staticmethod 

454 def _get_client_cert_source(provided_cert_source, use_cert_flag): 

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

456 

457 Args: 

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

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

460 

461 Returns: 

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

463 """ 

464 client_cert_source = None 

465 if use_cert_flag: 

466 if provided_cert_source: 

467 client_cert_source = provided_cert_source 

468 elif mtls.has_default_client_cert_source(): 

469 client_cert_source = mtls.default_client_cert_source() 

470 return client_cert_source 

471 

472 @staticmethod 

473 def _get_api_endpoint( 

474 api_override, client_cert_source, universe_domain, use_mtls_endpoint 

475 ): 

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

477 

478 Args: 

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

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

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

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

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

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

485 

486 Returns: 

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

488 """ 

489 if api_override is not None: 

490 api_endpoint = api_override 

491 elif use_mtls_endpoint == "always" or ( 

492 use_mtls_endpoint == "auto" and client_cert_source 

493 ): 

494 _default_universe = CloudTasksClient._DEFAULT_UNIVERSE 

495 if universe_domain != _default_universe: 

496 raise MutualTLSChannelError( 

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

498 ) 

499 api_endpoint = CloudTasksClient.DEFAULT_MTLS_ENDPOINT 

500 else: 

501 api_endpoint = CloudTasksClient._DEFAULT_ENDPOINT_TEMPLATE.format( 

502 UNIVERSE_DOMAIN=universe_domain 

503 ) 

504 return api_endpoint 

505 

506 @staticmethod 

507 def _get_universe_domain( 

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

509 ) -> str: 

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

511 

512 Args: 

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

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

515 

516 Returns: 

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

518 

519 Raises: 

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

521 """ 

522 universe_domain = CloudTasksClient._DEFAULT_UNIVERSE 

523 if client_universe_domain is not None: 

524 universe_domain = client_universe_domain 

525 elif universe_domain_env is not None: 

526 universe_domain = universe_domain_env 

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

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

529 return universe_domain 

530 

531 def _validate_universe_domain(self): 

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

533 

534 Returns: 

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

536 

537 Raises: 

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

539 """ 

540 

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

542 return True 

543 

544 def _add_cred_info_for_auth_errors( 

545 self, error: core_exceptions.GoogleAPICallError 

546 ) -> None: 

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

548 

549 Args: 

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

551 """ 

552 if error.code not in [ 

553 HTTPStatus.UNAUTHORIZED, 

554 HTTPStatus.FORBIDDEN, 

555 HTTPStatus.NOT_FOUND, 

556 ]: 

557 return 

558 

559 cred = self._transport._credentials 

560 

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

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

563 return 

564 

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

566 # is not available 

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

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

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

570 

571 @property 

572 def api_endpoint(self): 

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

574 

575 Returns: 

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

577 """ 

578 return self._api_endpoint 

579 

580 @property 

581 def universe_domain(self) -> str: 

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

583 

584 Returns: 

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

586 """ 

587 return self._universe_domain 

588 

589 def __init__( 

590 self, 

591 *, 

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

593 transport: Optional[ 

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

595 ] = None, 

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

597 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

598 ) -> None: 

599 """Instantiates the cloud tasks client. 

600 

601 Args: 

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

603 authorization credentials to attach to requests. These 

604 credentials identify the application to the service; if none 

605 are specified, the client will attempt to ascertain the 

606 credentials from the environment. 

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

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

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

610 arguments as used in the CloudTasksTransport constructor. 

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

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

613 Custom options for the client. 

614 

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

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

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

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

619 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

620 variable, which have one of the following values: 

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

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

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

624 the default value). 

625 

626 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

628 to provide a client certificate for mTLS transport. If 

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

630 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

631 set, no client certificate will be used. 

632 

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

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

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

636 currently not supported for mTLS. 

637 

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

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

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

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

642 your own client library. 

643 

644 Raises: 

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

646 creation failed for any reason. 

647 """ 

648 self._client_options = client_options 

649 if isinstance(self._client_options, dict): 

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

651 if self._client_options is None: 

652 self._client_options = client_options_lib.ClientOptions() 

653 self._client_options = cast( 

654 client_options_lib.ClientOptions, self._client_options 

655 ) 

656 

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

658 

659 ( 

660 self._use_client_cert, 

661 self._use_mtls_endpoint, 

662 self._universe_domain_env, 

663 ) = CloudTasksClient._read_environment_variables() 

664 self._client_cert_source = CloudTasksClient._get_client_cert_source( 

665 self._client_options.client_cert_source, self._use_client_cert 

666 ) 

667 self._universe_domain = CloudTasksClient._get_universe_domain( 

668 universe_domain_opt, self._universe_domain_env 

669 ) 

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

671 

672 # Initialize the universe domain validation. 

673 self._is_universe_domain_valid = False 

674 

675 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER 

676 # Setup logging. 

677 client_logging.initialize_logging() 

678 

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

680 if api_key_value and credentials: 

681 raise ValueError( 

682 "client_options.api_key and credentials are mutually exclusive" 

683 ) 

684 

685 # Save or instantiate the transport. 

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

687 # instance provides an extensibility point for unusual situations. 

688 transport_provided = isinstance(transport, CloudTasksTransport) 

689 if transport_provided: 

690 # transport is a CloudTasksTransport instance. 

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

692 raise ValueError( 

693 "When providing a transport instance, " 

694 "provide its credentials directly." 

695 ) 

696 if self._client_options.scopes: 

697 raise ValueError( 

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

699 "directly." 

700 ) 

701 self._transport = cast(CloudTasksTransport, transport) 

702 self._api_endpoint = self._transport.host 

703 

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

705 self._client_options.api_endpoint, 

706 self._client_cert_source, 

707 self._universe_domain, 

708 self._use_mtls_endpoint, 

709 ) 

710 

711 if not transport_provided: 

712 import google.auth._default # type: ignore 

713 

714 if api_key_value and hasattr( 

715 google.auth._default, "get_api_key_credentials" 

716 ): 

717 credentials = google.auth._default.get_api_key_credentials( 

718 api_key_value 

719 ) 

720 

721 transport_init: Union[ 

722 Type[CloudTasksTransport], Callable[..., CloudTasksTransport] 

723 ] = ( 

724 CloudTasksClient.get_transport_class(transport) 

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

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

727 ) 

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

729 self._transport = transport_init( 

730 credentials=credentials, 

731 credentials_file=self._client_options.credentials_file, 

732 host=self._api_endpoint, 

733 scopes=self._client_options.scopes, 

734 client_cert_source_for_mtls=self._client_cert_source, 

735 quota_project_id=self._client_options.quota_project_id, 

736 client_info=client_info, 

737 always_use_jwt_access=True, 

738 api_audience=self._client_options.api_audience, 

739 ) 

740 

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

742 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

743 std_logging.DEBUG 

744 ): # pragma: NO COVER 

745 _LOGGER.debug( 

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

747 extra={ 

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

749 "universeDomain": getattr( 

750 self._transport._credentials, "universe_domain", "" 

751 ), 

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

753 "credentialsInfo": getattr( 

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

755 )(), 

756 } 

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

758 else { 

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

760 "credentialsType": None, 

761 }, 

762 ) 

763 

764 def list_queues( 

765 self, 

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

767 *, 

768 parent: Optional[str] = None, 

769 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

772 ) -> pagers.ListQueuesPager: 

773 r"""Lists queues. 

774 

775 Queues are returned in lexicographical order. 

776 

777 .. code-block:: python 

778 

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

780 # code template only. 

781 # It will require modifications to work: 

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

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

784 # client as shown in: 

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

786 from google.cloud import tasks_v2 

787 

788 def sample_list_queues(): 

789 # Create a client 

790 client = tasks_v2.CloudTasksClient() 

791 

792 # Initialize request argument(s) 

793 request = tasks_v2.ListQueuesRequest( 

794 parent="parent_value", 

795 ) 

796 

797 # Make the request 

798 page_result = client.list_queues(request=request) 

799 

800 # Handle the response 

801 for response in page_result: 

802 print(response) 

803 

804 Args: 

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

806 The request object. Request message for 

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

808 parent (str): 

809 Required. The location name. For example: 

810 ``projects/PROJECT_ID/locations/LOCATION_ID`` 

811 

812 This corresponds to the ``parent`` field 

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

814 should not be set. 

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

816 should be retried. 

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

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

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

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

821 be of type `bytes`. 

822 

823 Returns: 

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

825 Response message for 

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

827 

828 Iterating over this object will yield results and 

829 resolve additional pages automatically. 

830 

831 """ 

832 # Create or coerce a protobuf request object. 

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

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

835 flattened_params = [parent] 

836 has_flattened_params = ( 

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

838 ) 

839 if request is not None and has_flattened_params: 

840 raise ValueError( 

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

842 "the individual field arguments should be set." 

843 ) 

844 

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

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

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

848 request = cloudtasks.ListQueuesRequest(request) 

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

850 # request, apply these. 

851 if parent is not None: 

852 request.parent = parent 

853 

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

855 # and friendly error handling. 

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

857 

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

859 # add these here. 

860 metadata = tuple(metadata) + ( 

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

862 ) 

863 

864 # Validate the universe domain. 

865 self._validate_universe_domain() 

866 

867 # Send the request. 

868 response = rpc( 

869 request, 

870 retry=retry, 

871 timeout=timeout, 

872 metadata=metadata, 

873 ) 

874 

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

876 # an `__iter__` convenience method. 

877 response = pagers.ListQueuesPager( 

878 method=rpc, 

879 request=request, 

880 response=response, 

881 retry=retry, 

882 timeout=timeout, 

883 metadata=metadata, 

884 ) 

885 

886 # Done; return the response. 

887 return response 

888 

889 def get_queue( 

890 self, 

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

892 *, 

893 name: Optional[str] = None, 

894 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

897 ) -> queue.Queue: 

898 r"""Gets a queue. 

899 

900 .. code-block:: python 

901 

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

903 # code template only. 

904 # It will require modifications to work: 

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

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

907 # client as shown in: 

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

909 from google.cloud import tasks_v2 

910 

911 def sample_get_queue(): 

912 # Create a client 

913 client = tasks_v2.CloudTasksClient() 

914 

915 # Initialize request argument(s) 

916 request = tasks_v2.GetQueueRequest( 

917 name="name_value", 

918 ) 

919 

920 # Make the request 

921 response = client.get_queue(request=request) 

922 

923 # Handle the response 

924 print(response) 

925 

926 Args: 

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

928 The request object. Request message for 

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

930 name (str): 

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

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

933 

934 This corresponds to the ``name`` field 

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

936 should not be set. 

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

938 should be retried. 

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

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

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

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

943 be of type `bytes`. 

944 

945 Returns: 

946 google.cloud.tasks_v2.types.Queue: 

947 A queue is a container of related 

948 tasks. Queues are configured to manage 

949 how those tasks are dispatched. 

950 Configurable properties include rate 

951 limits, retry options, queue types, and 

952 others. 

953 

954 """ 

955 # Create or coerce a protobuf request object. 

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

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

958 flattened_params = [name] 

959 has_flattened_params = ( 

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

961 ) 

962 if request is not None and has_flattened_params: 

963 raise ValueError( 

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

965 "the individual field arguments should be set." 

966 ) 

967 

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

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

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

971 request = cloudtasks.GetQueueRequest(request) 

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

973 # request, apply these. 

974 if name is not None: 

975 request.name = name 

976 

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

978 # and friendly error handling. 

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

980 

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

982 # add these here. 

983 metadata = tuple(metadata) + ( 

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

985 ) 

986 

987 # Validate the universe domain. 

988 self._validate_universe_domain() 

989 

990 # Send the request. 

991 response = rpc( 

992 request, 

993 retry=retry, 

994 timeout=timeout, 

995 metadata=metadata, 

996 ) 

997 

998 # Done; return the response. 

999 return response 

1000 

1001 def create_queue( 

1002 self, 

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

1004 *, 

1005 parent: Optional[str] = None, 

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

1007 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1010 ) -> gct_queue.Queue: 

1011 r"""Creates a queue. 

1012 

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

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

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

1016 

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

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

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

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

1021 before using this method. 

1022 

1023 .. code-block:: python 

1024 

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

1026 # code template only. 

1027 # It will require modifications to work: 

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

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

1030 # client as shown in: 

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

1032 from google.cloud import tasks_v2 

1033 

1034 def sample_create_queue(): 

1035 # Create a client 

1036 client = tasks_v2.CloudTasksClient() 

1037 

1038 # Initialize request argument(s) 

1039 request = tasks_v2.CreateQueueRequest( 

1040 parent="parent_value", 

1041 ) 

1042 

1043 # Make the request 

1044 response = client.create_queue(request=request) 

1045 

1046 # Handle the response 

1047 print(response) 

1048 

1049 Args: 

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

1051 The request object. Request message for 

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

1053 parent (str): 

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

1055 created. For example: 

1056 ``projects/PROJECT_ID/locations/LOCATION_ID`` 

1057 

1058 The list of allowed locations can be obtained by calling 

1059 Cloud Tasks' implementation of 

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

1061 

1062 This corresponds to the ``parent`` field 

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

1064 should not be set. 

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

1066 Required. The queue to create. 

1067 

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

1069 be the same as an existing queue. 

1070 

1071 This corresponds to the ``queue`` field 

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

1073 should not be set. 

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

1075 should be retried. 

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

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

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

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

1080 be of type `bytes`. 

1081 

1082 Returns: 

1083 google.cloud.tasks_v2.types.Queue: 

1084 A queue is a container of related 

1085 tasks. Queues are configured to manage 

1086 how those tasks are dispatched. 

1087 Configurable properties include rate 

1088 limits, retry options, queue types, and 

1089 others. 

1090 

1091 """ 

1092 # Create or coerce a protobuf request object. 

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

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

1095 flattened_params = [parent, queue] 

1096 has_flattened_params = ( 

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

1098 ) 

1099 if request is not None and has_flattened_params: 

1100 raise ValueError( 

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

1102 "the individual field arguments should be set." 

1103 ) 

1104 

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

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

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

1108 request = cloudtasks.CreateQueueRequest(request) 

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

1110 # request, apply these. 

1111 if parent is not None: 

1112 request.parent = parent 

1113 if queue is not None: 

1114 request.queue = queue 

1115 

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

1117 # and friendly error handling. 

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

1119 

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

1121 # add these here. 

1122 metadata = tuple(metadata) + ( 

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

1124 ) 

1125 

1126 # Validate the universe domain. 

1127 self._validate_universe_domain() 

1128 

1129 # Send the request. 

1130 response = rpc( 

1131 request, 

1132 retry=retry, 

1133 timeout=timeout, 

1134 metadata=metadata, 

1135 ) 

1136 

1137 # Done; return the response. 

1138 return response 

1139 

1140 def update_queue( 

1141 self, 

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

1143 *, 

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

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

1146 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1149 ) -> gct_queue.Queue: 

1150 r"""Updates a queue. 

1151 

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

1153 the queue if it does exist. 

1154 

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

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

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

1158 

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

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

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

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

1163 before using this method. 

1164 

1165 .. code-block:: python 

1166 

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

1168 # code template only. 

1169 # It will require modifications to work: 

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

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

1172 # client as shown in: 

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

1174 from google.cloud import tasks_v2 

1175 

1176 def sample_update_queue(): 

1177 # Create a client 

1178 client = tasks_v2.CloudTasksClient() 

1179 

1180 # Initialize request argument(s) 

1181 request = tasks_v2.UpdateQueueRequest( 

1182 ) 

1183 

1184 # Make the request 

1185 response = client.update_queue(request=request) 

1186 

1187 # Handle the response 

1188 print(response) 

1189 

1190 Args: 

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

1192 The request object. Request message for 

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

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

1195 Required. The queue to create or update. 

1196 

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

1198 must be specified. 

1199 

1200 Output only fields cannot be modified using UpdateQueue. 

1201 Any value specified for an output only field will be 

1202 ignored. The queue's 

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

1204 changed. 

1205 

1206 This corresponds to the ``queue`` field 

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

1208 should not be set. 

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

1210 A mask used to specify which fields 

1211 of the queue are being updated. 

1212 If empty, then all fields will be 

1213 updated. 

1214 

1215 This corresponds to the ``update_mask`` field 

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

1217 should not be set. 

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

1219 should be retried. 

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

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

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

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

1224 be of type `bytes`. 

1225 

1226 Returns: 

1227 google.cloud.tasks_v2.types.Queue: 

1228 A queue is a container of related 

1229 tasks. Queues are configured to manage 

1230 how those tasks are dispatched. 

1231 Configurable properties include rate 

1232 limits, retry options, queue types, and 

1233 others. 

1234 

1235 """ 

1236 # Create or coerce a protobuf request object. 

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

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

1239 flattened_params = [queue, update_mask] 

1240 has_flattened_params = ( 

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

1242 ) 

1243 if request is not None and has_flattened_params: 

1244 raise ValueError( 

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

1246 "the individual field arguments should be set." 

1247 ) 

1248 

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

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

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

1252 request = cloudtasks.UpdateQueueRequest(request) 

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

1254 # request, apply these. 

1255 if queue is not None: 

1256 request.queue = queue 

1257 if update_mask is not None: 

1258 request.update_mask = update_mask 

1259 

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

1261 # and friendly error handling. 

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

1263 

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

1265 # add these here. 

1266 metadata = tuple(metadata) + ( 

1267 gapic_v1.routing_header.to_grpc_metadata( 

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

1269 ), 

1270 ) 

1271 

1272 # Validate the universe domain. 

1273 self._validate_universe_domain() 

1274 

1275 # Send the request. 

1276 response = rpc( 

1277 request, 

1278 retry=retry, 

1279 timeout=timeout, 

1280 metadata=metadata, 

1281 ) 

1282 

1283 # Done; return the response. 

1284 return response 

1285 

1286 def delete_queue( 

1287 self, 

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

1289 *, 

1290 name: Optional[str] = None, 

1291 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1294 ) -> None: 

1295 r"""Deletes a queue. 

1296 

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

1298 

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

1300 created for 7 days. 

1301 

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

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

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

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

1306 before using this method. 

1307 

1308 .. code-block:: python 

1309 

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

1311 # code template only. 

1312 # It will require modifications to work: 

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

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

1315 # client as shown in: 

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

1317 from google.cloud import tasks_v2 

1318 

1319 def sample_delete_queue(): 

1320 # Create a client 

1321 client = tasks_v2.CloudTasksClient() 

1322 

1323 # Initialize request argument(s) 

1324 request = tasks_v2.DeleteQueueRequest( 

1325 name="name_value", 

1326 ) 

1327 

1328 # Make the request 

1329 client.delete_queue(request=request) 

1330 

1331 Args: 

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

1333 The request object. Request message for 

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

1335 name (str): 

1336 Required. The queue name. For example: 

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

1338 

1339 This corresponds to the ``name`` field 

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

1341 should not be set. 

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

1343 should be retried. 

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

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

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

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

1348 be of type `bytes`. 

1349 """ 

1350 # Create or coerce a protobuf request object. 

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

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

1353 flattened_params = [name] 

1354 has_flattened_params = ( 

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

1356 ) 

1357 if request is not None and has_flattened_params: 

1358 raise ValueError( 

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

1360 "the individual field arguments should be set." 

1361 ) 

1362 

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

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

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

1366 request = cloudtasks.DeleteQueueRequest(request) 

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

1368 # request, apply these. 

1369 if name is not None: 

1370 request.name = name 

1371 

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

1373 # and friendly error handling. 

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

1375 

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

1377 # add these here. 

1378 metadata = tuple(metadata) + ( 

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

1380 ) 

1381 

1382 # Validate the universe domain. 

1383 self._validate_universe_domain() 

1384 

1385 # Send the request. 

1386 rpc( 

1387 request, 

1388 retry=retry, 

1389 timeout=timeout, 

1390 metadata=metadata, 

1391 ) 

1392 

1393 def purge_queue( 

1394 self, 

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

1396 *, 

1397 name: Optional[str] = None, 

1398 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1401 ) -> queue.Queue: 

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

1403 

1404 All tasks created before this method is called are 

1405 permanently deleted. 

1406 

1407 Purge operations can take up to one minute to take 

1408 effect. Tasks might be dispatched before the purge takes 

1409 effect. A purge is irreversible. 

1410 

1411 .. code-block:: python 

1412 

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

1414 # code template only. 

1415 # It will require modifications to work: 

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

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

1418 # client as shown in: 

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

1420 from google.cloud import tasks_v2 

1421 

1422 def sample_purge_queue(): 

1423 # Create a client 

1424 client = tasks_v2.CloudTasksClient() 

1425 

1426 # Initialize request argument(s) 

1427 request = tasks_v2.PurgeQueueRequest( 

1428 name="name_value", 

1429 ) 

1430 

1431 # Make the request 

1432 response = client.purge_queue(request=request) 

1433 

1434 # Handle the response 

1435 print(response) 

1436 

1437 Args: 

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

1439 The request object. Request message for 

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

1441 name (str): 

1442 Required. The queue name. For example: 

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

1444 

1445 This corresponds to the ``name`` field 

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

1447 should not be set. 

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

1449 should be retried. 

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

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

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

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

1454 be of type `bytes`. 

1455 

1456 Returns: 

1457 google.cloud.tasks_v2.types.Queue: 

1458 A queue is a container of related 

1459 tasks. Queues are configured to manage 

1460 how those tasks are dispatched. 

1461 Configurable properties include rate 

1462 limits, retry options, queue types, and 

1463 others. 

1464 

1465 """ 

1466 # Create or coerce a protobuf request object. 

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

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

1469 flattened_params = [name] 

1470 has_flattened_params = ( 

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

1472 ) 

1473 if request is not None and has_flattened_params: 

1474 raise ValueError( 

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

1476 "the individual field arguments should be set." 

1477 ) 

1478 

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

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

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

1482 request = cloudtasks.PurgeQueueRequest(request) 

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

1484 # request, apply these. 

1485 if name is not None: 

1486 request.name = name 

1487 

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

1489 # and friendly error handling. 

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

1491 

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

1493 # add these here. 

1494 metadata = tuple(metadata) + ( 

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

1496 ) 

1497 

1498 # Validate the universe domain. 

1499 self._validate_universe_domain() 

1500 

1501 # Send the request. 

1502 response = rpc( 

1503 request, 

1504 retry=retry, 

1505 timeout=timeout, 

1506 metadata=metadata, 

1507 ) 

1508 

1509 # Done; return the response. 

1510 return response 

1511 

1512 def pause_queue( 

1513 self, 

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

1515 *, 

1516 name: Optional[str] = None, 

1517 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1520 ) -> queue.Queue: 

1521 r"""Pauses the queue. 

1522 

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

1524 until the queue is resumed via 

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

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

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

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

1529 

1530 .. code-block:: python 

1531 

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

1533 # code template only. 

1534 # It will require modifications to work: 

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

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

1537 # client as shown in: 

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

1539 from google.cloud import tasks_v2 

1540 

1541 def sample_pause_queue(): 

1542 # Create a client 

1543 client = tasks_v2.CloudTasksClient() 

1544 

1545 # Initialize request argument(s) 

1546 request = tasks_v2.PauseQueueRequest( 

1547 name="name_value", 

1548 ) 

1549 

1550 # Make the request 

1551 response = client.pause_queue(request=request) 

1552 

1553 # Handle the response 

1554 print(response) 

1555 

1556 Args: 

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

1558 The request object. Request message for 

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

1560 name (str): 

1561 Required. The queue name. For example: 

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

1563 

1564 This corresponds to the ``name`` field 

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

1566 should not be set. 

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

1568 should be retried. 

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

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

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

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

1573 be of type `bytes`. 

1574 

1575 Returns: 

1576 google.cloud.tasks_v2.types.Queue: 

1577 A queue is a container of related 

1578 tasks. Queues are configured to manage 

1579 how those tasks are dispatched. 

1580 Configurable properties include rate 

1581 limits, retry options, queue types, and 

1582 others. 

1583 

1584 """ 

1585 # Create or coerce a protobuf request object. 

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

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

1588 flattened_params = [name] 

1589 has_flattened_params = ( 

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

1591 ) 

1592 if request is not None and has_flattened_params: 

1593 raise ValueError( 

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

1595 "the individual field arguments should be set." 

1596 ) 

1597 

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

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

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

1601 request = cloudtasks.PauseQueueRequest(request) 

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

1603 # request, apply these. 

1604 if name is not None: 

1605 request.name = name 

1606 

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

1608 # and friendly error handling. 

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

1610 

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

1612 # add these here. 

1613 metadata = tuple(metadata) + ( 

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

1615 ) 

1616 

1617 # Validate the universe domain. 

1618 self._validate_universe_domain() 

1619 

1620 # Send the request. 

1621 response = rpc( 

1622 request, 

1623 retry=retry, 

1624 timeout=timeout, 

1625 metadata=metadata, 

1626 ) 

1627 

1628 # Done; return the response. 

1629 return response 

1630 

1631 def resume_queue( 

1632 self, 

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

1634 *, 

1635 name: Optional[str] = None, 

1636 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1639 ) -> queue.Queue: 

1640 r"""Resume a queue. 

1641 

1642 This method resumes a queue after it has been 

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

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

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

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

1647 method it will be set to 

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

1649 

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

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

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

1653 Scaling 

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

1655 

1656 .. code-block:: python 

1657 

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

1659 # code template only. 

1660 # It will require modifications to work: 

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

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

1663 # client as shown in: 

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

1665 from google.cloud import tasks_v2 

1666 

1667 def sample_resume_queue(): 

1668 # Create a client 

1669 client = tasks_v2.CloudTasksClient() 

1670 

1671 # Initialize request argument(s) 

1672 request = tasks_v2.ResumeQueueRequest( 

1673 name="name_value", 

1674 ) 

1675 

1676 # Make the request 

1677 response = client.resume_queue(request=request) 

1678 

1679 # Handle the response 

1680 print(response) 

1681 

1682 Args: 

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

1684 The request object. Request message for 

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

1686 name (str): 

1687 Required. The queue name. For example: 

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

1689 

1690 This corresponds to the ``name`` field 

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

1692 should not be set. 

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

1694 should be retried. 

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

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

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

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

1699 be of type `bytes`. 

1700 

1701 Returns: 

1702 google.cloud.tasks_v2.types.Queue: 

1703 A queue is a container of related 

1704 tasks. Queues are configured to manage 

1705 how those tasks are dispatched. 

1706 Configurable properties include rate 

1707 limits, retry options, queue types, and 

1708 others. 

1709 

1710 """ 

1711 # Create or coerce a protobuf request object. 

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

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

1714 flattened_params = [name] 

1715 has_flattened_params = ( 

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

1717 ) 

1718 if request is not None and has_flattened_params: 

1719 raise ValueError( 

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

1721 "the individual field arguments should be set." 

1722 ) 

1723 

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

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

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

1727 request = cloudtasks.ResumeQueueRequest(request) 

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

1729 # request, apply these. 

1730 if name is not None: 

1731 request.name = name 

1732 

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

1734 # and friendly error handling. 

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

1736 

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

1738 # add these here. 

1739 metadata = tuple(metadata) + ( 

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

1741 ) 

1742 

1743 # Validate the universe domain. 

1744 self._validate_universe_domain() 

1745 

1746 # Send the request. 

1747 response = rpc( 

1748 request, 

1749 retry=retry, 

1750 timeout=timeout, 

1751 metadata=metadata, 

1752 ) 

1753 

1754 # Done; return the response. 

1755 return response 

1756 

1757 def get_iam_policy( 

1758 self, 

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

1760 *, 

1761 resource: Optional[str] = None, 

1762 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1765 ) -> policy_pb2.Policy: 

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

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

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

1769 

1770 Authorization requires the following `Google 

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

1772 specified resource parent: 

1773 

1774 - ``cloudtasks.queues.getIamPolicy`` 

1775 

1776 .. code-block:: python 

1777 

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

1779 # code template only. 

1780 # It will require modifications to work: 

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

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

1783 # client as shown in: 

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

1785 from google.cloud import tasks_v2 

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

1787 

1788 def sample_get_iam_policy(): 

1789 # Create a client 

1790 client = tasks_v2.CloudTasksClient() 

1791 

1792 # Initialize request argument(s) 

1793 request = iam_policy_pb2.GetIamPolicyRequest( 

1794 resource="resource_value", 

1795 ) 

1796 

1797 # Make the request 

1798 response = client.get_iam_policy(request=request) 

1799 

1800 # Handle the response 

1801 print(response) 

1802 

1803 Args: 

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

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

1806 resource (str): 

1807 REQUIRED: The resource for which the 

1808 policy is being requested. See the 

1809 operation documentation for the 

1810 appropriate value for this field. 

1811 

1812 This corresponds to the ``resource`` field 

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

1814 should not be set. 

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

1816 should be retried. 

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

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

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

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

1821 be of type `bytes`. 

1822 

1823 Returns: 

1824 google.iam.v1.policy_pb2.Policy: 

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

1826 controls for Google Cloud resources. 

1827 

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

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

1830 Principals can be user accounts, service accounts, 

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

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

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

1834 

1835 For some types of Google Cloud resources, a binding 

1836 can also specify a condition, which is a logical 

1837 expression that allows access to a resource only if 

1838 the expression evaluates to true. A condition can add 

1839 constraints based on attributes of the request, the 

1840 resource, or both. To learn which resources support 

1841 conditions in their IAM policies, see the [IAM 

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

1843 

1844 **JSON example:** 

1845 

1846 :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 }`\ \` 

1847 

1848 **YAML example:** 

1849 

1850 :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`\ \` 

1851 

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

1853 [IAM 

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

1855 

1856 """ 

1857 # Create or coerce a protobuf request object. 

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

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

1860 flattened_params = [resource] 

1861 has_flattened_params = ( 

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

1863 ) 

1864 if request is not None and has_flattened_params: 

1865 raise ValueError( 

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

1867 "the individual field arguments should be set." 

1868 ) 

1869 

1870 if isinstance(request, dict): 

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

1872 # so it must be constructed via keyword expansion. 

1873 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

1874 elif not request: 

1875 # Null request, just make one. 

1876 request = iam_policy_pb2.GetIamPolicyRequest() 

1877 if resource is not None: 

1878 request.resource = resource 

1879 

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

1881 # and friendly error handling. 

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

1883 

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

1885 # add these here. 

1886 metadata = tuple(metadata) + ( 

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

1888 ) 

1889 

1890 # Validate the universe domain. 

1891 self._validate_universe_domain() 

1892 

1893 # Send the request. 

1894 response = rpc( 

1895 request, 

1896 retry=retry, 

1897 timeout=timeout, 

1898 metadata=metadata, 

1899 ) 

1900 

1901 # Done; return the response. 

1902 return response 

1903 

1904 def set_iam_policy( 

1905 self, 

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

1907 *, 

1908 resource: Optional[str] = None, 

1909 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1912 ) -> policy_pb2.Policy: 

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

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

1915 policy. 

1916 

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

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

1919 the Cloud Console. 

1920 

1921 Authorization requires the following `Google 

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

1923 specified resource parent: 

1924 

1925 - ``cloudtasks.queues.setIamPolicy`` 

1926 

1927 .. code-block:: python 

1928 

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

1930 # code template only. 

1931 # It will require modifications to work: 

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

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

1934 # client as shown in: 

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

1936 from google.cloud import tasks_v2 

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

1938 

1939 def sample_set_iam_policy(): 

1940 # Create a client 

1941 client = tasks_v2.CloudTasksClient() 

1942 

1943 # Initialize request argument(s) 

1944 request = iam_policy_pb2.SetIamPolicyRequest( 

1945 resource="resource_value", 

1946 ) 

1947 

1948 # Make the request 

1949 response = client.set_iam_policy(request=request) 

1950 

1951 # Handle the response 

1952 print(response) 

1953 

1954 Args: 

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

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

1957 resource (str): 

1958 REQUIRED: The resource for which the 

1959 policy is being specified. See the 

1960 operation documentation for the 

1961 appropriate value for this field. 

1962 

1963 This corresponds to the ``resource`` field 

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

1965 should not be set. 

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

1967 should be retried. 

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

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

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

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

1972 be of type `bytes`. 

1973 

1974 Returns: 

1975 google.iam.v1.policy_pb2.Policy: 

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

1977 controls for Google Cloud resources. 

1978 

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

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

1981 Principals can be user accounts, service accounts, 

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

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

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

1985 

1986 For some types of Google Cloud resources, a binding 

1987 can also specify a condition, which is a logical 

1988 expression that allows access to a resource only if 

1989 the expression evaluates to true. A condition can add 

1990 constraints based on attributes of the request, the 

1991 resource, or both. To learn which resources support 

1992 conditions in their IAM policies, see the [IAM 

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

1994 

1995 **JSON example:** 

1996 

1997 :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 }`\ \` 

1998 

1999 **YAML example:** 

2000 

2001 :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`\ \` 

2002 

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

2004 [IAM 

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

2006 

2007 """ 

2008 # Create or coerce a protobuf request object. 

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

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

2011 flattened_params = [resource] 

2012 has_flattened_params = ( 

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

2014 ) 

2015 if request is not None and has_flattened_params: 

2016 raise ValueError( 

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

2018 "the individual field arguments should be set." 

2019 ) 

2020 

2021 if isinstance(request, dict): 

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

2023 # so it must be constructed via keyword expansion. 

2024 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

2025 elif not request: 

2026 # Null request, just make one. 

2027 request = iam_policy_pb2.SetIamPolicyRequest() 

2028 if resource is not None: 

2029 request.resource = resource 

2030 

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

2032 # and friendly error handling. 

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

2034 

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

2036 # add these here. 

2037 metadata = tuple(metadata) + ( 

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

2039 ) 

2040 

2041 # Validate the universe domain. 

2042 self._validate_universe_domain() 

2043 

2044 # Send the request. 

2045 response = rpc( 

2046 request, 

2047 retry=retry, 

2048 timeout=timeout, 

2049 metadata=metadata, 

2050 ) 

2051 

2052 # Done; return the response. 

2053 return response 

2054 

2055 def test_iam_permissions( 

2056 self, 

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

2058 *, 

2059 resource: Optional[str] = None, 

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

2061 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

2064 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

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

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

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

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

2069 

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

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

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

2073 warning. 

2074 

2075 .. code-block:: python 

2076 

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

2078 # code template only. 

2079 # It will require modifications to work: 

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

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

2082 # client as shown in: 

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

2084 from google.cloud import tasks_v2 

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

2086 

2087 def sample_test_iam_permissions(): 

2088 # Create a client 

2089 client = tasks_v2.CloudTasksClient() 

2090 

2091 # Initialize request argument(s) 

2092 request = iam_policy_pb2.TestIamPermissionsRequest( 

2093 resource="resource_value", 

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

2095 ) 

2096 

2097 # Make the request 

2098 response = client.test_iam_permissions(request=request) 

2099 

2100 # Handle the response 

2101 print(response) 

2102 

2103 Args: 

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

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

2106 resource (str): 

2107 REQUIRED: The resource for which the 

2108 policy detail is being requested. See 

2109 the operation documentation for the 

2110 appropriate value for this field. 

2111 

2112 This corresponds to the ``resource`` field 

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

2114 should not be set. 

2115 permissions (MutableSequence[str]): 

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

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

2118 are not allowed. For more information see `IAM 

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

2120 

2121 This corresponds to the ``permissions`` field 

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

2123 should not be set. 

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

2125 should be retried. 

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

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

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

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

2130 be of type `bytes`. 

2131 

2132 Returns: 

2133 google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: 

2134 Response message for TestIamPermissions method. 

2135 """ 

2136 # Create or coerce a protobuf request object. 

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

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

2139 flattened_params = [resource, permissions] 

2140 has_flattened_params = ( 

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

2142 ) 

2143 if request is not None and has_flattened_params: 

2144 raise ValueError( 

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

2146 "the individual field arguments should be set." 

2147 ) 

2148 

2149 if isinstance(request, dict): 

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

2151 # so it must be constructed via keyword expansion. 

2152 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

2153 elif not request: 

2154 # Null request, just make one. 

2155 request = iam_policy_pb2.TestIamPermissionsRequest() 

2156 if resource is not None: 

2157 request.resource = resource 

2158 if permissions: 

2159 request.permissions.extend(permissions) 

2160 

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

2162 # and friendly error handling. 

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

2164 

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

2166 # add these here. 

2167 metadata = tuple(metadata) + ( 

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

2169 ) 

2170 

2171 # Validate the universe domain. 

2172 self._validate_universe_domain() 

2173 

2174 # Send the request. 

2175 response = rpc( 

2176 request, 

2177 retry=retry, 

2178 timeout=timeout, 

2179 metadata=metadata, 

2180 ) 

2181 

2182 # Done; return the response. 

2183 return response 

2184 

2185 def list_tasks( 

2186 self, 

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

2188 *, 

2189 parent: Optional[str] = None, 

2190 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

2193 ) -> pagers.ListTasksPager: 

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

2195 

2196 By default, only the 

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

2198 due to performance considerations; 

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

2200 controls the subset of information which is returned. 

2201 

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

2203 at any time. 

2204 

2205 .. code-block:: python 

2206 

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

2208 # code template only. 

2209 # It will require modifications to work: 

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

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

2212 # client as shown in: 

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

2214 from google.cloud import tasks_v2 

2215 

2216 def sample_list_tasks(): 

2217 # Create a client 

2218 client = tasks_v2.CloudTasksClient() 

2219 

2220 # Initialize request argument(s) 

2221 request = tasks_v2.ListTasksRequest( 

2222 parent="parent_value", 

2223 ) 

2224 

2225 # Make the request 

2226 page_result = client.list_tasks(request=request) 

2227 

2228 # Handle the response 

2229 for response in page_result: 

2230 print(response) 

2231 

2232 Args: 

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

2234 The request object. Request message for listing tasks using 

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

2236 parent (str): 

2237 Required. The queue name. For example: 

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

2239 

2240 This corresponds to the ``parent`` field 

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

2242 should not be set. 

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

2244 should be retried. 

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

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

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

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

2249 be of type `bytes`. 

2250 

2251 Returns: 

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

2253 Response message for listing tasks using 

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

2255 

2256 Iterating over this object will yield results and 

2257 resolve additional pages automatically. 

2258 

2259 """ 

2260 # Create or coerce a protobuf request object. 

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

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

2263 flattened_params = [parent] 

2264 has_flattened_params = ( 

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

2266 ) 

2267 if request is not None and has_flattened_params: 

2268 raise ValueError( 

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

2270 "the individual field arguments should be set." 

2271 ) 

2272 

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

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

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

2276 request = cloudtasks.ListTasksRequest(request) 

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

2278 # request, apply these. 

2279 if parent is not None: 

2280 request.parent = parent 

2281 

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

2283 # and friendly error handling. 

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

2285 

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

2287 # add these here. 

2288 metadata = tuple(metadata) + ( 

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

2290 ) 

2291 

2292 # Validate the universe domain. 

2293 self._validate_universe_domain() 

2294 

2295 # Send the request. 

2296 response = rpc( 

2297 request, 

2298 retry=retry, 

2299 timeout=timeout, 

2300 metadata=metadata, 

2301 ) 

2302 

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

2304 # an `__iter__` convenience method. 

2305 response = pagers.ListTasksPager( 

2306 method=rpc, 

2307 request=request, 

2308 response=response, 

2309 retry=retry, 

2310 timeout=timeout, 

2311 metadata=metadata, 

2312 ) 

2313 

2314 # Done; return the response. 

2315 return response 

2316 

2317 def get_task( 

2318 self, 

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

2320 *, 

2321 name: Optional[str] = None, 

2322 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

2325 ) -> task.Task: 

2326 r"""Gets a task. 

2327 

2328 .. code-block:: python 

2329 

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

2331 # code template only. 

2332 # It will require modifications to work: 

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

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

2335 # client as shown in: 

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

2337 from google.cloud import tasks_v2 

2338 

2339 def sample_get_task(): 

2340 # Create a client 

2341 client = tasks_v2.CloudTasksClient() 

2342 

2343 # Initialize request argument(s) 

2344 request = tasks_v2.GetTaskRequest( 

2345 name="name_value", 

2346 ) 

2347 

2348 # Make the request 

2349 response = client.get_task(request=request) 

2350 

2351 # Handle the response 

2352 print(response) 

2353 

2354 Args: 

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

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

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

2358 name (str): 

2359 Required. The task name. For example: 

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

2361 

2362 This corresponds to the ``name`` field 

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

2364 should not be set. 

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

2366 should be retried. 

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

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

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

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

2371 be of type `bytes`. 

2372 

2373 Returns: 

2374 google.cloud.tasks_v2.types.Task: 

2375 A unit of scheduled work. 

2376 """ 

2377 # Create or coerce a protobuf request object. 

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

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

2380 flattened_params = [name] 

2381 has_flattened_params = ( 

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

2383 ) 

2384 if request is not None and has_flattened_params: 

2385 raise ValueError( 

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

2387 "the individual field arguments should be set." 

2388 ) 

2389 

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

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

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

2393 request = cloudtasks.GetTaskRequest(request) 

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

2395 # request, apply these. 

2396 if name is not None: 

2397 request.name = name 

2398 

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

2400 # and friendly error handling. 

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

2402 

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

2404 # add these here. 

2405 metadata = tuple(metadata) + ( 

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

2407 ) 

2408 

2409 # Validate the universe domain. 

2410 self._validate_universe_domain() 

2411 

2412 # Send the request. 

2413 response = rpc( 

2414 request, 

2415 retry=retry, 

2416 timeout=timeout, 

2417 metadata=metadata, 

2418 ) 

2419 

2420 # Done; return the response. 

2421 return response 

2422 

2423 def create_task( 

2424 self, 

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

2426 *, 

2427 parent: Optional[str] = None, 

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

2429 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

2432 ) -> gct_task.Task: 

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

2434 

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

2436 command. 

2437 

2438 - The maximum task size is 100KB. 

2439 

2440 .. code-block:: python 

2441 

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

2443 # code template only. 

2444 # It will require modifications to work: 

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

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

2447 # client as shown in: 

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

2449 from google.cloud import tasks_v2 

2450 

2451 def sample_create_task(): 

2452 # Create a client 

2453 client = tasks_v2.CloudTasksClient() 

2454 

2455 # Initialize request argument(s) 

2456 request = tasks_v2.CreateTaskRequest( 

2457 parent="parent_value", 

2458 ) 

2459 

2460 # Make the request 

2461 response = client.create_task(request=request) 

2462 

2463 # Handle the response 

2464 print(response) 

2465 

2466 Args: 

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

2468 The request object. Request message for 

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

2470 parent (str): 

2471 Required. The queue name. For example: 

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

2473 

2474 The queue must already exist. 

2475 

2476 This corresponds to the ``parent`` field 

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

2478 should not be set. 

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

2480 Required. The task to add. 

2481 

2482 Task names have the following format: 

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

2484 The user can optionally specify a task 

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

2486 not specified then the system will generate a random 

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

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

2489 

2490 If 

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

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

2493 it to the current time. 

2494 

2495 Task De-duplication: 

2496 

2497 Explicitly specifying a task ID enables task 

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

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

2500 recently then the call will fail with 

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

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

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

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

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

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

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

2508 executed. 

2509 

2510 Because there is an extra lookup cost to identify 

2511 duplicate task names, these 

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

2513 calls have significantly increased latency. Using hashed 

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

2515 is recommended. Choosing task ids that are sequential or 

2516 have sequential prefixes, for example using a timestamp, 

2517 causes an increase in latency and error rates in all 

2518 task commands. The infrastructure relies on an 

2519 approximately uniform distribution of task ids to store 

2520 and serve tasks efficiently. 

2521 

2522 This corresponds to the ``task`` field 

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

2524 should not be set. 

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

2526 should be retried. 

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

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

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

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

2531 be of type `bytes`. 

2532 

2533 Returns: 

2534 google.cloud.tasks_v2.types.Task: 

2535 A unit of scheduled work. 

2536 """ 

2537 # Create or coerce a protobuf request object. 

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

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

2540 flattened_params = [parent, task] 

2541 has_flattened_params = ( 

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

2543 ) 

2544 if request is not None and has_flattened_params: 

2545 raise ValueError( 

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

2547 "the individual field arguments should be set." 

2548 ) 

2549 

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

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

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

2553 request = cloudtasks.CreateTaskRequest(request) 

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

2555 # request, apply these. 

2556 if parent is not None: 

2557 request.parent = parent 

2558 if task is not None: 

2559 request.task = task 

2560 

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

2562 # and friendly error handling. 

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

2564 

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

2566 # add these here. 

2567 metadata = tuple(metadata) + ( 

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

2569 ) 

2570 

2571 # Validate the universe domain. 

2572 self._validate_universe_domain() 

2573 

2574 # Send the request. 

2575 response = rpc( 

2576 request, 

2577 retry=retry, 

2578 timeout=timeout, 

2579 metadata=metadata, 

2580 ) 

2581 

2582 # Done; return the response. 

2583 return response 

2584 

2585 def delete_task( 

2586 self, 

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

2588 *, 

2589 name: Optional[str] = None, 

2590 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

2593 ) -> None: 

2594 r"""Deletes a task. 

2595 

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

2597 A task cannot be deleted if it has executed successfully 

2598 or permanently failed. 

2599 

2600 .. code-block:: python 

2601 

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

2603 # code template only. 

2604 # It will require modifications to work: 

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

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

2607 # client as shown in: 

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

2609 from google.cloud import tasks_v2 

2610 

2611 def sample_delete_task(): 

2612 # Create a client 

2613 client = tasks_v2.CloudTasksClient() 

2614 

2615 # Initialize request argument(s) 

2616 request = tasks_v2.DeleteTaskRequest( 

2617 name="name_value", 

2618 ) 

2619 

2620 # Make the request 

2621 client.delete_task(request=request) 

2622 

2623 Args: 

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

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

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

2627 name (str): 

2628 Required. The task name. For example: 

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

2630 

2631 This corresponds to the ``name`` field 

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

2633 should not be set. 

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

2635 should be retried. 

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

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

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

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

2640 be of type `bytes`. 

2641 """ 

2642 # Create or coerce a protobuf request object. 

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

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

2645 flattened_params = [name] 

2646 has_flattened_params = ( 

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

2648 ) 

2649 if request is not None and has_flattened_params: 

2650 raise ValueError( 

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

2652 "the individual field arguments should be set." 

2653 ) 

2654 

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

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

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

2658 request = cloudtasks.DeleteTaskRequest(request) 

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

2660 # request, apply these. 

2661 if name is not None: 

2662 request.name = name 

2663 

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

2665 # and friendly error handling. 

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

2667 

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

2669 # add these here. 

2670 metadata = tuple(metadata) + ( 

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

2672 ) 

2673 

2674 # Validate the universe domain. 

2675 self._validate_universe_domain() 

2676 

2677 # Send the request. 

2678 rpc( 

2679 request, 

2680 retry=retry, 

2681 timeout=timeout, 

2682 metadata=metadata, 

2683 ) 

2684 

2685 def run_task( 

2686 self, 

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

2688 *, 

2689 name: Optional[str] = None, 

2690 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

2693 ) -> task.Task: 

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

2695 

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

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

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

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

2700 

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

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

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

2704 manually force a task to be dispatched now. 

2705 

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

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

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

2709 

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

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

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

2713 be reset to the time that 

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

2715 plus the retry delay specified in the queue's 

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

2717 

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

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

2720 task that has already succeeded or permanently failed. 

2721 

2722 .. code-block:: python 

2723 

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

2725 # code template only. 

2726 # It will require modifications to work: 

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

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

2729 # client as shown in: 

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

2731 from google.cloud import tasks_v2 

2732 

2733 def sample_run_task(): 

2734 # Create a client 

2735 client = tasks_v2.CloudTasksClient() 

2736 

2737 # Initialize request argument(s) 

2738 request = tasks_v2.RunTaskRequest( 

2739 name="name_value", 

2740 ) 

2741 

2742 # Make the request 

2743 response = client.run_task(request=request) 

2744 

2745 # Handle the response 

2746 print(response) 

2747 

2748 Args: 

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

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

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

2752 name (str): 

2753 Required. The task name. For example: 

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

2755 

2756 This corresponds to the ``name`` field 

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

2758 should not be set. 

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

2760 should be retried. 

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

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

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

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

2765 be of type `bytes`. 

2766 

2767 Returns: 

2768 google.cloud.tasks_v2.types.Task: 

2769 A unit of scheduled work. 

2770 """ 

2771 # Create or coerce a protobuf request object. 

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

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

2774 flattened_params = [name] 

2775 has_flattened_params = ( 

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

2777 ) 

2778 if request is not None and has_flattened_params: 

2779 raise ValueError( 

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

2781 "the individual field arguments should be set." 

2782 ) 

2783 

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

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

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

2787 request = cloudtasks.RunTaskRequest(request) 

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

2789 # request, apply these. 

2790 if name is not None: 

2791 request.name = name 

2792 

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

2794 # and friendly error handling. 

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

2796 

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

2798 # add these here. 

2799 metadata = tuple(metadata) + ( 

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

2801 ) 

2802 

2803 # Validate the universe domain. 

2804 self._validate_universe_domain() 

2805 

2806 # Send the request. 

2807 response = rpc( 

2808 request, 

2809 retry=retry, 

2810 timeout=timeout, 

2811 metadata=metadata, 

2812 ) 

2813 

2814 # Done; return the response. 

2815 return response 

2816 

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

2818 return self 

2819 

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

2821 """Releases underlying transport's resources. 

2822 

2823 .. warning:: 

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

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

2826 and may cause errors in other clients! 

2827 """ 

2828 self.transport.close() 

2829 

2830 def get_location( 

2831 self, 

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

2833 *, 

2834 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

2837 ) -> locations_pb2.Location: 

2838 r"""Gets information about a location. 

2839 

2840 Args: 

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

2842 The request object. Request message for 

2843 `GetLocation` method. 

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

2845 if any, should be retried. 

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

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

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

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

2850 be of type `bytes`. 

2851 Returns: 

2852 ~.location_pb2.Location: 

2853 Location object. 

2854 """ 

2855 # Create or coerce a protobuf request object. 

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

2857 # so it must be constructed via keyword expansion. 

2858 if isinstance(request, dict): 

2859 request = locations_pb2.GetLocationRequest(**request) 

2860 

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

2862 # and friendly error handling. 

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

2864 

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

2866 # add these here. 

2867 metadata = tuple(metadata) + ( 

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

2869 ) 

2870 

2871 # Validate the universe domain. 

2872 self._validate_universe_domain() 

2873 

2874 try: 

2875 # Send the request. 

2876 response = rpc( 

2877 request, 

2878 retry=retry, 

2879 timeout=timeout, 

2880 metadata=metadata, 

2881 ) 

2882 

2883 # Done; return the response. 

2884 return response 

2885 except core_exceptions.GoogleAPICallError as e: 

2886 self._add_cred_info_for_auth_errors(e) 

2887 raise e 

2888 

2889 def list_locations( 

2890 self, 

2891 request: Optional[locations_pb2.ListLocationsRequest] = None, 

2892 *, 

2893 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

2896 ) -> locations_pb2.ListLocationsResponse: 

2897 r"""Lists information about the supported locations for this service. 

2898 

2899 Args: 

2900 request (:class:`~.location_pb2.ListLocationsRequest`): 

2901 The request object. Request message for 

2902 `ListLocations` method. 

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

2904 if any, should be retried. 

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

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

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

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

2909 be of type `bytes`. 

2910 Returns: 

2911 ~.location_pb2.ListLocationsResponse: 

2912 Response message for ``ListLocations`` method. 

2913 """ 

2914 # Create or coerce a protobuf request object. 

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

2916 # so it must be constructed via keyword expansion. 

2917 if isinstance(request, dict): 

2918 request = locations_pb2.ListLocationsRequest(**request) 

2919 

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

2921 # and friendly error handling. 

2922 rpc = self._transport._wrapped_methods[self._transport.list_locations] 

2923 

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

2925 # add these here. 

2926 metadata = tuple(metadata) + ( 

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

2928 ) 

2929 

2930 # Validate the universe domain. 

2931 self._validate_universe_domain() 

2932 

2933 try: 

2934 # Send the request. 

2935 response = rpc( 

2936 request, 

2937 retry=retry, 

2938 timeout=timeout, 

2939 metadata=metadata, 

2940 ) 

2941 

2942 # Done; return the response. 

2943 return response 

2944 except core_exceptions.GoogleAPICallError as e: 

2945 self._add_cred_info_for_auth_errors(e) 

2946 raise e 

2947 

2948 

2949DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

2950 gapic_version=package_version.__version__ 

2951) 

2952 

2953if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER 

2954 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

2955 

2956__all__ = ("CloudTasksClient",)