Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/google/pubsub_v1/services/publisher/async_client.py: 36%

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

232 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# 

16import logging as std_logging 

17from collections import OrderedDict 

18import re 

19from typing import ( 

20 Dict, 

21 Callable, 

22 Mapping, 

23 MutableMapping, 

24 MutableSequence, 

25 Optional, 

26 Sequence, 

27 Tuple, 

28 Type, 

29 Union, 

30) 

31 

32from google.pubsub_v1 import gapic_version as package_version 

33 

34from google.api_core.client_options import ClientOptions 

35from google.api_core import exceptions as core_exceptions 

36from google.api_core import gapic_v1 

37from google.api_core import retry_async as retries 

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

39from google.oauth2 import service_account # type: ignore 

40import google.protobuf 

41 

42 

43try: 

44 OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] 

45except AttributeError: # pragma: NO COVER 

46 OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore 

47 

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

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

50from google.protobuf import duration_pb2 # type: ignore 

51from google.protobuf import field_mask_pb2 # type: ignore 

52from google.pubsub_v1.services.publisher import pagers 

53from google.pubsub_v1.types import pubsub 

54from google.pubsub_v1.types import TimeoutType 

55from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO 

56from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport 

57from .client import PublisherClient 

58 

59try: 

60 from google.api_core import client_logging # type: ignore 

61 

62 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

63except ImportError: # pragma: NO COVER 

64 CLIENT_LOGGING_SUPPORTED = False 

65 

66_LOGGER = std_logging.getLogger(__name__) 

67 

68 

69class PublisherAsyncClient: 

70 """The service that an application uses to manipulate topics, 

71 and to send messages to a topic. 

72 """ 

73 

74 _client: PublisherClient 

75 

76 # Copy defaults from the synchronous client for use here. 

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

78 DEFAULT_ENDPOINT = PublisherClient.DEFAULT_ENDPOINT 

79 DEFAULT_MTLS_ENDPOINT = PublisherClient.DEFAULT_MTLS_ENDPOINT 

80 _DEFAULT_ENDPOINT_TEMPLATE = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE 

81 _DEFAULT_UNIVERSE = PublisherClient._DEFAULT_UNIVERSE 

82 

83 crypto_key_path = staticmethod(PublisherClient.crypto_key_path) 

84 parse_crypto_key_path = staticmethod(PublisherClient.parse_crypto_key_path) 

85 schema_path = staticmethod(PublisherClient.schema_path) 

86 parse_schema_path = staticmethod(PublisherClient.parse_schema_path) 

87 snapshot_path = staticmethod(PublisherClient.snapshot_path) 

88 parse_snapshot_path = staticmethod(PublisherClient.parse_snapshot_path) 

89 subscription_path = staticmethod(PublisherClient.subscription_path) 

90 parse_subscription_path = staticmethod(PublisherClient.parse_subscription_path) 

91 topic_path = staticmethod(PublisherClient.topic_path) 

92 parse_topic_path = staticmethod(PublisherClient.parse_topic_path) 

93 common_billing_account_path = staticmethod( 

94 PublisherClient.common_billing_account_path 

95 ) 

96 parse_common_billing_account_path = staticmethod( 

97 PublisherClient.parse_common_billing_account_path 

98 ) 

99 common_folder_path = staticmethod(PublisherClient.common_folder_path) 

100 parse_common_folder_path = staticmethod(PublisherClient.parse_common_folder_path) 

101 common_organization_path = staticmethod(PublisherClient.common_organization_path) 

102 parse_common_organization_path = staticmethod( 

103 PublisherClient.parse_common_organization_path 

104 ) 

105 common_project_path = staticmethod(PublisherClient.common_project_path) 

106 parse_common_project_path = staticmethod(PublisherClient.parse_common_project_path) 

107 common_location_path = staticmethod(PublisherClient.common_location_path) 

108 parse_common_location_path = staticmethod( 

109 PublisherClient.parse_common_location_path 

110 ) 

111 

112 @classmethod 

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

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

115 info. 

116 

117 Args: 

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

119 args: Additional arguments to pass to the constructor. 

120 kwargs: Additional arguments to pass to the constructor. 

121 

122 Returns: 

123 PublisherAsyncClient: The constructed client. 

124 """ 

125 return PublisherClient.from_service_account_info.__func__(PublisherAsyncClient, info, *args, **kwargs) # type: ignore 

126 

127 @classmethod 

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

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

130 file. 

131 

132 Args: 

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

134 file. 

135 args: Additional arguments to pass to the constructor. 

136 kwargs: Additional arguments to pass to the constructor. 

137 

138 Returns: 

139 PublisherAsyncClient: The constructed client. 

140 """ 

141 return PublisherClient.from_service_account_file.__func__(PublisherAsyncClient, filename, *args, **kwargs) # type: ignore 

142 

143 from_service_account_json = from_service_account_file 

144 

145 @classmethod 

146 def get_mtls_endpoint_and_cert_source( 

147 cls, client_options: Optional[ClientOptions] = None 

148 ): 

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

150 

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

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

153 client cert source is None. 

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

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

156 source is None. 

157 

158 The API endpoint is determined in the following order: 

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

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

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

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

163 use the default API endpoint. 

164 

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

166 

167 Args: 

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

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

170 in this method. 

171 

172 Returns: 

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

174 client cert source to use. 

175 

176 Raises: 

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

178 """ 

179 return PublisherClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore 

180 

181 @property 

182 def transport(self) -> PublisherTransport: 

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

184 

185 Returns: 

186 PublisherTransport: The transport used by the client instance. 

187 """ 

188 return self._client.transport 

189 

190 @property 

191 def api_endpoint(self): 

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

