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

311 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:03 +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 

63from .transports.rest import PublisherRestTransport 

64 

65 

66class PublisherClientMeta(type): 

67 """Metaclass for the Publisher client. 

68 

69 This provides class-level methods for building and retrieving 

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

71 objects. 

72 """ 

73 

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

75 _transport_registry["grpc"] = PublisherGrpcTransport 

76 _transport_registry["grpc_asyncio"] = PublisherGrpcAsyncIOTransport 

77 _transport_registry["rest"] = PublisherRestTransport 

78 

79 def get_transport_class( 

80 cls, 

81 label: Optional[str] = None, 

82 ) -> Type[PublisherTransport]: 

83 """Returns an appropriate transport class. 

84 

85 Args: 

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

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

88 

89 Returns: 

90 The transport class to use. 

91 """ 

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

93 if label: 

94 return cls._transport_registry[label] 

95 

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

97 # in the dictionary). 

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

99 

100 

101class PublisherClient(metaclass=PublisherClientMeta): 

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

103 and to send messages to a topic. 

104 """ 

105 

106 @staticmethod 

107 def _get_default_mtls_endpoint(api_endpoint): 

108 """Converts api endpoint to mTLS endpoint. 

109 

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

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

112 Args: 

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

114 Returns: 

115 str: converted mTLS api endpoint. 

116 """ 

117 if not api_endpoint: 

118 return api_endpoint 

119 

120 mtls_endpoint_re = re.compile( 

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

122 ) 

123 

124 m = mtls_endpoint_re.match(api_endpoint) 

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

126 if mtls or not googledomain: 

127 return api_endpoint 

128 

129 if sandbox: 

130 return api_endpoint.replace( 

131 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

132 ) 

133 

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

135 

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

137 # this service 

138 _DEFAULT_SCOPES = ( 

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

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

141 ) 

142 

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

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

145 

146 DEFAULT_ENDPOINT = "pubsub.googleapis.com" 

147 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

148 DEFAULT_ENDPOINT 

149 ) 

150 

151 @classmethod 

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

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

154 info. 

155 

156 Args: 

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

158 args: Additional arguments to pass to the constructor. 

159 kwargs: Additional arguments to pass to the constructor. 

160 

161 Returns: 

162 PublisherClient: The constructed client. 

163 """ 

164 credentials = service_account.Credentials.from_service_account_info(info) 

165 kwargs["credentials"] = credentials 

166 return cls(*args, **kwargs) 

167 

168 @classmethod 

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

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

171 file. 

172 

173 Args: 

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

175 file. 

176 args: Additional arguments to pass to the constructor. 

177 kwargs: Additional arguments to pass to the constructor. 

178 

179 Returns: 

180 PublisherClient: The constructed client. 

181 """ 

182 credentials = service_account.Credentials.from_service_account_file(filename) 

183 kwargs["credentials"] = credentials 

184 return cls(*args, **kwargs) 

185 

186 from_service_account_json = from_service_account_file 

187 

188 @property 

189 def transport(self) -> PublisherTransport: 

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

191 

192 Returns: 

193 PublisherTransport: The transport used by the client 

194 instance. 

195 """ 

196 return self._transport 

197 

198 @staticmethod 

199 def schema_path( 

200 project: str, 

201 schema: str, 

202 ) -> str: 

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

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

205 project=project, 

206 schema=schema, 

207 ) 

208 

209 @staticmethod 

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

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

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

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

214 

215 @staticmethod 

216 def subscription_path( 

217 project: str, 

218 subscription: str, 

219 ) -> str: 

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

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

222 project=project, 

223 subscription=subscription, 

224 ) 

225 

226 @staticmethod 

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

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

229 m = re.match( 

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

231 ) 

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

233 

234 @staticmethod 

235 def topic_path( 

236 project: str, 

237 topic: str, 

238 ) -> str: 

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

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

241 project=project, 

242 topic=topic, 

243 ) 

244 

245 @staticmethod 

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

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

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

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

250 

251 @staticmethod 

252 def common_billing_account_path( 

253 billing_account: str, 

254 ) -> str: 

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

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

257 billing_account=billing_account, 

258 ) 

259 

260 @staticmethod 

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

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

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

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

265 

266 @staticmethod 

267 def common_folder_path( 

268 folder: str, 

269 ) -> str: 

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

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

272 folder=folder, 

273 ) 

274 

275 @staticmethod 

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

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

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

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

