Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/pubsub_v1/services/publisher/client.py: 34%

309 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-26 06:25 +0000

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

2# Copyright 2022 Google LLC 

3# 

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

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

6# You may obtain a copy of the License at 

7# 

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

9# 

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

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

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

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

14# limitations under the License. 

15# 

16from collections import OrderedDict 

17import functools 

18import os 

19import re 

20from typing import ( 

21 Dict, 

22 Mapping, 

23 MutableMapping, 

24 MutableSequence, 

25 Optional, 

26 Sequence, 

27 Tuple, 

28 Type, 

29 Union, 

30 cast, 

31) 

32 

33from google.pubsub_v1 import gapic_version as package_version 

34 

35from google.api_core import client_options as client_options_lib 

36from google.api_core import exceptions as core_exceptions 

37from google.api_core import gapic_v1 

38from google.api_core import retry as retries 

39from google.api_core import timeout as timeouts # type: ignore 

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

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

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

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

44from google.oauth2 import service_account # type: ignore 

45 

46try: 

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

48except AttributeError: # pragma: NO COVER 

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

50 

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

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

53from google.protobuf import duration_pb2 # type: ignore 

54from google.protobuf import field_mask_pb2 # type: ignore 

55from google.pubsub_v1.services.publisher import pagers 

56from google.pubsub_v1.types import pubsub 

57from google.pubsub_v1.types import TimeoutType 

58 

59import grpc 

60from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO 

61from .transports.grpc import PublisherGrpcTransport 

62from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport 

63 

64 

65class PublisherClientMeta(type): 

66 """Metaclass for the Publisher client. 

67 

68 This provides class-level methods for building and retrieving 

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

70 objects. 

71 """ 

72 

73 _transport_registry = OrderedDict() # type: Dict[str, Type[PublisherTransport]] 

74 _transport_registry["grpc"] = PublisherGrpcTransport 

75 _transport_registry["grpc_asyncio"] = PublisherGrpcAsyncIOTransport 

76 

77 def get_transport_class( 

78 cls, 

79 label: Optional[str] = None, 

80 ) -> Type[PublisherTransport]: 

81 """Returns an appropriate transport class. 

82 

83 Args: 

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

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

86 

87 Returns: 

88 The transport class to use. 

89 """ 

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

91 if label: 

92 return cls._transport_registry[label] 

93 

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

95 # in the dictionary). 

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

97 

98 

99class PublisherClient(metaclass=PublisherClientMeta): 

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

101 and to send messages to a topic. 

102 """ 

103 

104 @staticmethod 

105 def _get_default_mtls_endpoint(api_endpoint): 

106 """Converts api endpoint to mTLS endpoint. 

107 

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

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

110 Args: 

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

112 Returns: 

113 str: converted mTLS api endpoint. 

114 """ 

115 if not api_endpoint: 

116 return api_endpoint 

117 

118 mtls_endpoint_re = re.compile( 

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

120 ) 

121 

122 m = mtls_endpoint_re.match(api_endpoint) 

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

124 if mtls or not googledomain: 

125 return api_endpoint 

126 

127 if sandbox: 

128 return api_endpoint.replace( 

129 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

130 ) 

131 

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

133 

134 # The scopes needed to make gRPC calls to all of the methods defined in 

135 # this service 

136 _DEFAULT_SCOPES = ( 

137 "https://www.googleapis.com/auth/cloud-platform", 

138 "https://www.googleapis.com/auth/pubsub", 

139 ) 

140 

141 SERVICE_ADDRESS = "pubsub.googleapis.com:443" 

142 """The default address of the service.""" 

143 

144 DEFAULT_ENDPOINT = "pubsub.googleapis.com" 

145 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

146 DEFAULT_ENDPOINT 

147 ) 

148 

149 @classmethod 

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

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

152 info. 

153 

154 Args: 

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

156 args: Additional arguments to pass to the constructor. 

157 kwargs: Additional arguments to pass to the constructor. 

158 

159 Returns: 

160 PublisherClient: The constructed client. 

161 """ 

162 credentials = service_account.Credentials.from_service_account_info(info) 

163 kwargs["credentials"] = credentials 

164 return cls(*args, **kwargs) 

165 

166 @classmethod 

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

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

169 file. 

170 

171 Args: 

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

173 file. 

174 args: Additional arguments to pass to the constructor. 

175 kwargs: Additional arguments to pass to the constructor. 

176 

177 Returns: 

178 PublisherClient: The constructed client. 

179 """ 

180 credentials = service_account.Credentials.from_service_account_file(filename) 

181 kwargs["credentials"] = credentials 

182 return cls(*args, **kwargs) 

183 

184 from_service_account_json = from_service_account_file 

185 

186 @property 

187 def transport(self) -> PublisherTransport: 

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

189 

190 Returns: 

191 PublisherTransport: The transport used by the client 

192 instance. 

193 """ 

194 return self._transport 

195 

196 @staticmethod 

197 def schema_path( 

198 project: str, 

199 schema: str, 

200 ) -> str: 

201 """Returns a fully-qualified schema string.""" 

202 return "projects/{project}/schemas/{schema}".format( 

203 project=project, 

204 schema=schema, 

205 ) 

206 

207 @staticmethod 

208 def parse_schema_path(path: str) -> Dict[str, str]: 

209 """Parses a schema path into its component segments.""" 

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

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

212 

213 @staticmethod 

214 def subscription_path( 

215 project: str, 

216 subscription: str, 

217 ) -> str: 

218 """Returns a fully-qualified subscription string.""" 