193 

194 Returns: 

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

196 """ 

197 return self._client._api_endpoint 

198 

199 @property 

200 def universe_domain(self) -> str: 

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

202 

203 Returns: 

204 str: The universe domain used 

205 by the client instance. 

206 """ 

207 return self._client._universe_domain 

208 

209 get_transport_class = PublisherClient.get_transport_class 

210 

211 def __init__( 

212 self, 

213 *, 

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

215 transport: Optional[ 

216 Union[str, PublisherTransport, Callable[..., PublisherTransport]] 

217 ] = "grpc_asyncio", 

218 client_options: Optional[ClientOptions] = None, 

219 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

220 ) -> None: 

221 """Instantiates the publisher async client. 

222 

223 Args: 

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

225 authorization credentials to attach to requests. These 

226 credentials identify the application to the service; if none 

227 are specified, the client will attempt to ascertain the 

228 credentials from the environment. 

229 transport (Optional[Union[str,PublisherTransport,Callable[..., PublisherTransport]]]): 

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

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

232 arguments as used in the PublisherTransport constructor. 

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

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

235 Custom options for the client. 

236 

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

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

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

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

241 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

242 variable, which have one of the following values: 

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

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

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

246 the default value). 

247 

248 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

250 to provide a client certificate for mTLS transport. If 

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

252 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

253 set, no client certificate will be used. 

254 

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

256 default "googleapis.com" universe. Note that ``api_endpoint`` 

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

258 currently not supported for mTLS. 

259 

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

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

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

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

264 your own client library. 

265 

266 Raises: 

267 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport 

268 creation failed for any reason. 

269 """ 

270 self._client = PublisherClient( 

271 credentials=credentials, 

272 transport=transport, 

273 client_options=client_options, 

274 client_info=client_info, 

275 ) 

276 

277 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

278 std_logging.DEBUG 

279 ): # pragma: NO COVER 

280 _LOGGER.debug( 

281 "Created client `google.pubsub_v1.PublisherAsyncClient`.", 

282 extra={ 

283 "serviceName": "google.pubsub.v1.Publisher", 

284 "universeDomain": getattr( 

285 self._client._transport._credentials, "universe_domain", "" 

286 ), 

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

288 "credentialsInfo": getattr( 

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

290 )(), 

291 } 

292 if hasattr(self._client._transport, "_credentials") 

293 else { 

294 "serviceName": "google.pubsub.v1.Publisher", 

295 "credentialsType": None, 

296 }, 

297 ) 

298 

299 async def create_topic( 

300 self, 

301 request: Optional[Union[pubsub.Topic, dict]] = None, 

302 *, 

303 name: Optional[str] = None, 

304 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

305 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

307 ) -> pubsub.Topic: 

308 r"""Creates the given topic with the given name. See the [resource 

309 name rules] 

310 (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). 

311 

312 .. code-block:: python 

313 

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

315 # code template only. 

316 # It will require modifications to work: 

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

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

319 # client as shown in: 

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

321 from google import pubsub_v1 

322 

323 async def sample_create_topic(): 

324 # Create a client 

325 client = pubsub_v1.PublisherAsyncClient() 

326 

327 # Initialize request argument(s) 

328 request = pubsub_v1.Topic( 

329 name="name_value", 

330 ) 

331 

332 # Make the request 

333 response = await client.create_topic(request=request) 

334 

335 # Handle the response 

336 print(response) 

337 

338 Args: 

339 request (Optional[Union[google.pubsub_v1.types.Topic, dict]]): 

340 The request object. A topic resource. 

341 name (:class:`str`): 

342 Required. The name of the topic. It must have the format 

343 ``"projects/{project}/topics/{topic}"``. ``{topic}`` 

344 must start with a letter, and contain only letters 

345 (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), 

346 underscores (``_``), periods (``.``), tildes (``~``), 

347 plus (``+``) or percent signs (``%``). It must be 

348 between 3 and 255 characters in length, and it must not 

349 start with ``"goog"``. 

350 

351 This corresponds to the ``name`` field 

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

353 should not be set. 

354 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

355 should be retried. 

356 timeout (TimeoutType): 

357 The timeout for this request. 

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

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

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

361 be of type `bytes`. 

362 

363 Returns: 

364 google.pubsub_v1.types.Topic: 

365 A topic resource. 

366 """ 

367 # Create or coerce a protobuf request object. 

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

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

370 flattened_params = [name] 

371 has_flattened_params = ( 

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

373 ) 

374 if request is not None and has_flattened_params: 

375 raise ValueError( 

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

377 "the individual field arguments should be set." 

378 ) 

379 

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

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

382 if not isinstance(request, pubsub.Topic): 

383 request = pubsub.Topic(request) 

384 

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

386 # request, apply these. 

387 if name is not None: 

388 request.name = name 

389 

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

391 # and friendly error handling. 

392 rpc = self._client._transport._wrapped_methods[ 

393 self._client._transport.create_topic 

394 ] 

395 

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

397 # add these here. 

398 metadata = tuple(metadata) + ( 

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

400 ) 

401 

402 # Validate the universe domain. 

403 self._client._validate_universe_domain() 

404 

405 # Send the request. 

406 response = await rpc( 

407 request, 

408 retry=retry, 

409 timeout=timeout, 

410 metadata=metadata, 

411 ) 

412 

413 # Done; return the response. 

414 return response 

415 

416 async def update_topic( 

417 self, 

418 request: Optional[Union[pubsub.UpdateTopicRequest, dict]] = None, 

419 *, 

420 topic: Optional[pubsub.Topic] = None, 

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

422 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

423 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

425 ) -> pubsub.Topic: 