280 

281 @staticmethod 

282 def common_organization_path( 

283 organization: str, 

284 ) -> str: 

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

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

287 organization=organization, 

288 ) 

289 

290 @staticmethod 

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

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

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

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

295 

296 @staticmethod 

297 def common_project_path( 

298 project: str, 

299 ) -> str: 

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

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

302 project=project, 

303 ) 

304 

305 @staticmethod 

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

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

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

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

310 

311 @staticmethod 

312 def common_location_path( 

313 project: str, 

314 location: str, 

315 ) -> str: 

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

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

318 project=project, 

319 location=location, 

320 ) 

321 

322 @staticmethod 

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

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

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

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

327 

328 @classmethod 

329 def get_mtls_endpoint_and_cert_source( 

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

331 ): 

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

333 

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

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

336 client cert source is None. 

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

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

339 source is None. 

340 

341 The API endpoint is determined in the following order: 

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

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

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

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

346 use the default API endpoint. 

347 

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

349 

350 Args: 

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

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

353 in this method. 

354 

355 Returns: 

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

357 client cert source to use. 

358 

359 Raises: 

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

361 """ 

362 if client_options is None: 

363 client_options = client_options_lib.ClientOptions() 

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

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

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

367 raise ValueError( 

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

369 ) 

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

371 raise MutualTLSChannelError( 

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

373 ) 

374 

375 # Figure out the client cert source to use. 

376 client_cert_source = None 

377 if use_client_cert == "true": 

378 if client_options.client_cert_source: 

379 client_cert_source = client_options.client_cert_source 

380 elif mtls.has_default_client_cert_source(): 

381 client_cert_source = mtls.default_client_cert_source() 

382 

383 # Figure out which api endpoint to use. 

384 if client_options.api_endpoint is not None: 

385 api_endpoint = client_options.api_endpoint 

386 elif use_mtls_endpoint == "always" or ( 

387 use_mtls_endpoint == "auto" and client_cert_source 

388 ): 

389 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

390 else: 

391 api_endpoint = cls.DEFAULT_ENDPOINT 

392 

393 return api_endpoint, client_cert_source 

394 

395 def __init__( 

396 self, 

397 *, 

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

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

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

401 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

402 ) -> None: 

403 """Instantiates the publisher client. 

404 

405 Args: 

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

407 authorization credentials to attach to requests. These 

408 credentials identify the application to the service; if none 

409 are specified, the client will attempt to ascertain the 

410 credentials from the environment. 

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

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

413 automatically. 

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

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

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

417 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT 

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

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

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

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

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

423 precedence if provided. 

424 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

426 to provide client certificate for mutual TLS transport. If 

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

428 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

429 set, no client certificate will be used. 

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

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

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

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

434 your own client library. 

435 

436 Raises: 

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

438 creation failed for any reason. 