219 return "projects/{project}/subscriptions/{subscription}".format( 

220 project=project, 

221 subscription=subscription, 

222 ) 

223 

224 @staticmethod 

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

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

227 m = re.match( 

228 r"^projects/(?P<project>.+?)/subscriptions/(?P<subscription>.+?)$", path 

229 ) 

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

231 

232 @staticmethod 

233 def topic_path( 

234 project: str, 

235 topic: str, 

236 ) -> str: 

237 """Returns a fully-qualified topic string.""" 

238 return "projects/{project}/topics/{topic}".format( 

239 project=project, 

240 topic=topic, 

241 ) 

242 

243 @staticmethod 

244 def parse_topic_path(path: str) -> Dict[str, str]: 

245 """Parses a topic path into its component segments.""" 

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

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

248 

249 @staticmethod 

250 def common_billing_account_path( 

251 billing_account: str, 

252 ) -> str: 

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

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

255 billing_account=billing_account, 

256 ) 

257 

258 @staticmethod 

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

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

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

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

263 

264 @staticmethod 

265 def common_folder_path( 

266 folder: str, 

267 ) -> str: 

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

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

270 folder=folder, 

271 ) 

272 

273 @staticmethod 

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

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

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

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

278 

279 @staticmethod 

280 def common_organization_path( 

281 organization: str, 

282 ) -> str: 

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

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

285 organization=organization, 

286 ) 

287 

288 @staticmethod 

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

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

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

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

293 

294 @staticmethod 

295 def common_project_path( 

296 project: str, 

297 ) -> str: 

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

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

300 project=project, 

301 ) 

302 

303 @staticmethod 

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

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

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

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

308 

309 @staticmethod 

310 def common_location_path( 

311 project: str, 

312 location: str, 

313 ) -> str: 

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

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

316 project=project, 

317 location=location, 

318 ) 

319 

320 @staticmethod 

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

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

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

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

325 

326 @classmethod 

327 def get_mtls_endpoint_and_cert_source( 

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

329 ): 

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

331 

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

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

334 client cert source is None. 

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

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

337 source is None. 

338 

339 The API endpoint is determined in the following order: 

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

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

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

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

344 use the default API endpoint. 

345 

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

347 

348 Args: 

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

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

351 in this method. 

352 

353 Returns: 

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

355 client cert source to use. 

356 

357 Raises: 

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

359 """ 

360 if client_options is None: 

361 client_options = client_options_lib.ClientOptions() 

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

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

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

365 raise ValueError( 

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

367 ) 

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

369 raise MutualTLSChannelError( 

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

371 ) 

372 

373 # Figure out the client cert source to use. 

374 client_cert_source = None 

375 if use_client_cert == "true": 

376 if client_options.client_cert_source: 

377 client_cert_source = client_options.client_cert_source 

378 elif mtls.has_default_client_cert_source(): 

379 client_cert_source = mtls.default_client_cert_source() 

380 

381 # Figure out which api endpoint to use. 

382 if client_options.api_endpoint is not None: 

383 api_endpoint = client_options.api_endpoint 

384 elif use_mtls_endpoint == "always" or ( 

385 use_mtls_endpoint == "auto" and client_cert_source 

386 ): 

387 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

388 else: 

389 api_endpoint = cls.DEFAULT_ENDPOINT 

390 

391 return api_endpoint, client_cert_source 

392 

393 def __init__( 

394 self, 

395 *, 

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

397 transport: Optional[Union[str, PublisherTransport]] = None, 

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

399 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

400 ) -> None: 

401 """Instantiates the publisher client. 

402 

403 Args: 

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

405 authorization credentials to attach to requests. These 

406 credentials identify the application to the service; if none 

407 are specified, the client will attempt to ascertain the 

408 credentials from the environment. 

409 transport (Union[str, PublisherTransport]): The 

410 transport to use. If set to None, a transport is chosen 

411 automatically. 

412 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the 

413 client. It won't take effect if a ``transport`` instance is provided. 

414 (1) The ``api_endpoint`` property can be used to override the 

415 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT 

416 environment variable can also be used to override the endpoint: 

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

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

419 default mTLS endpoint if client certificate is present, this is 

420 the default value). However, the ``api_endpoint`` property takes 

421 precedence if provided. 

422 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

424 to provide client certificate for mutual TLS transport. If 

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

426 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

427 set, no client certificate will be used. 

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

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

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

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

432 your own client library. 

433 

434 Raises: 

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

436 creation failed for any reason. 