426 r"""Updates an existing topic by updating the fields 

427 specified in the update mask. Note that certain 

428 properties of a topic are not modifiable. 

429 

430 .. code-block:: python 

431 

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

433 # code template only. 

434 # It will require modifications to work: 

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

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

437 # client as shown in: 

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

439 from google import pubsub_v1 

440 

441 async def sample_update_topic(): 

442 # Create a client 

443 client = pubsub_v1.PublisherAsyncClient() 

444 

445 # Initialize request argument(s) 

446 topic = pubsub_v1.Topic() 

447 topic.name = "name_value" 

448 

449 request = pubsub_v1.UpdateTopicRequest( 

450 topic=topic, 

451 ) 

452 

453 # Make the request 

454 response = await client.update_topic(request=request) 

455 

456 # Handle the response 

457 print(response) 

458 

459 Args: 

460 request (Optional[Union[google.pubsub_v1.types.UpdateTopicRequest, dict]]): 

461 The request object. Request for the UpdateTopic method. 

462 topic (:class:`google.pubsub_v1.types.Topic`): 

463 Required. The updated topic object. 

464 This corresponds to the ``topic`` field 

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

466 should not be set. 

467 update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): 

468 Required. Indicates which fields in the provided topic 

469 to update. Must be specified and non-empty. Note that if 

470 ``update_mask`` contains "message_storage_policy" but 

471 the ``message_storage_policy`` is not set in the 

472 ``topic`` provided above, then the updated value is 

473 determined by the policy configured at the project or 

474 organization level. 

475 

476 This corresponds to the ``update_mask`` field 

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

478 should not be set. 

479 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

480 should be retried. 

481 timeout (TimeoutType): 

482 The timeout for this request. 

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

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

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

486 be of type `bytes`. 

487 

488 Returns: 

489 google.pubsub_v1.types.Topic: 

490 A topic resource. 

491 """ 

492 # Create or coerce a protobuf request object. 

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

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

495 flattened_params = [topic, update_mask] 

496 has_flattened_params = ( 

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

498 ) 

499 if request is not None and has_flattened_params: 

500 raise ValueError( 

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

502 "the individual field arguments should be set." 

503 ) 

504 

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

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

507 if not isinstance(request, pubsub.UpdateTopicRequest): 

508 request = pubsub.UpdateTopicRequest(request) 

509 

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

511 # request, apply these. 

512 if topic is not None: 

513 request.topic = topic 

514 if update_mask is not None: 

515 request.update_mask = update_mask 

516 

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

518 # and friendly error handling. 

519 rpc = self._client._transport._wrapped_methods[ 

520 self._client._transport.update_topic 

521 ] 

522 

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

524 # add these here. 

525 metadata = tuple(metadata) + ( 

526 gapic_v1.routing_header.to_grpc_metadata( 

527 (("topic.name", request.topic.name),) 

528 ), 

529 ) 

530 

531 # Validate the universe domain. 

532 self._client._validate_universe_domain() 

533 

534 # Send the request. 

535 response = await rpc( 

536 request, 

537 retry=retry, 

538 timeout=timeout, 

539 metadata=metadata, 

540 ) 

541 

542 # Done; return the response. 

543 return response 

544 

545 async def publish( 

546 self, 

547 request: Optional[Union[pubsub.PublishRequest, dict]] = None, 

548 *, 

549 topic: Optional[str] = None, 

550 messages: Optional[MutableSequence[pubsub.PubsubMessage]] = None, 

551 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

552 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

554 ) -> pubsub.PublishResponse: 

555 r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if 

556 the topic does not exist. 

557 

558 .. code-block:: python 

559 

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

561 # code template only. 

562 # It will require modifications to work: 

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

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

565 # client as shown in: 

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

567 from google import pubsub_v1 

568 

569 async def sample_publish(): 

570 # Create a client 

571 client = pubsub_v1.PublisherAsyncClient() 

572 

573 # Initialize request argument(s) 

574 request = pubsub_v1.PublishRequest( 

575 topic="topic_value", 

576 ) 

577 

578 # Make the request 

579 response = await client.publish(request=request) 

580 

581 # Handle the response 

582 print(response) 

583 

584 Args: 

585 request (Optional[Union[google.pubsub_v1.types.PublishRequest, dict]]): 

586 The request object. Request for the Publish method. 

587 topic (:class:`str`): 

588 Required. The messages in the request will be published 

589 on this topic. Format is 

590 ``projects/{project}/topics/{topic}``. 

591 

592 This corresponds to the ``topic`` field 

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

594 should not be set. 

595 messages (:class:`MutableSequence[google.pubsub_v1.types.PubsubMessage]`): 

596 Required. The messages to publish. 

597 This corresponds to the ``messages`` field 

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

599 should not be set. 

600 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

601 should be retried. 

602 timeout (TimeoutType): 

603 The timeout for this request. 

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

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

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

607 be of type `bytes`. 

608 

609 Returns: 

610 google.pubsub_v1.types.PublishResponse: 

611 Response for the Publish method. 