439 """ 

440 if isinstance(client_options, dict): 

441 client_options = client_options_lib.from_dict(client_options) 

442 if client_options is None: 

443 client_options = client_options_lib.ClientOptions() 

444 client_options = cast(client_options_lib.ClientOptions, client_options) 

445 

446 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( 

447 client_options 

448 ) 

449 

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

451 if api_key_value and credentials: 

452 raise ValueError( 

453 "client_options.api_key and credentials are mutually exclusive" 

454 ) 

455 

456 # Save or instantiate the transport. 

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

458 # instance provides an extensibility point for unusual situations. 

459 if isinstance(transport, PublisherTransport): 

460 # transport is a PublisherTransport instance. 

461 if credentials or client_options.credentials_file or api_key_value: 

462 raise ValueError( 

463 "When providing a transport instance, " 

464 "provide its credentials directly." 

465 ) 

466 if client_options.scopes: 

467 raise ValueError( 

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

469 "directly." 

470 ) 

471 self._transport = transport 

472 else: 

473 import google.auth._default # type: ignore 

474 

475 if api_key_value and hasattr( 

476 google.auth._default, "get_api_key_credentials" 

477 ): 

478 credentials = google.auth._default.get_api_key_credentials( 

479 api_key_value 

480 ) 

481 

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

483 

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

485 if emulator_host: 

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

487 channel = grpc.insecure_channel(target=emulator_host) 

488 else: 

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

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

491 

492 self._transport = Transport( 

493 credentials=credentials, 

494 credentials_file=client_options.credentials_file, 

495 host=api_endpoint, 

496 scopes=client_options.scopes, 

497 client_cert_source_for_mtls=client_cert_source_func, 

498 quota_project_id=client_options.quota_project_id, 

499 client_info=client_info, 

500 always_use_jwt_access=True, 

501 api_audience=client_options.api_audience, 

502 ) 

503 

504 def create_topic( 

505 self, 

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

507 *, 

508 name: Optional[str] = None, 

509 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

510 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

512 ) -> pubsub.Topic: 

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

514 name rules] 

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

516 

517 .. code-block:: python 

518 

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

520 # code template only. 

521 # It will require modifications to work: 

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

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

524 # client as shown in: 

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

526 from google import pubsub_v1 

527 

528 def sample_create_topic(): 

529 # Create a client 

530 client = pubsub_v1.PublisherClient() 

531 

532 # Initialize request argument(s) 

533 request = pubsub_v1.Topic( 

534 name="name_value", 

535 ) 

536 

537 # Make the request 

538 response = client.create_topic(request=request) 

539 

540 # Handle the response 

541 print(response) 

542 

543 Args: 

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

545 The request object. A topic resource. 

546 name (str): 

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

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

549 must start with a letter, and contain only letters 

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

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

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

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

554 start with ``"goog"``. 

555 

556 This corresponds to the ``name`` field 

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

558 should not be set. 

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

560 should be retried. 

561 timeout (TimeoutType): 

562 The timeout for this request. 

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

564 sent along with the request as metadata. 

565 

566 Returns: 

567 google.pubsub_v1.types.Topic: 

568 A topic resource. 

569 """ 

570 # Create or coerce a protobuf request object. 

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

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

573 has_flattened_params = any([name]) 

574 if request is not None and has_flattened_params: 

575 raise ValueError( 

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

577 "the individual field arguments should be set." 

578 ) 

579 

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

581 # in a pubsub.Topic. 

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

583 # there are no flattened fields. 

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

585 request = pubsub.Topic(request) 

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

587 # request, apply these. 

588 if name is not None: 

589 request.name = name 

590 

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

592 # and friendly error handling. 

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

594 

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

596 # add these here. 

597 metadata = tuple(metadata) + ( 

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

599 ) 

600 

601 # Send the request. 

602 response = rpc( 

603 request, 

604 retry=retry, 

605 timeout=timeout, 

606 metadata=metadata, 

607 ) 

608 

609 # Done; return the response. 

610 return response 

611 

612 def update_topic( 

613 self, 

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

615 *, 

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

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

618 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

619 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

621 ) -> pubsub.Topic: 

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

623 properties of a topic are not modifiable. 

624 

625 .. code-block:: python 

626 

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

628 # code template only. 

629 # It will require modifications to work: 

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

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

632 # client as shown in: 

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

634 from google import pubsub_v1 

635 

636 def sample_update_topic(): 

637 # Create a client 

638 client = pubsub_v1.PublisherClient() 

639 

640 # Initialize request argument(s) 

641 topic = pubsub_v1.Topic() 

642 topic.name = "name_value" 

643 

644 request = pubsub_v1.UpdateTopicRequest( 

645 topic=topic, 

646 ) 

647 

648 # Make the request 

649 response = client.update_topic(request=request) 

650 

651 # Handle the response 

652 print(response) 

653 

654 Args: 

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

656 The request object. Request for the UpdateTopic method. 

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

658 Required. The updated topic object. 

659 This corresponds to the ``topic`` field 

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

661 should not be set. 

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

663 Required. Indicates which fields in the provided topic 

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

665 ``update_mask`` contains "message_storage_policy" but 

666 the ``message_storage_policy`` is not set in the 

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

668 determined by the policy configured at the project or 

669 organization level. 

670 

671 This corresponds to the ``update_mask`` field 

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

673 should not be set. 

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

675 should be retried. 

676 timeout (TimeoutType): 

677 The timeout for this request. 

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

679 sent along with the request as metadata. 

680 

681 Returns: 

682 google.pubsub_v1.types.Topic: 

683 A topic resource. 