437 """ 

438 if isinstance(client_options, dict): 

439 client_options = client_options_lib.from_dict(client_options) 

440 if client_options is None: 

441 client_options = client_options_lib.ClientOptions() 

442 client_options = cast(client_options_lib.ClientOptions, client_options) 

443 

444 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( 

445 client_options 

446 ) 

447 

448 api_key_value = getattr(client_options, "api_key", None) 

449 if api_key_value and credentials: 

450 raise ValueError( 

451 "client_options.api_key and credentials are mutually exclusive" 

452 ) 

453 

454 # Save or instantiate the transport. 

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

456 # instance provides an extensibility point for unusual situations. 

457 if isinstance(transport, PublisherTransport): 

458 # transport is a PublisherTransport instance. 

459 if credentials or client_options.credentials_file or api_key_value: 

460 raise ValueError( 

461 "When providing a transport instance, " 

462 "provide its credentials directly." 

463 ) 

464 if client_options.scopes: 

465 raise ValueError( 

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

467 "directly." 

468 ) 

469 self._transport = transport 

470 else: 

471 import google.auth._default # type: ignore 

472 

473 if api_key_value and hasattr( 

474 google.auth._default, "get_api_key_credentials" 

475 ): 

476 credentials = google.auth._default.get_api_key_credentials( 

477 api_key_value 

478 ) 

479 

480 Transport = type(self).get_transport_class(transport) 

481 

482 emulator_host = os.environ.get("PUBSUB_EMULATOR_HOST") 

483 if emulator_host: 

484 if issubclass(Transport, type(self)._transport_registry["grpc"]): 

485 channel = grpc.insecure_channel(target=emulator_host) 

486 else: 

487 channel = grpc.aio.insecure_channel(target=emulator_host) 

488 Transport = functools.partial(Transport, channel=channel) 

489 

490 self._transport = Transport( 

491 credentials=credentials, 

492 credentials_file=client_options.credentials_file, 

493 host=api_endpoint, 

494 scopes=client_options.scopes, 

495 client_cert_source_for_mtls=client_cert_source_func, 

496 quota_project_id=client_options.quota_project_id, 

497 client_info=client_info, 

498 always_use_jwt_access=True, 

499 api_audience=client_options.api_audience, 

500 ) 

501 

502 def create_topic( 

503 self, 

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

505 *, 

506 name: Optional[str] = None, 

507 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

508 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

509 metadata: Sequence[Tuple[str, str]] = (), 

510 ) -> pubsub.Topic: 

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

512 name rules] 

513 (https://cloud.google.com/pubsub/docs/admin#resource_names). 

514 

515 .. code-block:: python 

516 

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

518 # code template only. 

519 # It will require modifications to work: 

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

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

522 # client as shown in: 

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

524 from google import pubsub_v1 

525 

526 def sample_create_topic(): 

527 # Create a client 

528 client = pubsub_v1.PublisherClient() 

529 

530 # Initialize request argument(s) 

531 request = pubsub_v1.Topic( 

532 name="name_value", 

533 ) 

534 

535 # Make the request 

536 response = client.create_topic(request=request) 

537 

538 # Handle the response 

539 print(response) 

540 

541 Args: 

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

543 The request object. A topic resource. 

544 name (str): 

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

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

547 must start with a letter, and contain only letters 

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

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

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

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

552 start with ``"goog"``. 

553 

554 This corresponds to the ``name`` field 

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

556 should not be set. 

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

558 should be retried. 

559 timeout (TimeoutType): 

560 The timeout for this request. 

561 metadata (Sequence[Tuple[str, str]]): Strings which should be 

562 sent along with the request as metadata. 

563 

564 Returns: 

565 google.pubsub_v1.types.Topic: 

566 A topic resource. 

567 """ 

568 # Create or coerce a protobuf request object. 

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

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

571 has_flattened_params = any([name]) 

572 if request is not None and has_flattened_params: 

573 raise ValueError( 

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

575 "the individual field arguments should be set." 

576 ) 

577 

578 # Minor optimization to avoid making a copy if the user passes 

579 # in a pubsub.Topic. 

580 # There's no risk of modifying the input as we've already verified 

581 # there are no flattened fields. 

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

583 request = pubsub.Topic(request) 

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

585 # request, apply these. 

586 if name is not None: 

587 request.name = name 

588 

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

590 # and friendly error handling. 

591 rpc = self._transport._wrapped_methods[self._transport.create_topic] 

592 

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

594 # add these here. 

595 metadata = tuple(metadata) + ( 

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

597 ) 

598 

599 # Send the request. 

600 response = rpc( 

601 request, 

602 retry=retry, 

603 timeout=timeout, 

604 metadata=metadata, 

605 ) 

606 

607 # Done; return the response. 

608 return response 

609 

610 def update_topic( 

611 self, 

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

613 *, 

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

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

616 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

617 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

618 metadata: Sequence[Tuple[str, str]] = (), 

619 ) -> pubsub.Topic: 

620 r"""Updates an existing topic. Note that certain 

621 properties of a topic are not modifiable. 

622 

623 .. code-block:: python 

624 

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

626 # code template only. 

627 # It will require modifications to work: 

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

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

630 # client as shown in: 

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

632 from google import pubsub_v1 

633 

634 def sample_update_topic(): 

635 # Create a client 

636 client = pubsub_v1.PublisherClient() 

637 

638 # Initialize request argument(s) 

639 topic = pubsub_v1.Topic() 

640 topic.name = "name_value" 

641 

642 request = pubsub_v1.UpdateTopicRequest( 

643 topic=topic, 

644 ) 

645 

646 # Make the request 

647 response = client.update_topic(request=request) 

648 

649 # Handle the response 

650 print(response) 

651 

652 Args: 

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

654 The request object. Request for the UpdateTopic method. 

655 topic (google.pubsub_v1.types.Topic): 

656 Required. The updated topic object. 

657 This corresponds to the ``topic`` field 

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

659 should not be set. 

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

661 Required. Indicates which fields in the provided topic 

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

663 ``update_mask`` contains "message_storage_policy" but 

664 the ``message_storage_policy`` is not set in the 

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

666 determined by the policy configured at the project or 

667 organization level. 

668 

669 This corresponds to the ``update_mask`` field 

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

671 should not be set. 

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

673 should be retried. 

674 timeout (TimeoutType): 

675 The timeout for this request. 

676 metadata (Sequence[Tuple[str, str]]): Strings which should be 

677 sent along with the request as metadata. 

678 

679 Returns: 

680 google.pubsub_v1.types.Topic: 

681 A topic resource. 

682 """ 