612 """ 

613 # Create or coerce a protobuf request object. 

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

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

616 flattened_params = [topic, messages] 

617 has_flattened_params = ( 

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

619 ) 

620 if request is not None and has_flattened_params: 

621 raise ValueError( 

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

623 "the individual field arguments should be set." 

624 ) 

625 

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

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

628 if not isinstance(request, pubsub.PublishRequest): 

629 request = pubsub.PublishRequest(request) 

630 

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

632 # request, apply these. 

633 if topic is not None: 

634 request.topic = topic 

635 if messages: 

636 request.messages.extend(messages) 

637 

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

639 # and friendly error handling. 

640 rpc = self._client._transport._wrapped_methods[self._client._transport.publish] 

641 

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

643 # add these here. 

644 metadata = tuple(metadata) + ( 

645 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

646 ) 

647 

648 # Validate the universe domain. 

649 self._client._validate_universe_domain() 

650 

651 # Send the request. 

652 response = await rpc( 

653 request, 

654 retry=retry, 

655 timeout=timeout, 

656 metadata=metadata, 

657 ) 

658 

659 # Done; return the response. 

660 return response 

661 

662 async def get_topic( 

663 self, 

664 request: Optional[Union[pubsub.GetTopicRequest, dict]] = None, 

665 *, 

666 topic: Optional[str] = None, 

667 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

668 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

670 ) -> pubsub.Topic: 

671 r"""Gets the configuration of a topic. 

672 

673 .. code-block:: python 

674 

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

676 # code template only. 

677 # It will require modifications to work: 

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

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

680 # client as shown in: 

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

682 from google import pubsub_v1 

683 

684 async def sample_get_topic(): 

685 # Create a client 

686 client = pubsub_v1.PublisherAsyncClient() 

687 

688 # Initialize request argument(s) 

689 request = pubsub_v1.GetTopicRequest( 

690 topic="topic_value", 

691 ) 

692 

693 # Make the request 

694 response = await client.get_topic(request=request) 

695 

696 # Handle the response 

697 print(response) 

698 

699 Args: 

700 request (Optional[Union[google.pubsub_v1.types.GetTopicRequest, dict]]): 

701 The request object. Request for the GetTopic method. 

702 topic (:class:`str`): 

703 Required. The name of the topic to get. Format is 

704 ``projects/{project}/topics/{topic}``. 

705 

706 This corresponds to the ``topic`` field 

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

708 should not be set. 

709 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

710 should be retried. 

711 timeout (TimeoutType): 

712 The timeout for this request. 

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

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

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

716 be of type `bytes`. 

717 

718 Returns: 

719 google.pubsub_v1.types.Topic: 

720 A topic resource. 

721 """ 

722 # Create or coerce a protobuf request object. 

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

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

725 flattened_params = [topic] 

726 has_flattened_params = ( 

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

728 ) 

729 if request is not None and has_flattened_params: 

730 raise ValueError( 

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

732 "the individual field arguments should be set." 

733 ) 

734 

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

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

737 if not isinstance(request, pubsub.GetTopicRequest): 

738 request = pubsub.GetTopicRequest(request) 

739 

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

741 # request, apply these. 

742 if topic is not None: 

743 request.topic = topic 

744 

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

746 # and friendly error handling. 

747 rpc = self._client._transport._wrapped_methods[ 

748 self._client._transport.get_topic 

749 ] 

750 

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

752 # add these here. 

753 metadata = tuple(metadata) + ( 

754 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

755 ) 

756 

757 # Validate the universe domain. 

758 self._client._validate_universe_domain() 

759 

760 # Send the request. 

761 response = await rpc( 

762 request, 

763 retry=retry, 

764 timeout=timeout, 

765 metadata=metadata, 

766 ) 

767 

768 # Done; return the response. 

769 return response 

770 

771 async def list_topics( 

772 self, 

773 request: Optional[Union[pubsub.ListTopicsRequest, dict]] = None, 

774 *, 

775 project: Optional[str] = None, 

776 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

777 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

779 ) -> pagers.ListTopicsAsyncPager: 

780 r"""Lists matching topics. 

781 

782 .. code-block:: python 

783 

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

785 # code template only. 

786 # It will require modifications to work: 

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

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

789 # client as shown in: 

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

791 from google import pubsub_v1 

792 

793 async def sample_list_topics(): 

794 # Create a client 

795 client = pubsub_v1.PublisherAsyncClient() 

796 

797 # Initialize request argument(s) 

798 request = pubsub_v1.ListTopicsRequest( 

799 project="project_value", 

800 ) 

801 

802 # Make the request 

803 page_result = client.list_topics(request=request) 

804 

805 # Handle the response 

806 async for response in page_result: 

807 print(response) 

808 

809 Args: 

810 request (Optional[Union[google.pubsub_v1.types.ListTopicsRequest, dict]]): 

811 The request object. Request for the ``ListTopics`` method. 

812 project (:class:`str`): 

813 Required. The name of the project in which to list 

814 topics. Format is ``projects/{project-id}``. 

815 

816 This corresponds to the ``project`` field 

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

818 should not be set. 

819 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

820 should be retried. 

821 timeout (TimeoutType): 

822 The timeout for this request. 

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

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

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

826 be of type `bytes`. 

827 

828 Returns: 

829 google.pubsub_v1.services.publisher.pagers.ListTopicsAsyncPager: 

830 Response for the ListTopics method. 

831 

832 Iterating over this object will yield results and 

833 resolve additional pages automatically. 

834 

835 """ 

836 # Create or coerce a protobuf request object. 

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

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

839 flattened_params = [project] 

840 has_flattened_params = ( 

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

842 ) 

843 if request is not None and has_flattened_params: 

844 raise ValueError( 

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

846 "the individual field arguments should be set." 

847 ) 

848 

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

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

851 if not isinstance(request, pubsub.ListTopicsRequest): 

852 request = pubsub.ListTopicsRequest(request) 

853 

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

855 # request, apply these. 

856 if project is not None: 

857 request.project = project 

858 

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

860 # and friendly error handling. 

861 rpc = self._client._transport._wrapped_methods[ 

862 self._client._transport.list_topics 

863 ] 

864 

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

866 # add these here. 

867 metadata = tuple(metadata) + ( 

868 gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), 

869 ) 

870 

871 # Validate the universe domain. 

872 self._client._validate_universe_domain() 

873 

874 # Send the request. 

875 response = await rpc( 

876 request, 

877 retry=retry, 

878 timeout=timeout, 

879 metadata=metadata, 

880 ) 

881 

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

883 # an `__aiter__` convenience method. 

884 response = pagers.ListTopicsAsyncPager( 

885 method=rpc, 

886 request=request, 

887 response=response, 

888 retry=retry, 

889 timeout=timeout, 

890 metadata=metadata, 

891 ) 

892 

893 # Done; return the response. 

894 return response 

895 

896 async def list_topic_subscriptions( 

897 self, 

898 request: Optional[Union[pubsub.ListTopicSubscriptionsRequest, dict]] = None, 

899 *, 

900 topic: Optional[str] = None, 

901 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

902 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

904 ) -> pagers.ListTopicSubscriptionsAsyncPager: 

905 r"""Lists the names of the attached subscriptions on this 