684 """ 

685 # Create or coerce a protobuf request object. 

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

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

688 has_flattened_params = any([topic, update_mask]) 

689 if request is not None and has_flattened_params: 

690 raise ValueError( 

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

692 "the individual field arguments should be set." 

693 ) 

694 

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

696 # in a pubsub.UpdateTopicRequest. 

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

698 # there are no flattened fields. 

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

700 request = pubsub.UpdateTopicRequest(request) 

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

702 # request, apply these. 

703 if topic is not None: 

704 request.topic = topic 

705 if update_mask is not None: 

706 request.update_mask = update_mask 

707 

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

709 # and friendly error handling. 

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

711 

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

713 # add these here. 

714 metadata = tuple(metadata) + ( 

715 gapic_v1.routing_header.to_grpc_metadata( 

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

717 ), 

718 ) 

719 

720 # Send the request. 

721 response = rpc( 

722 request, 

723 retry=retry, 

724 timeout=timeout, 

725 metadata=metadata, 

726 ) 

727 

728 # Done; return the response. 

729 return response 

730 

731 def publish( 

732 self, 

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

734 *, 

735 topic: Optional[str] = None, 

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

737 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

738 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

740 ) -> pubsub.PublishResponse: 

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

742 the topic does not exist. 

743 

744 .. code-block:: python 

745 

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

747 # code template only. 

748 # It will require modifications to work: 

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

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

751 # client as shown in: 

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

753 from google import pubsub_v1 

754 

755 def sample_publish(): 

756 # Create a client 

757 client = pubsub_v1.PublisherClient() 

758 

759 # Initialize request argument(s) 

760 request = pubsub_v1.PublishRequest( 

761 topic="topic_value", 

762 ) 

763 

764 # Make the request 

765 response = client.publish(request=request) 

766 

767 # Handle the response 

768 print(response) 

769 

770 Args: 

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

772 The request object. Request for the Publish method. 

773 topic (str): 

774 Required. The messages in the request will be published 

775 on this topic. Format is 

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

777 

778 This corresponds to the ``topic`` field 

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

780 should not be set. 

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

782 Required. The messages to publish. 

783 This corresponds to the ``messages`` field 

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

785 should not be set. 

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

787 should be retried. 

788 timeout (TimeoutType): 

789 The timeout for this request. 

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

791 sent along with the request as metadata. 

792 

793 Returns: 

794 google.pubsub_v1.types.PublishResponse: 

795 Response for the Publish method. 

796 """ 

797 # Create or coerce a protobuf request object. 

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

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

800 has_flattened_params = any([topic, messages]) 

801 if request is not None and has_flattened_params: 

802 raise ValueError( 

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

804 "the individual field arguments should be set." 

805 ) 

806 

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

808 # in a pubsub.PublishRequest. 

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

810 # there are no flattened fields. 

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

812 request = pubsub.PublishRequest(request) 

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

814 # request, apply these. 

815 if topic is not None: 

816 request.topic = topic 

817 if messages is not None: 

818 request.messages = messages 

819 

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

821 # and friendly error handling. 

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

823 

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

825 # add these here. 

826 metadata = tuple(metadata) + ( 

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

828 ) 

829 

830 # Send the request. 

831 response = rpc( 

832 request, 

833 retry=retry, 

834 timeout=timeout, 

835 metadata=metadata, 

836 ) 

837 

838 # Done; return the response. 

839 return response 

840 

841 def get_topic( 

842 self, 

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

844 *, 

845 topic: Optional[str] = None, 

846 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

847 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

849 ) -> pubsub.Topic: 

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

851 

852 .. code-block:: python 

853 

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

855 # code template only. 

856 # It will require modifications to work: 

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

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

859 # client as shown in: 

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

861 from google import pubsub_v1 

862 

863 def sample_get_topic(): 

864 # Create a client 

865 client = pubsub_v1.PublisherClient() 

866 

867 # Initialize request argument(s) 

868 request = pubsub_v1.GetTopicRequest( 

869 topic="topic_value", 

870 ) 

871 

872 # Make the request 

873 response = client.get_topic(request=request) 

874 

875 # Handle the response 

876 print(response) 

877 

878 Args: 

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

880 The request object. Request for the GetTopic method. 

881 topic (str): 

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

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

884 

885 This corresponds to the ``topic`` field 

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

887 should not be set. 

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

889 should be retried. 

890 timeout (TimeoutType): 

891 The timeout for this request. 

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

893 sent along with the request as metadata. 

894 

895 Returns: 

896 google.pubsub_v1.types.Topic: 

897 A topic resource. 