683 # Create or coerce a protobuf request object. 

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

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

686 has_flattened_params = any([topic, update_mask]) 

687 if request is not None and has_flattened_params: 

688 raise ValueError( 

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

690 "the individual field arguments should be set." 

691 ) 

692 

693 # Minor optimization to avoid making a copy if the user passes 

694 # in a pubsub.UpdateTopicRequest. 

695 # There's no risk of modifying the input as we've already verified 

696 # there are no flattened fields. 

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

698 request = pubsub.UpdateTopicRequest(request) 

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

700 # request, apply these. 

701 if topic is not None: 

702 request.topic = topic 

703 if update_mask is not None: 

704 request.update_mask = update_mask 

705 

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

707 # and friendly error handling. 

708 rpc = self._transport._wrapped_methods[self._transport.update_topic] 

709 

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

711 # add these here. 

712 metadata = tuple(metadata) + ( 

713 gapic_v1.routing_header.to_grpc_metadata( 

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

715 ), 

716 ) 

717 

718 # Send the request. 

719 response = rpc( 

720 request, 

721 retry=retry, 

722 timeout=timeout, 

723 metadata=metadata, 

724 ) 

725 

726 # Done; return the response. 

727 return response 

728 

729 def publish( 

730 self, 

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

732 *, 

733 topic: Optional[str] = None, 

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

735 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

736 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

737 metadata: Sequence[Tuple[str, str]] = (), 

738 ) -> pubsub.PublishResponse: 

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

740 the topic does not exist. 

741 

742 .. code-block:: python 

743 

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

745 # code template only. 

746 # It will require modifications to work: 

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

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

749 # client as shown in: 

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

751 from google import pubsub_v1 

752 

753 def sample_publish(): 

754 # Create a client 

755 client = pubsub_v1.PublisherClient() 

756 

757 # Initialize request argument(s) 

758 request = pubsub_v1.PublishRequest( 

759 topic="topic_value", 

760 ) 

761 

762 # Make the request 

763 response = client.publish(request=request) 

764 

765 # Handle the response 

766 print(response) 

767 

768 Args: 

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

770 The request object. Request for the Publish method. 

771 topic (str): 

772 Required. The messages in the request will be published 

773 on this topic. Format is 

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

775 

776 This corresponds to the ``topic`` field 

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

778 should not be set. 

779 messages (MutableSequence[google.pubsub_v1.types.PubsubMessage]): 

780 Required. The messages to publish. 

781 This corresponds to the ``messages`` field 

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

783 should not be set. 

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

785 should be retried. 

786 timeout (TimeoutType): 

787 The timeout for this request. 

788 metadata (Sequence[Tuple[str, str]]): Strings which should be 

789 sent along with the request as metadata. 

790 

791 Returns: 

792 google.pubsub_v1.types.PublishResponse: 

793 Response for the Publish method. 

794 """ 

795 # Create or coerce a protobuf request object. 

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

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

798 has_flattened_params = any([topic, messages]) 

799 if request is not None and has_flattened_params: 

800 raise ValueError( 

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

802 "the individual field arguments should be set." 

803 ) 

804 

805 # Minor optimization to avoid making a copy if the user passes 

806 # in a pubsub.PublishRequest. 

807 # There's no risk of modifying the input as we've already verified 

808 # there are no flattened fields. 

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

810 request = pubsub.PublishRequest(request) 

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

812 # request, apply these. 

813 if topic is not None: 

814 request.topic = topic 

815 if messages is not None: 

816 request.messages = messages 

817 

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

819 # and friendly error handling. 

820 rpc = self._transport._wrapped_methods[self._transport.publish] 

821 

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

823 # add these here. 

824 metadata = tuple(metadata) + ( 

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

826 ) 

827 

828 # Send the request. 

829 response = rpc( 

830 request, 

831 retry=retry, 

832 timeout=timeout, 

833 metadata=metadata, 

834 ) 

835 

836 # Done; return the response. 

837 return response 

838 

839 def get_topic( 

840 self, 

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

842 *, 

843 topic: Optional[str] = None, 

844 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

845 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

846 metadata: Sequence[Tuple[str, str]] = (), 

847 ) -> pubsub.Topic: 

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

849 

850 .. code-block:: python 

851 

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

853 # code template only. 

854 # It will require modifications to work: 

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

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

857 # client as shown in: 

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

859 from google import pubsub_v1 

860 

861 def sample_get_topic(): 

862 # Create a client 

863 client = pubsub_v1.PublisherClient() 

864 

865 # Initialize request argument(s) 

866 request = pubsub_v1.GetTopicRequest( 

867 topic="topic_value", 

868 ) 

869 

870 # Make the request 

871 response = client.get_topic(request=request) 

872 

873 # Handle the response 

874 print(response) 

875 

876 Args: 

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

878 The request object. Request for the GetTopic method. 

879 topic (str): 

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

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

882 

883 This corresponds to the ``topic`` field 

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

885 should not be set. 

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

887 should be retried. 

888 timeout (TimeoutType): 

889 The timeout for this request. 

890 metadata (Sequence[Tuple[str, str]]): Strings which should be 

891 sent along with the request as metadata. 

892 

893 Returns: 

894 google.pubsub_v1.types.Topic: 

895 A topic resource. 

896 """ 

897 # Create or coerce a protobuf request object. 

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

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

900 has_flattened_params = any([topic]) 

901 if request is not None and has_flattened_params: 

902 raise ValueError( 

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

904 "the individual field arguments should be set." 

905 ) 

906 