906 topic. 

907 

908 .. code-block:: python 

909 

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

911 # code template only. 

912 # It will require modifications to work: 

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

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

915 # client as shown in: 

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

917 from google import pubsub_v1 

918 

919 async def sample_list_topic_subscriptions(): 

920 # Create a client 

921 client = pubsub_v1.PublisherAsyncClient() 

922 

923 # Initialize request argument(s) 

924 request = pubsub_v1.ListTopicSubscriptionsRequest( 

925 topic="topic_value", 

926 ) 

927 

928 # Make the request 

929 page_result = client.list_topic_subscriptions(request=request) 

930 

931 # Handle the response 

932 async for response in page_result: 

933 print(response) 

934 

935 Args: 

936 request (Optional[Union[google.pubsub_v1.types.ListTopicSubscriptionsRequest, dict]]): 

937 The request object. Request for the ``ListTopicSubscriptions`` method. 

938 topic (:class:`str`): 

939 Required. The name of the topic that subscriptions are 

940 attached to. Format is 

941 ``projects/{project}/topics/{topic}``. 

942 

943 This corresponds to the ``topic`` field 

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

945 should not be set. 

946 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

947 should be retried. 

948 timeout (TimeoutType): 

949 The timeout for this request. 

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

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

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

953 be of type `bytes`. 

954 

955 Returns: 

956 google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsAsyncPager: 

957 Response for the ListTopicSubscriptions method. 

958 

959 Iterating over this object will yield results and 

960 resolve additional pages automatically. 

961 

962 """ 

963 # Create or coerce a protobuf request object. 

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

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

966 flattened_params = [topic] 

967 has_flattened_params = ( 

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

969 ) 

970 if request is not None and has_flattened_params: 

971 raise ValueError( 

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

973 "the individual field arguments should be set." 

974 ) 

975 

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

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

978 if not isinstance(request, pubsub.ListTopicSubscriptionsRequest): 

979 request = pubsub.ListTopicSubscriptionsRequest(request) 

980 

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

982 # request, apply these. 

983 if topic is not None: 

984 request.topic = topic 

985 

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

987 # and friendly error handling. 

988 rpc = self._client._transport._wrapped_methods[ 

989 self._client._transport.list_topic_subscriptions 

990 ] 

991 

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

993 # add these here. 

994 metadata = tuple(metadata) + ( 

995 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

996 ) 

997 

998 # Validate the universe domain. 

999 self._client._validate_universe_domain() 

1000 

1001 # Send the request. 

1002 response = await rpc( 

1003 request, 

1004 retry=retry, 

1005 timeout=timeout, 

1006 metadata=metadata, 

1007 ) 

1008 

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

1010 # an `__aiter__` convenience method. 

1011 response = pagers.ListTopicSubscriptionsAsyncPager( 

1012 method=rpc, 

1013 request=request, 

1014 response=response, 

1015 retry=retry, 

1016 timeout=timeout, 

1017 metadata=metadata, 

1018 ) 

1019 

1020 # Done; return the response. 

1021 return response 

1022 

1023 async def list_topic_snapshots( 

1024 self, 

1025 request: Optional[Union[pubsub.ListTopicSnapshotsRequest, dict]] = None, 

1026 *, 

1027 topic: Optional[str] = None, 

1028 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1029 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1031 ) -> pagers.ListTopicSnapshotsAsyncPager: 

1032 r"""Lists the names of the snapshots on this topic. Snapshots are 

1033 used in 

1034 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__ 

1035 operations, which allow you to manage message acknowledgments in 

1036 bulk. That is, you can set the acknowledgment state of messages 

1037 in an existing subscription to the state captured by a snapshot. 

1038 

1039 .. code-block:: python 

1040 

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

1042 # code template only. 

1043 # It will require modifications to work: 

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

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

1046 # client as shown in: 

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

1048 from google import pubsub_v1 

1049 

1050 async def sample_list_topic_snapshots(): 

1051 # Create a client 

1052 client = pubsub_v1.PublisherAsyncClient() 

1053 

1054 # Initialize request argument(s) 

1055 request = pubsub_v1.ListTopicSnapshotsRequest( 

1056 topic="topic_value", 

1057 ) 

1058 

1059 # Make the request 

1060 page_result = client.list_topic_snapshots(request=request) 

1061 

1062 # Handle the response 

1063 async for response in page_result: 

1064 print(response) 

1065 

1066 Args: 

1067 request (Optional[Union[google.pubsub_v1.types.ListTopicSnapshotsRequest, dict]]): 

1068 The request object. Request for the ``ListTopicSnapshots`` method. 

1069 topic (:class:`str`): 

1070 Required. The name of the topic that snapshots are 

1071 attached to. Format is 

1072 ``projects/{project}/topics/{topic}``. 

1073 

1074 This corresponds to the ``topic`` field 

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