898 """ 

899 # Create or coerce a protobuf request object. 

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

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

902 has_flattened_params = any([topic]) 

903 if request is not None and has_flattened_params: 

904 raise ValueError( 

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

906 "the individual field arguments should be set." 

907 ) 

908 

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

910 # in a pubsub.GetTopicRequest. 

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

912 # there are no flattened fields. 

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

914 request = pubsub.GetTopicRequest(request) 

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

916 # request, apply these. 

917 if topic is not None: 

918 request.topic = topic 

919 

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

921 # and friendly error handling. 

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

923 

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

925 # add these here. 

926 metadata = tuple(metadata) + ( 

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

928 ) 

929 

930 # Send the request. 

931 response = rpc( 

932 request, 

933 retry=retry, 

934 timeout=timeout, 

935 metadata=metadata, 

936 ) 

937 

938 # Done; return the response. 

939 return response 

940 

941 def list_topics( 

942 self, 

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

944 *, 

945 project: Optional[str] = None, 

946 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

947 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

949 ) -> pagers.ListTopicsPager: 

950 r"""Lists matching topics. 

951 

952 .. code-block:: python 

953 

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

955 # code template only. 

956 # It will require modifications to work: 

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

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

959 # client as shown in: 

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

961 from google import pubsub_v1 

962 

963 def sample_list_topics(): 

964 # Create a client 

965 client = pubsub_v1.PublisherClient() 

966 

967 # Initialize request argument(s) 

968 request = pubsub_v1.ListTopicsRequest( 

969 project="project_value", 

970 ) 

971 

972 # Make the request 

973 page_result = client.list_topics(request=request) 

974 

975 # Handle the response 

976 for response in page_result: 

977 print(response) 

978 

979 Args: 

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

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

982 project (str): 

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

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

985 

986 This corresponds to the ``project`` field 

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

988 should not be set. 

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

990 should be retried. 

991 timeout (TimeoutType): 

992 The timeout for this request. 

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

994 sent along with the request as metadata. 

995 

996 Returns: 

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

998 Response for the ListTopics method. 

999 

1000 Iterating over this object will yield results and 

1001 resolve additional pages automatically. 

1002 

1003 """ 

1004 # Create or coerce a protobuf request object. 

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

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

1007 has_flattened_params = any([project]) 

1008 if request is not None and has_flattened_params: 

1009 raise ValueError( 

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

1011 "the individual field arguments should be set." 

1012 ) 

1013 

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

1015 # in a pubsub.ListTopicsRequest. 

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

1017 # there are no flattened fields. 

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

1019 request = pubsub.ListTopicsRequest(request) 

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

1021 # request, apply these. 

1022 if project is not None: 

1023 request.project = project 

1024 

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

1026 # and friendly error handling. 

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

1028 

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

1030 # add these here. 

1031 metadata = tuple(metadata) + ( 

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

1033 ) 

1034 

1035 # Send the request. 

1036 response = rpc( 

1037 request, 

1038 retry=retry, 

1039 timeout=timeout, 

1040 metadata=metadata, 

1041 ) 

1042 

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

1044 # an `__iter__` convenience method. 

1045 response = pagers.ListTopicsPager( 

1046 method=rpc, 

1047 request=request, 

1048 response=response, 

1049 metadata=metadata, 

1050 ) 

1051 

1052 # Done; return the response. 

1053 return response 

1054 

1055 def list_topic_subscriptions( 

1056 self, 

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

1058 *, 

1059 topic: Optional[str] = None, 

1060 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1061 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1063 ) -> pagers.ListTopicSubscriptionsPager: 

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

1065 topic. 

1066 

1067 .. code-block:: python 

1068 

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

1070 # code template only. 

1071 # It will require modifications to work: 

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

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

1074 # client as shown in: 

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

1076 from google import pubsub_v1 

1077 

1078 def sample_list_topic_subscriptions(): 

1079 # Create a client 

1080 client = pubsub_v1.PublisherClient() 

1081 

1082 # Initialize request argument(s) 

1083 request = pubsub_v1.ListTopicSubscriptionsRequest( 

1084 topic="topic_value", 

1085 ) 

1086 

1087 # Make the request 

1088 page_result = client.list_topic_subscriptions(request=request) 

1089 

1090 # Handle the response 

1091 for response in page_result: 

1092 print(response) 

1093 

1094 Args: 

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

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

1097 topic (str): 

1098 Required. The name of the topic that subscriptions are 

1099 attached to. Format is 

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

1101 

1102 This corresponds to the ``topic`` field 

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

1104 should not be set. 

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

1106 should be retried. 

1107 timeout (TimeoutType): 

1108 The timeout for this request. 

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

1110 sent along with the request as metadata. 

1111 

1112 Returns: 

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

1114 Response for the ListTopicSubscriptions method. 

1115 

1116 Iterating over this object will yield results and 

1117 resolve additional pages automatically. 

1118 

1119 """ 