907 # Minor optimization to avoid making a copy if the user passes 

908 # in a pubsub.GetTopicRequest. 

909 # There's no risk of modifying the input as we've already verified 

910 # there are no flattened fields. 

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

912 request = pubsub.GetTopicRequest(request) 

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

914 # request, apply these. 

915 if topic is not None: 

916 request.topic = topic 

917 

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

919 # and friendly error handling. 

920 rpc = self._transport._wrapped_methods[self._transport.get_topic] 

921 

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

923 # add these here. 

924 metadata = tuple(metadata) + ( 

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

926 ) 

927 

928 # Send the request. 

929 response = rpc( 

930 request, 

931 retry=retry, 

932 timeout=timeout, 

933 metadata=metadata, 

934 ) 

935 

936 # Done; return the response. 

937 return response 

938 

939 def list_topics( 

940 self, 

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

942 *, 

943 project: Optional[str] = None, 

944 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

945 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

946 metadata: Sequence[Tuple[str, str]] = (), 

947 ) -> pagers.ListTopicsPager: 

948 r"""Lists matching topics. 

949 

950 .. code-block:: python 

951 

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

953 # code template only. 

954 # It will require modifications to work: 

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

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

957 # client as shown in: 

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

959 from google import pubsub_v1 

960 

961 def sample_list_topics(): 

962 # Create a client 

963 client = pubsub_v1.PublisherClient() 

964 

965 # Initialize request argument(s) 

966 request = pubsub_v1.ListTopicsRequest( 

967 project="project_value", 

968 ) 

969 

970 # Make the request 

971 page_result = client.list_topics(request=request) 

972 

973 # Handle the response 

974 for response in page_result: 

975 print(response) 

976 

977 Args: 

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

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

980 project (str): 

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

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

983 

984 This corresponds to the ``project`` field 

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

986 should not be set. 

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

988 should be retried. 

989 timeout (TimeoutType): 

990 The timeout for this request. 

991 metadata (Sequence[Tuple[str, str]]): Strings which should be 

992 sent along with the request as metadata. 

993 

994 Returns: 

995 google.pubsub_v1.services.publisher.pagers.ListTopicsPager: 

996 Response for the ListTopics method. 

997 

998 Iterating over this object will yield results and 

999 resolve additional pages automatically. 

1000 

1001 """ 

1002 # Create or coerce a protobuf request object. 

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

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

1005 has_flattened_params = any([project]) 

1006 if request is not None and has_flattened_params: 

1007 raise ValueError( 

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

1009 "the individual field arguments should be set." 

1010 ) 

1011 

1012 # Minor optimization to avoid making a copy if the user passes 

1013 # in a pubsub.ListTopicsRequest. 

1014 # There's no risk of modifying the input as we've already verified 

1015 # there are no flattened fields. 

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

1017 request = pubsub.ListTopicsRequest(request) 

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

1019 # request, apply these. 

1020 if project is not None: 

1021 request.project = project 

1022 

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

1024 # and friendly error handling. 

1025 rpc = self._transport._wrapped_methods[self._transport.list_topics] 

1026 

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

1028 # add these here. 

1029 metadata = tuple(metadata) + ( 

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

1031 ) 

1032 

1033 # Send the request. 

1034 response = rpc( 

1035 request, 

1036 retry=retry, 

1037 timeout=timeout, 

1038 metadata=metadata, 

1039 ) 

1040 

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

1042 # an `__iter__` convenience method. 

1043 response = pagers.ListTopicsPager( 

1044 method=rpc, 

1045 request=request, 

1046 response=response, 

1047 metadata=metadata, 

1048 ) 

1049 

1050 # Done; return the response. 

1051 return response 

1052 

1053 def list_topic_subscriptions( 

1054 self, 

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

1056 *, 

1057 topic: Optional[str] = None, 

1058 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1059 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1060 metadata: Sequence[Tuple[str, str]] = (), 

1061 ) -> pagers.ListTopicSubscriptionsPager: 

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

1063 topic. 

1064 

1065 .. code-block:: python 

1066 

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

1068 # code template only. 

1069 # It will require modifications to work: 

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

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

1072 # client as shown in: 

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

1074 from google import pubsub_v1 

1075 

1076 def sample_list_topic_subscriptions(): 

1077 # Create a client 

1078 client = pubsub_v1.PublisherClient() 

1079 

1080 # Initialize request argument(s) 

1081 request = pubsub_v1.ListTopicSubscriptionsRequest( 

1082 topic="topic_value", 

1083 ) 

1084 

1085 # Make the request 

1086 page_result = client.list_topic_subscriptions(request=request) 

1087 

1088 # Handle the response 

1089 for response in page_result: 

1090 print(response) 

1091 

1092 Args: 

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

1094 The request object. Request for the 

1095 `ListTopicSubscriptions` method. 

1096 topic (str): 

1097 Required. The name of the topic that subscriptions are 

1098 attached to. Format is 

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

1100 

1101 This corresponds to the ``topic`` field 

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

1103 should not be set. 

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

1105 should be retried. 

1106 timeout (TimeoutType): 

1107 The timeout for this request. 

1108 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1109 sent along with the request as metadata. 

1110 

1111 Returns: 

1112 google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsPager: 

1113 Response for the ListTopicSubscriptions method. 

1114 

1115 Iterating over this object will yield results and 

1116 resolve additional pages automatically. 

1117 