1076 should not be set. 

1077 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

1078 should be retried. 

1079 timeout (TimeoutType): 

1080 The timeout for this request. 

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

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

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

1084 be of type `bytes`. 

1085 

1086 Returns: 

1087 google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsAsyncPager: 

1088 Response for the ListTopicSnapshots method. 

1089 

1090 Iterating over this object will yield results and 

1091 resolve additional pages automatically. 

1092 

1093 """ 

1094 # Create or coerce a protobuf request object. 

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

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

1097 flattened_params = [topic] 

1098 has_flattened_params = ( 

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

1100 ) 

1101 if request is not None and has_flattened_params: 

1102 raise ValueError( 

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

1104 "the individual field arguments should be set." 

1105 ) 

1106 

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

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

1109 if not isinstance(request, pubsub.ListTopicSnapshotsRequest): 

1110 request = pubsub.ListTopicSnapshotsRequest(request) 

1111 

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

1113 # request, apply these. 

1114 if topic is not None: 

1115 request.topic = topic 

1116 

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

1118 # and friendly error handling. 

1119 rpc = self._client._transport._wrapped_methods[ 

1120 self._client._transport.list_topic_snapshots 

1121 ] 

1122 

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

1124 # add these here. 

1125 metadata = tuple(metadata) + ( 

1126 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

1127 ) 

1128 

1129 # Validate the universe domain. 

1130 self._client._validate_universe_domain() 

1131 

1132 # Send the request. 

1133 response = await rpc( 

1134 request, 

1135 retry=retry, 

1136 timeout=timeout, 

1137 metadata=metadata, 

1138 ) 

1139 

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

1141 # an `__aiter__` convenience method. 

1142 response = pagers.ListTopicSnapshotsAsyncPager( 

1143 method=rpc, 

1144 request=request, 

1145 response=response, 

1146 retry=retry, 

1147 timeout=timeout, 

1148 metadata=metadata, 

1149 ) 

1150 

1151 # Done; return the response. 

1152 return response 

1153 

1154 async def delete_topic( 

1155 self, 

1156 request: Optional[Union[pubsub.DeleteTopicRequest, dict]] = None, 

1157 *, 

1158 topic: Optional[str] = None, 

1159 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1160 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1162 ) -> None: 

1163 r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if 

1164 the topic does not exist. After a topic is deleted, a new topic 

1165 may be created with the same name; this is an entirely new topic 

1166 with none of the old configuration or subscriptions. Existing 

1167 subscriptions to this topic are not deleted, but their ``topic`` 

1168 field is set to ``_deleted-topic_``. 

1169 

1170 .. code-block:: python 

1171 

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

1173 # code template only. 

1174 # It will require modifications to work: 

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

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

1177 # client as shown in: 

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

1179 from google import pubsub_v1 

1180 

1181 async def sample_delete_topic(): 

1182 # Create a client 

1183 client = pubsub_v1.PublisherAsyncClient() 

1184 

1185 # Initialize request argument(s) 

1186 request = pubsub_v1.DeleteTopicRequest( 

1187 topic="topic_value", 

1188 ) 

1189 

1190 # Make the request 

1191 await client.delete_topic(request=request) 

1192 

1193 Args: 

1194 request (Optional[Union[google.pubsub_v1.types.DeleteTopicRequest, dict]]): 

1195 The request object. Request for the ``DeleteTopic`` method. 

1196 topic (:class:`str`): 

1197 Required. Name of the topic to delete. Format is 

1198 ``projects/{project}/topics/{topic}``. 

1199 

1200 This corresponds to the ``topic`` field 

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

1202 should not be set. 

1203 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

1204 should be retried. 

1205 timeout (TimeoutType): 

1206 The timeout for this request. 

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

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

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

1210 be of type `bytes`. 

1211 """ 

1212 # Create or coerce a protobuf request object. 

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

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

1215 flattened_params = [topic] 

1216 has_flattened_params = ( 

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

1218 ) 

1219 if request is not None and has_flattened_params: 

1220 raise ValueError( 

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

1222 "the individual field arguments should be set." 

1223 ) 

1224 

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

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

1227 if not isinstance(request, pubsub.DeleteTopicRequest): 

1228 request = pubsub.DeleteTopicRequest(request) 

1229 

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

1231 # request, apply these. 

1232 if topic is not None: 

1233 request.topic = topic 

1234 

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

1236 # and friendly error handling. 

1237 rpc = self._client._transport._wrapped_methods[ 

1238 self._client._transport.delete_topic 

1239 ] 

1240 

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

1242 # add these here. 

1243 metadata = tuple(metadata) + ( 

1244 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

1245 ) 

1246 

1247 # Validate the universe domain. 

1248 self._client._validate_universe_domain() 

1249 

1250 # Send the request. 

1251 await rpc( 

1252 request, 

1253 retry=retry, 

1254 timeout=timeout, 

1255 metadata=metadata, 

1256 ) 

1257 

1258 async def detach_subscription( 

1259 self, 

1260 request: Optional[Union[pubsub.DetachSubscriptionRequest, dict]] = None, 

1261 *, 

1262 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1263 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1265 ) -> pubsub.DetachSubscriptionResponse: 