1120 # Create or coerce a protobuf request object. 

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

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

1123 has_flattened_params = any([topic]) 

1124 if request is not None and has_flattened_params: 

1125 raise ValueError( 

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

1127 "the individual field arguments should be set." 

1128 ) 

1129 

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

1131 # in a pubsub.ListTopicSubscriptionsRequest. 

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

1133 # there are no flattened fields. 

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

1135 request = pubsub.ListTopicSubscriptionsRequest(request) 

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

1137 # request, apply these. 

1138 if topic is not None: 

1139 request.topic = topic 

1140 

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

1142 # and friendly error handling. 

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

1144 

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

1146 # add these here. 

1147 metadata = tuple(metadata) + ( 

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

1149 ) 

1150 

1151 # Send the request. 

1152 response = rpc( 

1153 request, 

1154 retry=retry, 

1155 timeout=timeout, 

1156 metadata=metadata, 

1157 ) 

1158 

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

1160 # an `__iter__` convenience method. 

1161 response = pagers.ListTopicSubscriptionsPager( 

1162 method=rpc, 

1163 request=request, 

1164 response=response, 

1165 metadata=metadata, 

1166 ) 

1167 

1168 # Done; return the response. 

1169 return response 

1170 

1171 def list_topic_snapshots( 

1172 self, 

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

1174 *, 

1175 topic: Optional[str] = None, 

1176 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1177 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1179 ) -> pagers.ListTopicSnapshotsPager: 

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

1181 used in 

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

1183 operations, which allow you to manage message acknowledgments in 

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

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

1186 

1187 .. code-block:: python 

1188 

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

1190 # code template only. 

1191 # It will require modifications to work: 

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

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

1194 # client as shown in: 

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

1196 from google import pubsub_v1 

1197 

1198 def sample_list_topic_snapshots(): 

1199 # Create a client 

1200 client = pubsub_v1.PublisherClient() 

1201 

1202 # Initialize request argument(s) 

1203 request = pubsub_v1.ListTopicSnapshotsRequest( 

1204 topic="topic_value", 

1205 ) 

1206 

1207 # Make the request 

1208 page_result = client.list_topic_snapshots(request=request) 

1209 

1210 # Handle the response 

1211 for response in page_result: 

1212 print(response) 

1213 

1214 Args: 

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

1216 The request object. Request for the ``ListTopicSnapshots`` 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`` method. 

1333 topic (str): 

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

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

1336 

1337 This corresponds to the ``topic`` field 

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

1339 should not be set. 

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

1341 should be retried. 

1342 timeout (TimeoutType): 

1343 The timeout for this request. 

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

1345 sent along with the request as metadata. 

1346 """ 

1347 # Create or coerce a protobuf request object. 

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

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

1350 has_flattened_params = any([topic]) 

1351 if request is not None and has_flattened_params: 

1352 raise ValueError( 

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

1354 "the individual field arguments should be set." 

1355 ) 

1356 

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

1358 # in a pubsub.DeleteTopicRequest. 

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

1360 # there are no flattened fields. 

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

1362 request = pubsub.DeleteTopicRequest(request) 

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

1364 # request, apply these. 

1365 if topic is not None: 

1366 request.topic = topic 

1367 

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

1369 # and friendly error handling. 

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

1371 

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

1373 # add these here. 

1374 metadata = tuple(metadata) + ( 

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

1376 ) 

1377 

1378 # Send the request. 

1379 rpc( 

1380 request, 

1381 retry=retry, 

1382 timeout=timeout, 

1383 metadata=metadata, 

1384 ) 

1385 

1386 def detach_subscription( 

1387 self, 

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

1389 *, 

1390 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1391 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1393 ) -> pubsub.DetachSubscriptionResponse: 

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

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

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

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

1398 will stop. 

1399 

1400 .. code-block:: python 

1401 

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

1403 # code template only. 

1404 # It will require modifications to work: 

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

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

1407 # client as shown in: 

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

1409 from google import pubsub_v1 

1410 

1411 def sample_detach_subscription(): 

1412 # Create a client 

1413 client = pubsub_v1.PublisherClient() 

1414 

1415 # Initialize request argument(s) 

1416 request = pubsub_v1.DetachSubscriptionRequest( 

1417 subscription="subscription_value", 

1418 ) 

1419 

1420 # Make the request 

1421 response = client.detach_subscription(request=request) 

1422 

1423 # Handle the response 

1424 print(response) 

1425 

1426 Args: 

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

1428 The request object. Request for the DetachSubscription 

1429 method. 

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

1431 should be retried. 

1432 timeout (TimeoutType): 

1433 The timeout for this request. 

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

1435 sent along with the request as metadata. 

1436 

1437 Returns: 

1438 google.pubsub_v1.types.DetachSubscriptionResponse: 

1439 Response for the DetachSubscription 

1440 method. Reserved for future use. 

1441 

1442 """ 