1118 """ 

1119 # Create or coerce a protobuf request object. 

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

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

1122 has_flattened_params = any([topic]) 

1123 if request is not None and has_flattened_params: 

1124 raise ValueError( 

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

1126 "the individual field arguments should be set." 

1127 ) 

1128 

1129 # Minor optimization to avoid making a copy if the user passes 

1130 # in a pubsub.ListTopicSubscriptionsRequest. 

1131 # There's no risk of modifying the input as we've already verified 

1132 # there are no flattened fields. 

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

1134 request = pubsub.ListTopicSubscriptionsRequest(request) 

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

1136 # request, apply these. 

1137 if topic is not None: 

1138 request.topic = topic 

1139 

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

1141 # and friendly error handling. 

1142 rpc = self._transport._wrapped_methods[self._transport.list_topic_subscriptions] 

1143 

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

1145 # add these here. 

1146 metadata = tuple(metadata) + ( 

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

1148 ) 

1149 

1150 # Send the request. 

1151 response = rpc( 

1152 request, 

1153 retry=retry, 

1154 timeout=timeout, 

1155 metadata=metadata, 

1156 ) 

1157 

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

1159 # an `__iter__` convenience method. 

1160 response = pagers.ListTopicSubscriptionsPager( 

1161 method=rpc, 

1162 request=request, 

1163 response=response, 

1164 metadata=metadata, 

1165 ) 

1166 

1167 # Done; return the response. 

1168 return response 

1169 

1170 def list_topic_snapshots( 

1171 self, 

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

1173 *, 

1174 topic: Optional[str] = None, 

1175 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1176 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1177 metadata: Sequence[Tuple[str, str]] = (), 

1178 ) -> pagers.ListTopicSnapshotsPager: 

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

1180 used in 

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

1182 operations, which allow you to manage message acknowledgments in 

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

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

1185 

1186 .. code-block:: python 

1187 

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

1189 # code template only. 

1190 # It will require modifications to work: 

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

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

1193 # client as shown in: 

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

1195 from google import pubsub_v1 

1196 

1197 def sample_list_topic_snapshots(): 

1198 # Create a client 

1199 client = pubsub_v1.PublisherClient() 

1200 

1201 # Initialize request argument(s) 

1202 request = pubsub_v1.ListTopicSnapshotsRequest( 

1203 topic="topic_value", 

1204 ) 

1205 

1206 # Make the request 

1207 page_result = client.list_topic_snapshots(request=request) 

1208 

1209 # Handle the response 

1210 for response in page_result: 

1211 print(response) 

1212 

1213 Args: 

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

1215 The request object. Request for the `ListTopicSnapshots` 

1216 method. 

1217 topic (str): 

1218 Required. The name of the topic that snapshots are 

1219 attached to. Format is 

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

1221 

1222 This corresponds to the ``topic`` field 

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

1224 should not be set. 

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

1226 should be retried. 

1227 timeout (TimeoutType): 

1228 The timeout for this request. 

1229 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1230 sent along with the request as metadata. 

1231 

1232 Returns: 

1233 google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsPager: 

1234 Response for the ListTopicSnapshots method. 

1235 

1236 Iterating over this object will yield results and 

1237 resolve additional pages automatically. 

1238 

1239 """ 

1240 # Create or coerce a protobuf request object. 

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

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

1243 has_flattened_params = any([topic]) 

1244 if request is not None and has_flattened_params: 

1245 raise ValueError( 

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

1247 "the individual field arguments should be set." 

1248 ) 

1249 

1250 # Minor optimization to avoid making a copy if the user passes 

1251 # in a pubsub.ListTopicSnapshotsRequest. 

1252 # There's no risk of modifying the input as we've already verified 

1253 # there are no flattened fields. 

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

1255 request = pubsub.ListTopicSnapshotsRequest(request) 

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

1257 # request, apply these. 

1258 if topic is not None: 

1259 request.topic = topic 

1260 

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

1262 # and friendly error handling. 

1263 rpc = self._transport._wrapped_methods[self._transport.list_topic_snapshots] 

1264 

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

1266 # add these here. 

1267 metadata = tuple(metadata) + ( 

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

1269 ) 

1270 

1271 # Send the request. 

1272 response = rpc( 

1273 request, 

1274 retry=retry, 

1275 timeout=timeout, 

1276 metadata=metadata, 

1277 ) 

1278 

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

1280 # an `__iter__` convenience method. 

1281 response = pagers.ListTopicSnapshotsPager( 

1282 method=rpc, 

1283 request=request, 

1284 response=response, 

1285 metadata=metadata, 

1286 ) 

1287 

1288 # Done; return the response. 

1289 return response 

1290 

1291 def delete_topic( 

1292 self, 

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

1294 *, 

1295 topic: Optional[str] = None, 

1296 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1297 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1298 metadata: Sequence[Tuple[str, str]] = (), 

1299 ) -> None: 

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

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

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

1303 with none of the old configuration or subscriptions. Existing 

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

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

1306 

1307 .. code-block:: python 

1308 

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

1310 # code template only. 

1311 # It will require modifications to work: 

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

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

1314 # client as shown in: 

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

1316 from google import pubsub_v1 

1317 

1318 def sample_delete_topic(): 

1319 # Create a client 

1320 client = pubsub_v1.PublisherClient() 

1321 

1322 # Initialize request argument(s) 

1323 request = pubsub_v1.DeleteTopicRequest( 

1324 topic="topic_value", 

1325 ) 

1326 

1327 # Make the request 

1328 client.delete_topic(request=request) 

1329 

1330 Args: 

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

1332 The request object. Request for the `DeleteTopic` 

1333 method. 

1334 topic (str): 

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

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

1337 