1266 r"""Detaches a subscription from this topic. All messages retained 

1267 in the subscription are dropped. Subsequent ``Pull`` and 

1268 ``StreamingPull`` requests will return FAILED_PRECONDITION. If 

1269 the subscription is a push subscription, pushes to the endpoint 

1270 will stop. 

1271 

1272 .. code-block:: python 

1273 

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

1275 # code template only. 

1276 # It will require modifications to work: 

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

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

1279 # client as shown in: 

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

1281 from google import pubsub_v1 

1282 

1283 async def sample_detach_subscription(): 

1284 # Create a client 

1285 client = pubsub_v1.PublisherAsyncClient() 

1286 

1287 # Initialize request argument(s) 

1288 request = pubsub_v1.DetachSubscriptionRequest( 

1289 subscription="subscription_value", 

1290 ) 

1291 

1292 # Make the request 

1293 response = await client.detach_subscription(request=request) 

1294 

1295 # Handle the response 

1296 print(response) 

1297 

1298 Args: 

1299 request (Optional[Union[google.pubsub_v1.types.DetachSubscriptionRequest, dict]]): 

1300 The request object. Request for the DetachSubscription 

1301 method. 

1302 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

1303 should be retried. 

1304 timeout (TimeoutType): 

1305 The timeout for this request. 

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

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

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

1309 be of type `bytes`. 

1310 

1311 Returns: 

1312 google.pubsub_v1.types.DetachSubscriptionResponse: 

1313 Response for the DetachSubscription 

1314 method. Reserved for future use. 

1315 

1316 """ 

1317 # Create or coerce a protobuf request object. 

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

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

1320 if not isinstance(request, pubsub.DetachSubscriptionRequest): 

1321 request = pubsub.DetachSubscriptionRequest(request) 

1322 

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

1324 # and friendly error handling. 

1325 rpc = self._client._transport._wrapped_methods[ 

1326 self._client._transport.detach_subscription 

1327 ] 

1328 

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

1330 # add these here. 

1331 metadata = tuple(metadata) + ( 

1332 gapic_v1.routing_header.to_grpc_metadata( 

1333 (("subscription", request.subscription),) 

1334 ), 

1335 ) 

1336 

1337 # Validate the universe domain. 

1338 self._client._validate_universe_domain() 

1339 

1340 # Send the request. 

1341 response = await rpc( 

1342 request, 

1343 retry=retry, 

1344 timeout=timeout, 

1345 metadata=metadata, 

1346 ) 

1347 

1348 # Done; return the response. 

1349 return response 

1350 

1351 async def set_iam_policy( 

1352 self, 

1353 request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, 

1354 *, 

1355 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1356 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1358 ) -> policy_pb2.Policy: 

1359 r"""Sets the IAM access control policy on the specified function. 

1360 

1361 Replaces any existing policy. 

1362 

1363 Args: 

1364 request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): 

1365 The request object. Request message for `SetIamPolicy` 

1366 method. 

1367 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

1368 should be retried. 

1369 timeout (TimeoutType): 

1370 The timeout for this request. 

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

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

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

1374 be of type `bytes`. 

1375 Returns: 

1376 ~.policy_pb2.Policy: 

1377 Defines an Identity and Access Management (IAM) policy. 

1378 It is used to specify access control policies for Cloud 

1379 Platform resources. 

1380 A ``Policy`` is a collection of ``bindings``. A 

1381 ``binding`` binds one or more ``members`` to a single 

1382 ``role``. Members can be user accounts, service 

1383 accounts, Google groups, and domains (such as G Suite). 

1384 A ``role`` is a named list of permissions (defined by 

1385 IAM or configured by users). A ``binding`` can 

1386 optionally specify a ``condition``, which is a logic 

1387 expression that further constrains the role binding 

1388 based on attributes about the request and/or target 

1389 resource. 

1390 

1391 **JSON Example** 

1392 

1393 :: 

1394 

1395 { 

1396 "bindings": [ 

1397 { 

1398 "role": "roles/resourcemanager.organizationAdmin", 

1399 "members": [ 

1400 "user:mike@example.com", 

1401 "group:admins@example.com", 

1402 "domain:google.com", 

1403 "serviceAccount:my-project-id@appspot.gserviceaccount.com" 

1404 ] 

1405 }, 

1406 { 

1407 "role": "roles/resourcemanager.organizationViewer", 

1408 "members": ["user:eve@example.com"], 

1409 "condition": { 

1410 "title": "expirable access", 

1411 "description": "Does not grant access after Sep 2020", 

1412 "expression": "request.time < 

1413 timestamp('2020-10-01T00:00:00.000Z')", 

1414 } 

1415 } 

1416 ] 

1417 } 

1418 

1419 **YAML Example** 

1420 

1421 :: 

1422 

1423 bindings: 

1424 - members: 

1425 - user:mike@example.com 

1426 - group:admins@example.com 

1427 - domain:google.com 

1428 - serviceAccount:my-project-id@appspot.gserviceaccount.com 

1429 role: roles/resourcemanager.organizationAdmin 

1430 - members: 

1431 - user:eve@example.com 

1432 role: roles/resourcemanager.organizationViewer 

1433 condition: 

1434 title: expirable access 

1435 description: Does not grant access after Sep 2020 

1436 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') 

1437 

1438 For a description of IAM and its features, see the `IAM 

1439 developer's 

1440 guide <https://cloud.google.com/iam/docs>`__. 

1441 """ 

1442 # Create or coerce a protobuf request object. 

1443 

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

1445 # so it must be constructed via keyword expansion. 

1446 if isinstance(request, dict): 

1447 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

1448 

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

1450 # and friendly error handling. 

1451 rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] 

1452 

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

1454 # add these here. 

1455 metadata = tuple(metadata) + ( 

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

1457 ) 

1458 

1459 # Validate the universe domain. 

1460 self._client._validate_universe_domain() 

1461 

1462 # Send the request. 

1463 response = await rpc( 

1464 request, 

1465 retry=retry, 

1466 timeout=timeout, 

1467 metadata=metadata, 

1468 ) 

1469 

1470 # Done; return the response. 

1471 return response 

1472 