1443 # Create or coerce a protobuf request object. 

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

1445 # in a pubsub.DetachSubscriptionRequest. 

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

1447 # there are no flattened fields. 

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

1449 request = pubsub.DetachSubscriptionRequest(request) 

1450 

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

1452 # and friendly error handling. 

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

1454 

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

1456 # add these here. 

1457 metadata = tuple(metadata) + ( 

1458 gapic_v1.routing_header.to_grpc_metadata( 

1459 (("subscription", request.subscription),) 

1460 ), 

1461 ) 

1462 

1463 # Send the request. 

1464 response = rpc( 

1465 request, 

1466 retry=retry, 

1467 timeout=timeout, 

1468 metadata=metadata, 

1469 ) 

1470 

1471 # Done; return the response. 

1472 return response 

1473 

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

1475 return self 

1476 

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

1478 """Releases underlying transport's resources. 

1479 

1480 .. warning:: 

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

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

1483 and may cause errors in other clients! 

1484 """ 

1485 self.transport.close() 

1486 

1487 def set_iam_policy( 

1488 self, 

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

1490 *, 

1491 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1492 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1494 ) -> policy_pb2.Policy: 

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

1496 

1497 Replaces any existing policy. 

1498 

1499 Args: 

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

1501 The request object. Request message for `SetIamPolicy` 

1502 method. 

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

1504 should be retried. 

1505 timeout (TimeoutType): 

1506 The timeout for this request. 

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

1508 sent along with the request as metadata. 

1509 Returns: 

1510 ~.policy_pb2.Policy: 

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

1512 It is used to specify access control policies for Cloud 

1513 Platform resources. 

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

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

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

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

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

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

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

1521 expression that further constrains the role binding 

1522 based on attributes about the request and/or target 

1523 resource. 

1524 

1525 **JSON Example** 

1526 

1527 :: 

1528 

1529 { 

1530 "bindings": [ 

1531 { 

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

1533 "members": [ 

1534 "user:mike@example.com", 

1535 "group:admins@example.com", 

1536 "domain:google.com", 

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

1538 ] 

1539 }, 

1540 { 

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

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

1543 "condition": { 

1544 "title": "expirable access", 

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

1546 "expression": "request.time < 

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

1548 } 

1549 } 

1550 ] 

1551 } 

1552 

1553 **YAML Example** 

1554 

1555 :: 

1556 

1557 bindings: 

1558 - members: 

1559 - user:mike@example.com 

1560 - group:admins@example.com 

1561 - domain:google.com 

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

1563 role: roles/resourcemanager.organizationAdmin 

1564 - members: 

1565 - user:eve@example.com 

1566 role: roles/resourcemanager.organizationViewer 

1567 condition: 

1568 title: expirable access 

1569 description: Does not grant access after Sep 2020 

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

1571 

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

1573 developer's 

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