1338 This corresponds to the ``topic`` field 

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

1340 should not be set. 

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

1342 should be retried. 

1343 timeout (TimeoutType): 

1344 The timeout for this request. 

1345 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1346 sent along with the request as metadata. 

1347 """ 

1348 # Create or coerce a protobuf request object. 

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

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

1351 has_flattened_params = any([topic]) 

1352 if request is not None and has_flattened_params: 

1353 raise ValueError( 

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

1355 "the individual field arguments should be set." 

1356 ) 

1357 

1358 # Minor optimization to avoid making a copy if the user passes 

1359 # in a pubsub.DeleteTopicRequest. 

1360 # There's no risk of modifying the input as we've already verified 

1361 # there are no flattened fields. 

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

1363 request = pubsub.DeleteTopicRequest(request) 

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

1365 # request, apply these. 

1366 if topic is not None: 

1367 request.topic = topic 

1368 

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

1370 # and friendly error handling. 

1371 rpc = self._transport._wrapped_methods[self._transport.delete_topic] 

1372 

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

1374 # add these here. 

1375 metadata = tuple(metadata) + ( 

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

1377 ) 

1378 

1379 # Send the request. 

1380 rpc( 

1381 request, 

1382 retry=retry, 

1383 timeout=timeout, 

1384 metadata=metadata, 

1385 ) 

1386 

1387 def detach_subscription( 

1388 self, 

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

1390 *, 

1391 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1392 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1393 metadata: Sequence[Tuple[str, str]] = (), 

1394 ) -> pubsub.DetachSubscriptionResponse: 

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

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

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

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

1399 will stop. 

1400 

1401 .. code-block:: python 

1402 

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

1404 # code template only. 

1405 # It will require modifications to work: 

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

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

1408 # client as shown in: 

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

1410 from google import pubsub_v1 

1411 

1412 def sample_detach_subscription(): 

1413 # Create a client 

1414 client = pubsub_v1.PublisherClient() 

1415 

1416 # Initialize request argument(s) 

1417 request = pubsub_v1.DetachSubscriptionRequest( 

1418 subscription="subscription_value", 

1419 ) 

1420 

1421 # Make the request 

1422 response = client.detach_subscription(request=request) 

1423 

1424 # Handle the response 

1425 print(response) 

1426 

1427 Args: 

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

1429 The request object. Request for the DetachSubscription 

1430 method. 

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

1432 should be retried. 

1433 timeout (TimeoutType): 

1434 The timeout for this request. 

1435 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1436 sent along with the request as metadata. 

1437 

1438 Returns: 

1439 google.pubsub_v1.types.DetachSubscriptionResponse: 

1440 Response for the DetachSubscription 

1441 method. Reserved for future use. 

1442 

1443 """ 

1444 # Create or coerce a protobuf request object. 

1445 # Minor optimization to avoid making a copy if the user passes 

1446 # in a pubsub.DetachSubscriptionRequest. 

1447 # There's no risk of modifying the input as we've already verified 

1448 # there are no flattened fields. 

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

1450 request = pubsub.DetachSubscriptionRequest(request) 

1451 

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

1453 # and friendly error handling. 

1454 rpc = self._transport._wrapped_methods[self._transport.detach_subscription] 

1455 

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

1457 # add these here. 

1458 metadata = tuple(metadata) + ( 

1459 gapic_v1.routing_header.to_grpc_metadata( 

1460 (("subscription", request.subscription),) 

1461 ), 

1462 ) 

1463 

1464 # Send the request. 

1465 response = rpc( 

1466 request, 

1467 retry=retry, 

1468 timeout=timeout, 

1469 metadata=metadata, 

1470 ) 

1471 

1472 # Done; return the response. 

1473 return response 

1474 

1475 def __enter__(self) -> "PublisherClient": 

1476 return self 

1477 

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

1479 """Releases underlying transport's resources. 

1480 

1481 .. warning:: 

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

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

1484 and may cause errors in other clients! 

1485 """ 

1486 self.transport.close() 

1487 

1488 def set_iam_policy( 

1489 self, 

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

1491 *, 

1492 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1493 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1494 metadata: Sequence[Tuple[str, str]] = (), 

1495 ) -> policy_pb2.Policy: 

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

1497 

1498 Replaces any existing policy. 

1499 

1500 Args: 

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

1502 The request object. Request message for `SetIamPolicy` 

1503 method. 

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

1505 should be retried. 

1506 timeout (TimeoutType): 

1507 The timeout for this request. 

1508 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1509 sent along with the request as metadata. 

1510 Returns: 

1511 ~.policy_pb2.Policy: 

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

1513 It is used to specify access control policies for Cloud 

1514 Platform resources. 

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

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

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

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

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

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

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

1522 expression that further constrains the role binding 

1523 based on attributes about the request and/or target 

1524 resource. 

1525 

1526 **JSON Example** 

1527 

1528 :: 

1529 

1530 { 

1531 "bindings": [ 

1532 { 

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

1534 "members": [ 

1535 "user:mike@example.com", 

1536 "group:admins@example.com", 

1537 "domain:google.com", 

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

1539 ] 

1540 }, 

1541 { 

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

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

1544 "condition": { 

1545 "title": "expirable access", 

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

1547 "expression": "request.time < 

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

1549 } 

1550 } 

1551 ] 

1552 } 

1553 

1554 **YAML Example** 

1555 

1556 :: 

1557 

1558 bindings: 

1559 - members: 

1560 - user:mike@example.com 

1561 - group:admins@example.com 

1562 - domain:google.com 

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