1473 async def get_iam_policy( 

1474 self, 

1475 request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, 

1476 *, 

1477 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1478 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1480 ) -> policy_pb2.Policy: 

1481 r"""Gets the IAM access control policy for a function. 

1482 

1483 Returns an empty policy if the function exists and does not have a 

1484 policy set. 

1485 

1486 Args: 

1487 request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): 

1488 The request object. Request message for `GetIamPolicy` 

1489 method. 

1490 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if 

1491 any, should be retried. 

1492 timeout (TimeoutType): 

1493 The timeout for this request. 

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

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

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

1497 be of type `bytes`. 

1498 Returns: 

1499 ~.policy_pb2.Policy: 

1500 Defines an Identity and Access Management (IAM) policy. 

1501 It is used to specify access control policies for Cloud 

1502 Platform resources. 

1503 A ``Policy`` is a collection of ``bindings``. A 

1504 ``binding`` binds one or more ``members`` to a single 

1505 ``role``. Members can be user accounts, service 

1506 accounts, Google groups, and domains (such as G Suite). 

1507 A ``role`` is a named list of permissions (defined by 

1508 IAM or configured by users). A ``binding`` can 

1509 optionally specify a ``condition``, which is a logic 

1510 expression that further constrains the role binding 

1511 based on attributes about the request and/or target 

1512 resource. 

1513 

1514 **JSON Example** 

1515 

1516 :: 

1517 

1518 { 

1519 "bindings": [ 

1520 { 

1521 "role": "roles/resourcemanager.organizationAdmin", 

1522 "members": [ 

1523 "user:mike@example.com", 

1524 "group:admins@example.com", 

1525 "domain:google.com", 

1526 "serviceAccount:my-project-id@appspot.gserviceaccount.com" 

1527 ] 

1528 }, 

1529 { 

1530 "role": "roles/resourcemanager.organizationViewer", 

1531 "members": ["user:eve@example.com"], 

1532 "condition": { 

1533 "title": "expirable access", 

1534 "description": "Does not grant access after Sep 2020", 

1535 "expression": "request.time < 

1536 timestamp('2020-10-01T00:00:00.000Z')", 

1537 } 

1538 } 

1539 ] 

1540 } 

1541 

1542 **YAML Example** 

1543 

1544 :: 

1545 

1546 bindings: 

1547 - members: 

1548 - user:mike@example.com 

1549 - group:admins@example.com 

1550 - domain:google.com 

1551 - serviceAccount:my-project-id@appspot.gserviceaccount.com 

1552 role: roles/resourcemanager.organizationAdmin 

1553 - members: 

1554 - user:eve@example.com 

1555 role: roles/resourcemanager.organizationViewer 

1556 condition: 

1557 title: expirable access 

1558 description: Does not grant access after Sep 2020 

1559 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') 

1560 

1561 For a description of IAM and its features, see the `IAM 

1562 developer's 

1563 guide <https://cloud.google.com/iam/docs>`__. 

1564 """ 

1565 # Create or coerce a protobuf request object. 

1566 

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

1568 # so it must be constructed via keyword expansion. 

1569 if isinstance(request, dict): 

1570 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

1571 

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

1573 # and friendly error handling. 

1574 rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] 

1575 

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

1577 # add these here. 

1578 metadata = tuple(metadata) + ( 

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

1580 ) 

1581 

1582 # Validate the universe domain. 

1583 self._client._validate_universe_domain() 

1584 

1585 # Send the request. 

1586 response = await rpc( 

1587 request, 

1588 retry=retry, 

1589 timeout=timeout, 

1590 metadata=metadata, 

1591 ) 

1592 

1593 # Done; return the response. 

1594 return response 

1595 

1596 async def test_iam_permissions( 

1597 self, 

1598 request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, 

1599 *, 

1600 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1601 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1603 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

1604 r"""Tests the specified IAM permissions against the IAM access control 

1605 policy for a function. 

1606 

1607 If the function does not exist, this will return an empty set 

1608 of permissions, not a NOT_FOUND error. 

1609 

1610 Args: 

1611 request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): 

1612 The request object. Request message for 

1613 `TestIamPermissions` method. 

1614 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, 

1615 if any, should be retried. 

1616 timeout (TimeoutType): 

1617 The timeout for this request. 

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

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

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

1621 be of type `bytes`. 

1622 Returns: 

1623 ~.iam_policy_pb2.TestIamPermissionsResponse: 

1624 Response message for ``TestIamPermissions`` method. 

1625 """ 

1626 # Create or coerce a protobuf request object. 

1627 

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

1629 # so it must be constructed via keyword expansion. 

1630 if isinstance(request, dict): 

1631 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

1632 

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

1634 # and friendly error handling. 

1635 rpc = self.transport._wrapped_methods[ 

1636 self._client._transport.test_iam_permissions 

1637 ] 

1638 

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

1640 # add these here. 

1641 metadata = tuple(metadata) + ( 

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

1643 ) 

1644 

1645 # Validate the universe domain. 

1646 self._client._validate_universe_domain() 

1647 

1648 # Send the request. 

1649 response = await rpc( 

1650 request, 

1651 retry=retry, 

1652 timeout=timeout, 

1653 metadata=metadata, 

1654 ) 

1655 

1656 # Done; return the response. 

1657 return response 

1658 

1659 async def __aenter__(self) -> "PublisherAsyncClient": 

1660 return self 

1661 

1662 async def __aexit__(self, exc_type, exc, tb): 

1663 await self.transport.close() 

1664 

1665 

1666DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1667 client_library_version=package_version.__version__ 

1668) 

1669 

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

1671 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

1672 

1673 

1674__all__ = ("PublisherAsyncClient",)