1575 """ 

1576 # Create or coerce a protobuf request object. 

1577 

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

1579 # so it must be constructed via keyword expansion. 

1580 if isinstance(request, dict): 

1581 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

1582 

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

1584 # and friendly error handling. 

1585 rpc = gapic_v1.method.wrap_method( 

1586 self._transport.set_iam_policy, 

1587 default_timeout=None, 

1588 client_info=DEFAULT_CLIENT_INFO, 

1589 ) 

1590 

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

1592 # add these here. 

1593 metadata = tuple(metadata) + ( 

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

1595 ) 

1596 

1597 # Send the request. 

1598 response = rpc( 

1599 request, 

1600 retry=retry, 

1601 timeout=timeout, 

1602 metadata=metadata, 

1603 ) 

1604 

1605 # Done; return the response. 

1606 return response 

1607 

1608 def get_iam_policy( 

1609 self, 

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

1611 *, 

1612 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1613 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1615 ) -> policy_pb2.Policy: 

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

1617 

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

1619 policy set. 

1620 

1621 Args: 

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

1623 The request object. Request message for `GetIamPolicy` 

1624 method. 

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

1626 any, should be retried. 

1627 timeout (TimeoutType): 

1628 The timeout for this request. 

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

1630 sent along with the request as metadata. 

1631 Returns: 

1632 ~.policy_pb2.Policy: 

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

1634 It is used to specify access control policies for Cloud 

1635 Platform resources. 

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

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

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

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

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

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

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

1643 expression that further constrains the role binding 

1644 based on attributes about the request and/or target 

1645 resource. 

1646 

1647 **JSON Example** 

1648 

1649 :: 

1650 

1651 { 

1652 "bindings": [ 

1653 { 

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

1655 "members": [ 

1656 "user:mike@example.com", 

1657 "group:admins@example.com", 

1658 "domain:google.com", 

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

1660 ] 

1661 }, 

1662 { 

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

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

1665 "condition": { 

1666 "title": "expirable access", 

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

1668 "expression": "request.time < 

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

1670 } 

1671 } 

1672 ] 

1673 } 

1674 

1675 **YAML Example** 

1676 

1677 :: 

1678 

1679 bindings: 

1680 - members: 

1681 - user:mike@example.com 

1682 - group:admins@example.com 

1683 - domain:google.com 

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

1685 role: roles/resourcemanager.organizationAdmin 

1686 - members: 

1687 - user:eve@example.com 

1688 role: roles/resourcemanager.organizationViewer 

1689 condition: 

1690 title: expirable access 

1691 description: Does not grant access after Sep 2020 

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

1693 

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

1695 developer's 

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

1697 """ 

1698 # Create or coerce a protobuf request object. 

1699 

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

1701 # so it must be constructed via keyword expansion. 

1702 if isinstance(request, dict): 

1703 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

1704 

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

1706 # and friendly error handling. 

1707 rpc = gapic_v1.method.wrap_method( 

1708 self._transport.get_iam_policy, 

1709 default_timeout=None, 

1710 client_info=DEFAULT_CLIENT_INFO, 

1711 ) 

1712 

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

1714 # add these here. 

1715 metadata = tuple(metadata) + ( 

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

1717 ) 

1718 

1719 # Send the request. 

1720 response = rpc( 

1721 request, 

1722 retry=retry, 

1723 timeout=timeout, 

1724 metadata=metadata, 

1725 ) 

1726 

1727 # Done; return the response. 

1728 return response 

1729 

1730 def test_iam_permissions( 

1731 self, 

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

1733 *, 

1734 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1735 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1737 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

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

1739 policy for a function. 

1740 

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

1742 of permissions, not a NOT_FOUND error. 

1743 

1744 Args: 

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

1746 The request object. Request message for 

1747 `TestIamPermissions` method. 

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

1749 if any, should be retried. 

1750 timeout (TimeoutType): 

1751 The timeout for this request. 

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

1753 sent along with the request as metadata. 

1754 Returns: 

1755 ~.iam_policy_pb2.TestIamPermissionsResponse: 

1756 Response message for ``TestIamPermissions`` method. 

1757 """ 

1758 # Create or coerce a protobuf request object. 

1759 

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

1761 # so it must be constructed via keyword expansion. 

1762 if isinstance(request, dict): 

1763 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

1764 

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

1766 # and friendly error handling. 

1767 rpc = gapic_v1.method.wrap_method( 

1768 self._transport.test_iam_permissions, 

1769 default_timeout=None, 

1770 client_info=DEFAULT_CLIENT_INFO, 

1771 ) 

1772 

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

1774 # add these here. 

1775 metadata = tuple(metadata) + ( 

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

1777 ) 

1778 

1779 # Send the request. 

1780 response = rpc( 

1781 request, 

1782 retry=retry, 

1783 timeout=timeout, 

1784 metadata=metadata, 

1785 ) 

1786 

1787 # Done; return the response. 

1788 return response 

1789 

1790 

1791DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1792 client_library_version=package_version.__version__ 

1793) 

1794 

1795 

1796__all__ = ("PublisherClient",)