1564 role: roles/resourcemanager.organizationAdmin 

1565 - members: 

1566 - user:eve@example.com 

1567 role: roles/resourcemanager.organizationViewer 

1568 condition: 

1569 title: expirable access 

1570 description: Does not grant access after Sep 2020 

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

1572 

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

1574 developer's 

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

1576 """ 

1577 # Create or coerce a protobuf request object. 

1578 

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

1580 # so it must be constructed via keyword expansion. 

1581 if isinstance(request, dict): 

1582 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

1583 

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

1585 # and friendly error handling. 

1586 rpc = gapic_v1.method.wrap_method( 

1587 self._transport.set_iam_policy, 

1588 default_timeout=None, 

1589 client_info=DEFAULT_CLIENT_INFO, 

1590 ) 

1591 

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

1593 # add these here. 

1594 metadata = tuple(metadata) + ( 

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

1596 ) 

1597 

1598 # Send the request. 

1599 response = rpc( 

1600 request, 

1601 retry=retry, 

1602 timeout=timeout, 

1603 metadata=metadata, 

1604 ) 

1605 

1606 # Done; return the response. 

1607 return response 

1608 

1609 def get_iam_policy( 

1610 self, 

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

1612 *, 

1613 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1614 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1615 metadata: Sequence[Tuple[str, str]] = (), 

1616 ) -> policy_pb2.Policy: 

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

1618 

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

1620 policy set. 

1621 

1622 Args: 

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

1624 The request object. Request message for `GetIamPolicy` 

1625 method. 

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

1627 any, should be retried. 

1628 timeout (TimeoutType): 

1629 The timeout for this request. 

1630 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1631 sent along with the request as metadata. 

1632 Returns: 

1633 ~.policy_pb2.Policy: 

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

1635 It is used to specify access control policies for Cloud 

1636 Platform resources. 

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

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

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

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

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

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

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

1644 expression that further constrains the role binding 

1645 based on attributes about the request and/or target 

1646 resource. 

1647 

1648 **JSON Example** 

1649 

1650 :: 

1651 

1652 { 

1653 "bindings": [ 

1654 { 

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

1656 "members": [ 

1657 "user:mike@example.com", 

1658 "group:admins@example.com", 

1659 "domain:google.com", 

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

1661 ] 

1662 }, 

1663 { 

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

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

1666 "condition": { 

1667 "title": "expirable access", 

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

1669 "expression": "request.time < 

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

1671 } 

1672 } 

1673 ] 

1674 } 

1675 

1676 **YAML Example** 

1677 

1678 :: 

1679 

1680 bindings: 

1681 - members: 

1682 - user:mike@example.com 

1683 - group:admins@example.com 

1684 - domain:google.com 

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

1686 role: roles/resourcemanager.organizationAdmin 

1687 - members: 

1688 - user:eve@example.com 

1689 role: roles/resourcemanager.organizationViewer 

1690 condition: 

1691 title: expirable access 

1692 description: Does not grant access after Sep 2020 

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

1694 

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

1696 developer's 

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

1698 """ 

1699 # Create or coerce a protobuf request object. 

1700 

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

1702 # so it must be constructed via keyword expansion. 

1703 if isinstance(request, dict): 

1704 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

1705 

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

1707 # and friendly error handling. 

1708 rpc = gapic_v1.method.wrap_method( 

1709 self._transport.get_iam_policy, 

1710 default_timeout=None, 

1711 client_info=DEFAULT_CLIENT_INFO, 

1712 ) 

1713 

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

1715 # add these here. 

1716 metadata = tuple(metadata) + ( 

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

1718 ) 

1719 

1720 # Send the request. 

1721 response = rpc( 

1722 request, 

1723 retry=retry, 

1724 timeout=timeout, 

1725 metadata=metadata, 

1726 ) 

1727 

1728 # Done; return the response. 

1729 return response 

1730 

1731 def test_iam_permissions( 

1732 self, 

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

1734 *, 

1735 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1736 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

1737 metadata: Sequence[Tuple[str, str]] = (), 

1738 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

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

1740 policy for a function. 

1741 

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

1743 of permissions, not a NOT_FOUND error. 

1744 

1745 Args: 

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

1747 The request object. Request message for 

1748 `TestIamPermissions` method. 

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

1750 if any, should be retried. 

1751 timeout (TimeoutType): 

1752 The timeout for this request. 

1753 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1754 sent along with the request as metadata. 

1755 Returns: 

1756 ~.iam_policy_pb2.TestIamPermissionsResponse: 

1757 Response message for ``TestIamPermissions`` method. 

1758 """ 

1759 # Create or coerce a protobuf request object. 

1760 

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

1762 # so it must be constructed via keyword expansion. 

1763 if isinstance(request, dict): 

1764 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

1765 

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

1767 # and friendly error handling. 

1768 rpc = gapic_v1.method.wrap_method( 

1769 self._transport.test_iam_permissions, 

1770 default_timeout=None, 

1771 client_info=DEFAULT_CLIENT_INFO, 

1772 ) 

1773 

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

1775 # add these here. 

1776 metadata = tuple(metadata) + ( 

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

1778 ) 

1779 

1780 # Send the request. 

1781 response = rpc( 

1782 request, 

1783 retry=retry, 

1784 timeout=timeout, 

1785 metadata=metadata, 

1786 ) 

1787 

1788 # Done; return the response. 

1789 return response 

1790 

1791 

1792DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1793 client_library_version=package_version.__version__ 

1794) 

1795 

1796 

1797__all__ = ("PublisherClient",)