Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/pubsub_v1/services/publisher/transports/rest.py: 34%
430 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:03 +0000
« 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#
17from google.auth.transport.requests import AuthorizedSession # type: ignore
18import json # type: ignore
19import grpc # type: ignore
20from google.auth.transport.grpc import SslCredentials # type: ignore
21from google.auth import credentials as ga_credentials # type: ignore
22from google.api_core import exceptions as core_exceptions
23from google.api_core import retry as retries
24from google.api_core import rest_helpers
25from google.api_core import rest_streaming
26from google.api_core import path_template
27from google.api_core import gapic_v1
29from google.protobuf import json_format
30from google.iam.v1 import iam_policy_pb2 # type: ignore
31from google.iam.v1 import policy_pb2 # type: ignore
32from requests import __version__ as requests_version
33import dataclasses
34import re
35from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
36import warnings
38try:
39 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
40except AttributeError: # pragma: NO COVER
41 OptionalRetry = Union[retries.Retry, object] # type: ignore
44from google.iam.v1 import iam_policy_pb2 # type: ignore
45from google.iam.v1 import policy_pb2 # type: ignore
46from google.protobuf import empty_pb2 # type: ignore
47from google.pubsub_v1.types import pubsub
49from .base import PublisherTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
52DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
53 gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
54 grpc_version=None,
55 rest_version=requests_version,
56)
59class PublisherRestInterceptor:
60 """Interceptor for Publisher.
62 Interceptors are used to manipulate requests, request metadata, and responses
63 in arbitrary ways.
64 Example use cases include:
65 * Logging
66 * Verifying requests according to service or custom semantics
67 * Stripping extraneous information from responses
69 These use cases and more can be enabled by injecting an
70 instance of a custom subclass when constructing the PublisherRestTransport.
72 .. code-block:: python
73 class MyCustomPublisherInterceptor(PublisherRestInterceptor):
74 def pre_create_topic(self, request, metadata):
75 logging.log(f"Received request: {request}")
76 return request, metadata
78 def post_create_topic(self, response):
79 logging.log(f"Received response: {response}")
80 return response
82 def pre_delete_topic(self, request, metadata):
83 logging.log(f"Received request: {request}")
84 return request, metadata
86 def pre_detach_subscription(self, request, metadata):
87 logging.log(f"Received request: {request}")
88 return request, metadata
90 def post_detach_subscription(self, response):
91 logging.log(f"Received response: {response}")
92 return response
94 def pre_get_topic(self, request, metadata):
95 logging.log(f"Received request: {request}")
96 return request, metadata
98 def post_get_topic(self, response):
99 logging.log(f"Received response: {response}")
100 return response
102 def pre_list_topics(self, request, metadata):
103 logging.log(f"Received request: {request}")
104 return request, metadata
106 def post_list_topics(self, response):
107 logging.log(f"Received response: {response}")
108 return response
110 def pre_list_topic_snapshots(self, request, metadata):
111 logging.log(f"Received request: {request}")
112 return request, metadata
114 def post_list_topic_snapshots(self, response):
115 logging.log(f"Received response: {response}")
116 return response
118 def pre_list_topic_subscriptions(self, request, metadata):
119 logging.log(f"Received request: {request}")
120 return request, metadata
122 def post_list_topic_subscriptions(self, response):
123 logging.log(f"Received response: {response}")
124 return response
126 def pre_publish(self, request, metadata):
127 logging.log(f"Received request: {request}")
128 return request, metadata
130 def post_publish(self, response):
131 logging.log(f"Received response: {response}")
132 return response
134 def pre_update_topic(self, request, metadata):
135 logging.log(f"Received request: {request}")
136 return request, metadata
138 def post_update_topic(self, response):
139 logging.log(f"Received response: {response}")
140 return response
142 transport = PublisherRestTransport(interceptor=MyCustomPublisherInterceptor())
143 client = PublisherClient(transport=transport)
146 """
148 def pre_create_topic(
149 self, request: pubsub.Topic, metadata: Sequence[Tuple[str, str]]
150 ) -> Tuple[pubsub.Topic, Sequence[Tuple[str, str]]]:
151 """Pre-rpc interceptor for create_topic
153 Override in a subclass to manipulate the request or metadata
154 before they are sent to the Publisher server.
155 """
156 return request, metadata
158 def post_create_topic(self, response: pubsub.Topic) -> pubsub.Topic:
159 """Post-rpc interceptor for create_topic
161 Override in a subclass to manipulate the response
162 after it is returned by the Publisher server but before
163 it is returned to user code.
164 """
165 return response
167 def pre_delete_topic(
168 self, request: pubsub.DeleteTopicRequest, metadata: Sequence[Tuple[str, str]]
169 ) -> Tuple[pubsub.DeleteTopicRequest, Sequence[Tuple[str, str]]]:
170 """Pre-rpc interceptor for delete_topic
172 Override in a subclass to manipulate the request or metadata
173 before they are sent to the Publisher server.
174 """
175 return request, metadata
177 def pre_detach_subscription(
178 self,
179 request: pubsub.DetachSubscriptionRequest,
180 metadata: Sequence[Tuple[str, str]],
181 ) -> Tuple[pubsub.DetachSubscriptionRequest, Sequence[Tuple[str, str]]]:
182 """Pre-rpc interceptor for detach_subscription
184 Override in a subclass to manipulate the request or metadata
185 before they are sent to the Publisher server.
186 """
187 return request, metadata
189 def post_detach_subscription(
190 self, response: pubsub.DetachSubscriptionResponse
191 ) -> pubsub.DetachSubscriptionResponse:
192 """Post-rpc interceptor for detach_subscription
194 Override in a subclass to manipulate the response
195 after it is returned by the Publisher server but before
196 it is returned to user code.
197 """
198 return response
200 def pre_get_topic(
201 self, request: pubsub.GetTopicRequest, metadata: Sequence[Tuple[str, str]]
202 ) -> Tuple[pubsub.GetTopicRequest, Sequence[Tuple[str, str]]]:
203 """Pre-rpc interceptor for get_topic
205 Override in a subclass to manipulate the request or metadata
206 before they are sent to the Publisher server.
207 """
208 return request, metadata
210 def post_get_topic(self, response: pubsub.Topic) -> pubsub.Topic:
211 """Post-rpc interceptor for get_topic
213 Override in a subclass to manipulate the response
214 after it is returned by the Publisher server but before
215 it is returned to user code.
216 """
217 return response
219 def pre_list_topics(
220 self, request: pubsub.ListTopicsRequest, metadata: Sequence[Tuple[str, str]]
221 ) -> Tuple[pubsub.ListTopicsRequest, Sequence[Tuple[str, str]]]:
222 """Pre-rpc interceptor for list_topics
224 Override in a subclass to manipulate the request or metadata
225 before they are sent to the Publisher server.
226 """
227 return request, metadata
229 def post_list_topics(
230 self, response: pubsub.ListTopicsResponse
231 ) -> pubsub.ListTopicsResponse:
232 """Post-rpc interceptor for list_topics
234 Override in a subclass to manipulate the response
235 after it is returned by the Publisher server but before
236 it is returned to user code.
237 """
238 return response
240 def pre_list_topic_snapshots(
241 self,
242 request: pubsub.ListTopicSnapshotsRequest,
243 metadata: Sequence[Tuple[str, str]],
244 ) -> Tuple[pubsub.ListTopicSnapshotsRequest, Sequence[Tuple[str, str]]]:
245 """Pre-rpc interceptor for list_topic_snapshots
247 Override in a subclass to manipulate the request or metadata
248 before they are sent to the Publisher server.
249 """
250 return request, metadata
252 def post_list_topic_snapshots(
253 self, response: pubsub.ListTopicSnapshotsResponse
254 ) -> pubsub.ListTopicSnapshotsResponse:
255 """Post-rpc interceptor for list_topic_snapshots
257 Override in a subclass to manipulate the response
258 after it is returned by the Publisher server but before
259 it is returned to user code.
260 """
261 return response
263 def pre_list_topic_subscriptions(
264 self,
265 request: pubsub.ListTopicSubscriptionsRequest,
266 metadata: Sequence[Tuple[str, str]],
267 ) -> Tuple[pubsub.ListTopicSubscriptionsRequest, Sequence[Tuple[str, str]]]:
268 """Pre-rpc interceptor for list_topic_subscriptions
270 Override in a subclass to manipulate the request or metadata
271 before they are sent to the Publisher server.
272 """
273 return request, metadata
275 def post_list_topic_subscriptions(
276 self, response: pubsub.ListTopicSubscriptionsResponse
277 ) -> pubsub.ListTopicSubscriptionsResponse:
278 """Post-rpc interceptor for list_topic_subscriptions
280 Override in a subclass to manipulate the response
281 after it is returned by the Publisher server but before
282 it is returned to user code.
283 """
284 return response
286 def pre_publish(
287 self, request: pubsub.PublishRequest, metadata: Sequence[Tuple[str, str]]
288 ) -> Tuple[pubsub.PublishRequest, Sequence[Tuple[str, str]]]:
289 """Pre-rpc interceptor for publish
291 Override in a subclass to manipulate the request or metadata
292 before they are sent to the Publisher server.
293 """
294 return request, metadata
296 def post_publish(self, response: pubsub.PublishResponse) -> pubsub.PublishResponse:
297 """Post-rpc interceptor for publish
299 Override in a subclass to manipulate the response
300 after it is returned by the Publisher server but before
301 it is returned to user code.
302 """
303 return response
305 def pre_update_topic(
306 self, request: pubsub.UpdateTopicRequest, metadata: Sequence[Tuple[str, str]]
307 ) -> Tuple[pubsub.UpdateTopicRequest, Sequence[Tuple[str, str]]]:
308 """Pre-rpc interceptor for update_topic
310 Override in a subclass to manipulate the request or metadata
311 before they are sent to the Publisher server.
312 """
313 return request, metadata
315 def post_update_topic(self, response: pubsub.Topic) -> pubsub.Topic:
316 """Post-rpc interceptor for update_topic
318 Override in a subclass to manipulate the response
319 after it is returned by the Publisher server but before
320 it is returned to user code.
321 """
322 return response
324 def pre_get_iam_policy(
325 self,
326 request: iam_policy_pb2.GetIamPolicyRequest,
327 metadata: Sequence[Tuple[str, str]],
328 ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]:
329 """Pre-rpc interceptor for get_iam_policy
331 Override in a subclass to manipulate the request or metadata
332 before they are sent to the Publisher server.
333 """
334 return request, metadata
336 def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
337 """Post-rpc interceptor for get_iam_policy
339 Override in a subclass to manipulate the response
340 after it is returned by the Publisher server but before
341 it is returned to user code.
342 """
343 return response
345 def pre_set_iam_policy(
346 self,
347 request: iam_policy_pb2.SetIamPolicyRequest,
348 metadata: Sequence[Tuple[str, str]],
349 ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]:
350 """Pre-rpc interceptor for set_iam_policy
352 Override in a subclass to manipulate the request or metadata
353 before they are sent to the Publisher server.
354 """
355 return request, metadata
357 def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
358 """Post-rpc interceptor for set_iam_policy
360 Override in a subclass to manipulate the response
361 after it is returned by the Publisher server but before
362 it is returned to user code.
363 """
364 return response
366 def pre_test_iam_permissions(
367 self,
368 request: iam_policy_pb2.TestIamPermissionsRequest,
369 metadata: Sequence[Tuple[str, str]],
370 ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]:
371 """Pre-rpc interceptor for test_iam_permissions
373 Override in a subclass to manipulate the request or metadata
374 before they are sent to the Publisher server.
375 """
376 return request, metadata
378 def post_test_iam_permissions(
379 self, response: iam_policy_pb2.TestIamPermissionsResponse
380 ) -> iam_policy_pb2.TestIamPermissionsResponse:
381 """Post-rpc interceptor for test_iam_permissions
383 Override in a subclass to manipulate the response
384 after it is returned by the Publisher server but before
385 it is returned to user code.
386 """
387 return response
390@dataclasses.dataclass
391class PublisherRestStub:
392 _session: AuthorizedSession
393 _host: str
394 _interceptor: PublisherRestInterceptor
397class PublisherRestTransport(PublisherTransport):
398 """REST backend transport for Publisher.
400 The service that an application uses to manipulate topics,
401 and to send messages to a topic.
403 This class defines the same methods as the primary client, so the
404 primary client can load the underlying transport implementation
405 and call it.
407 It sends JSON representations of protocol buffers over HTTP/1.1
409 """
411 def __init__(
412 self,
413 *,
414 host: str = "pubsub.googleapis.com",
415 credentials: Optional[ga_credentials.Credentials] = None,
416 credentials_file: Optional[str] = None,
417 scopes: Optional[Sequence[str]] = None,
418 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
419 quota_project_id: Optional[str] = None,
420 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
421 always_use_jwt_access: Optional[bool] = False,
422 url_scheme: str = "https",
423 interceptor: Optional[PublisherRestInterceptor] = None,
424 api_audience: Optional[str] = None,
425 ) -> None:
426 """Instantiate the transport.
428 Args:
429 host (Optional[str]):
430 The hostname to connect to.
431 credentials (Optional[google.auth.credentials.Credentials]): The
432 authorization credentials to attach to requests. These
433 credentials identify the application to the service; if none
434 are specified, the client will attempt to ascertain the
435 credentials from the environment.
437 credentials_file (Optional[str]): A file with credentials that can
438 be loaded with :func:`google.auth.load_credentials_from_file`.
439 This argument is ignored if ``channel`` is provided.
440 scopes (Optional(Sequence[str])): A list of scopes. This argument is
441 ignored if ``channel`` is provided.
442 client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
443 certificate to configure mutual TLS HTTP channel. It is ignored
444 if ``channel`` is provided.
445 quota_project_id (Optional[str]): An optional project to use for billing
446 and quota.
447 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
448 The client info used to send a user-agent string along with
449 API requests. If ``None``, then default info will be used.
450 Generally, you only need to set this if you are developing
451 your own client library.
452 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
453 be used for service account credentials.
454 url_scheme: the protocol scheme for the API endpoint. Normally
455 "https", but for testing or local servers,
456 "http" can be specified.
457 """
458 # Run the base constructor
459 # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
460 # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
461 # credentials object
462 maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
463 if maybe_url_match is None:
464 raise ValueError(
465 f"Unexpected hostname structure: {host}"
466 ) # pragma: NO COVER
468 url_match_items = maybe_url_match.groupdict()
470 host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
472 super().__init__(
473 host=host,
474 credentials=credentials,
475 client_info=client_info,
476 always_use_jwt_access=always_use_jwt_access,
477 api_audience=api_audience,
478 )
479 self._session = AuthorizedSession(
480 self._credentials, default_host=self.DEFAULT_HOST
481 )
482 if client_cert_source_for_mtls:
483 self._session.configure_mtls_channel(client_cert_source_for_mtls)
484 self._interceptor = interceptor or PublisherRestInterceptor()
485 self._prep_wrapped_messages(client_info)
487 class _CreateTopic(PublisherRestStub):
488 def __hash__(self):
489 return hash("CreateTopic")
491 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
493 @classmethod
494 def _get_unset_required_fields(cls, message_dict):
495 return {
496 k: v
497 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
498 if k not in message_dict
499 }
501 def __call__(
502 self,
503 request: pubsub.Topic,
504 *,
505 retry: OptionalRetry = gapic_v1.method.DEFAULT,
506 timeout: Optional[float] = None,
507 metadata: Sequence[Tuple[str, str]] = (),
508 ) -> pubsub.Topic:
509 r"""Call the create topic method over HTTP.
511 Args:
512 request (~.pubsub.Topic):
513 The request object. A topic resource.
514 retry (google.api_core.retry.Retry): Designation of what errors, if any,
515 should be retried.
516 timeout (float): The timeout for this request.
517 metadata (Sequence[Tuple[str, str]]): Strings which should be
518 sent along with the request as metadata.
520 Returns:
521 ~.pubsub.Topic:
522 A topic resource.
523 """
525 http_options: List[Dict[str, str]] = [
526 {
527 "method": "put",
528 "uri": "/v1/{name=projects/*/topics/*}",
529 "body": "*",
530 },
531 ]
532 request, metadata = self._interceptor.pre_create_topic(request, metadata)
533 pb_request = pubsub.Topic.pb(request)
534 transcoded_request = path_template.transcode(http_options, pb_request)
536 # Jsonify the request body
538 body = json_format.MessageToJson(
539 transcoded_request["body"],
540 including_default_value_fields=False,
541 use_integers_for_enums=True,
542 )
543 uri = transcoded_request["uri"]
544 method = transcoded_request["method"]
546 # Jsonify the query params
547 query_params = json.loads(
548 json_format.MessageToJson(
549 transcoded_request["query_params"],
550 including_default_value_fields=False,
551 use_integers_for_enums=True,
552 )
553 )
554 query_params.update(self._get_unset_required_fields(query_params))
556 query_params["$alt"] = "json;enum-encoding=int"
558 # Send the request
559 headers = dict(metadata)
560 headers["Content-Type"] = "application/json"
561 response = getattr(self._session, method)(
562 "{host}{uri}".format(host=self._host, uri=uri),
563 timeout=timeout,
564 headers=headers,
565 params=rest_helpers.flatten_query_params(query_params, strict=True),
566 data=body,
567 )
569 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
570 # subclass.
571 if response.status_code >= 400:
572 raise core_exceptions.from_http_response(response)
574 # Return the response
575 resp = pubsub.Topic()
576 pb_resp = pubsub.Topic.pb(resp)
578 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
579 resp = self._interceptor.post_create_topic(resp)
580 return resp
582 class _DeleteTopic(PublisherRestStub):
583 def __hash__(self):
584 return hash("DeleteTopic")
586 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
588 @classmethod
589 def _get_unset_required_fields(cls, message_dict):
590 return {
591 k: v
592 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
593 if k not in message_dict
594 }
596 def __call__(
597 self,
598 request: pubsub.DeleteTopicRequest,
599 *,
600 retry: OptionalRetry = gapic_v1.method.DEFAULT,
601 timeout: Optional[float] = None,
602 metadata: Sequence[Tuple[str, str]] = (),
603 ):
604 r"""Call the delete topic method over HTTP.
606 Args:
607 request (~.pubsub.DeleteTopicRequest):
608 The request object. Request for the ``DeleteTopic`` method.
609 retry (google.api_core.retry.Retry): Designation of what errors, if any,
610 should be retried.
611 timeout (float): The timeout for this request.
612 metadata (Sequence[Tuple[str, str]]): Strings which should be
613 sent along with the request as metadata.
614 """
616 http_options: List[Dict[str, str]] = [
617 {
618 "method": "delete",
619 "uri": "/v1/{topic=projects/*/topics/*}",
620 },
621 ]
622 request, metadata = self._interceptor.pre_delete_topic(request, metadata)
623 pb_request = pubsub.DeleteTopicRequest.pb(request)
624 transcoded_request = path_template.transcode(http_options, pb_request)
626 uri = transcoded_request["uri"]
627 method = transcoded_request["method"]
629 # Jsonify the query params
630 query_params = json.loads(
631 json_format.MessageToJson(
632 transcoded_request["query_params"],
633 including_default_value_fields=False,
634 use_integers_for_enums=True,
635 )
636 )
637 query_params.update(self._get_unset_required_fields(query_params))
639 query_params["$alt"] = "json;enum-encoding=int"
641 # Send the request
642 headers = dict(metadata)
643 headers["Content-Type"] = "application/json"
644 response = getattr(self._session, method)(
645 "{host}{uri}".format(host=self._host, uri=uri),
646 timeout=timeout,
647 headers=headers,
648 params=rest_helpers.flatten_query_params(query_params, strict=True),
649 )
651 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
652 # subclass.
653 if response.status_code >= 400:
654 raise core_exceptions.from_http_response(response)
656 class _DetachSubscription(PublisherRestStub):
657 def __hash__(self):
658 return hash("DetachSubscription")
660 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
662 @classmethod
663 def _get_unset_required_fields(cls, message_dict):
664 return {
665 k: v
666 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
667 if k not in message_dict
668 }
670 def __call__(
671 self,
672 request: pubsub.DetachSubscriptionRequest,
673 *,
674 retry: OptionalRetry = gapic_v1.method.DEFAULT,
675 timeout: Optional[float] = None,
676 metadata: Sequence[Tuple[str, str]] = (),
677 ) -> pubsub.DetachSubscriptionResponse:
678 r"""Call the detach subscription method over HTTP.
680 Args:
681 request (~.pubsub.DetachSubscriptionRequest):
682 The request object. Request for the DetachSubscription
683 method.
684 retry (google.api_core.retry.Retry): Designation of what errors, if any,
685 should be retried.
686 timeout (float): The timeout for this request.
687 metadata (Sequence[Tuple[str, str]]): Strings which should be
688 sent along with the request as metadata.
690 Returns:
691 ~.pubsub.DetachSubscriptionResponse:
692 Response for the DetachSubscription
693 method. Reserved for future use.
695 """
697 http_options: List[Dict[str, str]] = [
698 {
699 "method": "post",
700 "uri": "/v1/{subscription=projects/*/subscriptions/*}:detach",
701 },
702 ]
703 request, metadata = self._interceptor.pre_detach_subscription(
704 request, metadata
705 )
706 pb_request = pubsub.DetachSubscriptionRequest.pb(request)
707 transcoded_request = path_template.transcode(http_options, pb_request)
709 uri = transcoded_request["uri"]
710 method = transcoded_request["method"]
712 # Jsonify the query params
713 query_params = json.loads(
714 json_format.MessageToJson(
715 transcoded_request["query_params"],
716 including_default_value_fields=False,
717 use_integers_for_enums=True,
718 )
719 )
720 query_params.update(self._get_unset_required_fields(query_params))
722 query_params["$alt"] = "json;enum-encoding=int"
724 # Send the request
725 headers = dict(metadata)
726 headers["Content-Type"] = "application/json"
727 response = getattr(self._session, method)(
728 "{host}{uri}".format(host=self._host, uri=uri),
729 timeout=timeout,
730 headers=headers,
731 params=rest_helpers.flatten_query_params(query_params, strict=True),
732 )
734 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
735 # subclass.
736 if response.status_code >= 400:
737 raise core_exceptions.from_http_response(response)
739 # Return the response
740 resp = pubsub.DetachSubscriptionResponse()
741 pb_resp = pubsub.DetachSubscriptionResponse.pb(resp)
743 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
744 resp = self._interceptor.post_detach_subscription(resp)
745 return resp
747 class _GetTopic(PublisherRestStub):
748 def __hash__(self):
749 return hash("GetTopic")
751 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
753 @classmethod
754 def _get_unset_required_fields(cls, message_dict):
755 return {
756 k: v
757 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
758 if k not in message_dict
759 }
761 def __call__(
762 self,
763 request: pubsub.GetTopicRequest,
764 *,
765 retry: OptionalRetry = gapic_v1.method.DEFAULT,
766 timeout: Optional[float] = None,
767 metadata: Sequence[Tuple[str, str]] = (),
768 ) -> pubsub.Topic:
769 r"""Call the get topic method over HTTP.
771 Args:
772 request (~.pubsub.GetTopicRequest):
773 The request object. Request for the GetTopic method.
774 retry (google.api_core.retry.Retry): Designation of what errors, if any,
775 should be retried.
776 timeout (float): The timeout for this request.
777 metadata (Sequence[Tuple[str, str]]): Strings which should be
778 sent along with the request as metadata.
780 Returns:
781 ~.pubsub.Topic:
782 A topic resource.
783 """
785 http_options: List[Dict[str, str]] = [
786 {
787 "method": "get",
788 "uri": "/v1/{topic=projects/*/topics/*}",
789 },
790 ]
791 request, metadata = self._interceptor.pre_get_topic(request, metadata)
792 pb_request = pubsub.GetTopicRequest.pb(request)
793 transcoded_request = path_template.transcode(http_options, pb_request)
795 uri = transcoded_request["uri"]
796 method = transcoded_request["method"]
798 # Jsonify the query params
799 query_params = json.loads(
800 json_format.MessageToJson(
801 transcoded_request["query_params"],
802 including_default_value_fields=False,
803 use_integers_for_enums=True,
804 )
805 )
806 query_params.update(self._get_unset_required_fields(query_params))
808 query_params["$alt"] = "json;enum-encoding=int"
810 # Send the request
811 headers = dict(metadata)
812 headers["Content-Type"] = "application/json"
813 response = getattr(self._session, method)(
814 "{host}{uri}".format(host=self._host, uri=uri),
815 timeout=timeout,
816 headers=headers,
817 params=rest_helpers.flatten_query_params(query_params, strict=True),
818 )
820 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
821 # subclass.
822 if response.status_code >= 400:
823 raise core_exceptions.from_http_response(response)
825 # Return the response
826 resp = pubsub.Topic()
827 pb_resp = pubsub.Topic.pb(resp)
829 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
830 resp = self._interceptor.post_get_topic(resp)
831 return resp
833 class _ListTopics(PublisherRestStub):
834 def __hash__(self):
835 return hash("ListTopics")
837 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
839 @classmethod
840 def _get_unset_required_fields(cls, message_dict):
841 return {
842 k: v
843 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
844 if k not in message_dict
845 }
847 def __call__(
848 self,
849 request: pubsub.ListTopicsRequest,
850 *,
851 retry: OptionalRetry = gapic_v1.method.DEFAULT,
852 timeout: Optional[float] = None,
853 metadata: Sequence[Tuple[str, str]] = (),
854 ) -> pubsub.ListTopicsResponse:
855 r"""Call the list topics method over HTTP.
857 Args:
858 request (~.pubsub.ListTopicsRequest):
859 The request object. Request for the ``ListTopics`` method.
860 retry (google.api_core.retry.Retry): Designation of what errors, if any,
861 should be retried.
862 timeout (float): The timeout for this request.
863 metadata (Sequence[Tuple[str, str]]): Strings which should be
864 sent along with the request as metadata.
866 Returns:
867 ~.pubsub.ListTopicsResponse:
868 Response for the ``ListTopics`` method.
869 """
871 http_options: List[Dict[str, str]] = [
872 {
873 "method": "get",
874 "uri": "/v1/{project=projects/*}/topics",
875 },
876 ]
877 request, metadata = self._interceptor.pre_list_topics(request, metadata)
878 pb_request = pubsub.ListTopicsRequest.pb(request)
879 transcoded_request = path_template.transcode(http_options, pb_request)
881 uri = transcoded_request["uri"]
882 method = transcoded_request["method"]
884 # Jsonify the query params
885 query_params = json.loads(
886 json_format.MessageToJson(
887 transcoded_request["query_params"],
888 including_default_value_fields=False,
889 use_integers_for_enums=True,
890 )
891 )
892 query_params.update(self._get_unset_required_fields(query_params))
894 query_params["$alt"] = "json;enum-encoding=int"
896 # Send the request
897 headers = dict(metadata)
898 headers["Content-Type"] = "application/json"
899 response = getattr(self._session, method)(
900 "{host}{uri}".format(host=self._host, uri=uri),
901 timeout=timeout,
902 headers=headers,
903 params=rest_helpers.flatten_query_params(query_params, strict=True),
904 )
906 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
907 # subclass.
908 if response.status_code >= 400:
909 raise core_exceptions.from_http_response(response)
911 # Return the response
912 resp = pubsub.ListTopicsResponse()
913 pb_resp = pubsub.ListTopicsResponse.pb(resp)
915 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
916 resp = self._interceptor.post_list_topics(resp)
917 return resp
919 class _ListTopicSnapshots(PublisherRestStub):
920 def __hash__(self):
921 return hash("ListTopicSnapshots")
923 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
925 @classmethod
926 def _get_unset_required_fields(cls, message_dict):
927 return {
928 k: v
929 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
930 if k not in message_dict
931 }
933 def __call__(
934 self,
935 request: pubsub.ListTopicSnapshotsRequest,
936 *,
937 retry: OptionalRetry = gapic_v1.method.DEFAULT,
938 timeout: Optional[float] = None,
939 metadata: Sequence[Tuple[str, str]] = (),
940 ) -> pubsub.ListTopicSnapshotsResponse:
941 r"""Call the list topic snapshots method over HTTP.
943 Args:
944 request (~.pubsub.ListTopicSnapshotsRequest):
945 The request object. Request for the ``ListTopicSnapshots`` method.
946 retry (google.api_core.retry.Retry): Designation of what errors, if any,
947 should be retried.
948 timeout (float): The timeout for this request.
949 metadata (Sequence[Tuple[str, str]]): Strings which should be
950 sent along with the request as metadata.
952 Returns:
953 ~.pubsub.ListTopicSnapshotsResponse:
954 Response for the ``ListTopicSnapshots`` method.
955 """
957 http_options: List[Dict[str, str]] = [
958 {
959 "method": "get",
960 "uri": "/v1/{topic=projects/*/topics/*}/snapshots",
961 },
962 ]
963 request, metadata = self._interceptor.pre_list_topic_snapshots(
964 request, metadata
965 )
966 pb_request = pubsub.ListTopicSnapshotsRequest.pb(request)
967 transcoded_request = path_template.transcode(http_options, pb_request)
969 uri = transcoded_request["uri"]
970 method = transcoded_request["method"]
972 # Jsonify the query params
973 query_params = json.loads(
974 json_format.MessageToJson(
975 transcoded_request["query_params"],
976 including_default_value_fields=False,
977 use_integers_for_enums=True,
978 )
979 )
980 query_params.update(self._get_unset_required_fields(query_params))
982 query_params["$alt"] = "json;enum-encoding=int"
984 # Send the request
985 headers = dict(metadata)
986 headers["Content-Type"] = "application/json"
987 response = getattr(self._session, method)(
988 "{host}{uri}".format(host=self._host, uri=uri),
989 timeout=timeout,
990 headers=headers,
991 params=rest_helpers.flatten_query_params(query_params, strict=True),
992 )
994 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
995 # subclass.
996 if response.status_code >= 400:
997 raise core_exceptions.from_http_response(response)
999 # Return the response
1000 resp = pubsub.ListTopicSnapshotsResponse()
1001 pb_resp = pubsub.ListTopicSnapshotsResponse.pb(resp)
1003 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1004 resp = self._interceptor.post_list_topic_snapshots(resp)
1005 return resp
1007 class _ListTopicSubscriptions(PublisherRestStub):
1008 def __hash__(self):
1009 return hash("ListTopicSubscriptions")
1011 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1013 @classmethod
1014 def _get_unset_required_fields(cls, message_dict):
1015 return {
1016 k: v
1017 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1018 if k not in message_dict
1019 }
1021 def __call__(
1022 self,
1023 request: pubsub.ListTopicSubscriptionsRequest,
1024 *,
1025 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1026 timeout: Optional[float] = None,
1027 metadata: Sequence[Tuple[str, str]] = (),
1028 ) -> pubsub.ListTopicSubscriptionsResponse:
1029 r"""Call the list topic subscriptions method over HTTP.
1031 Args:
1032 request (~.pubsub.ListTopicSubscriptionsRequest):
1033 The request object. Request for the ``ListTopicSubscriptions`` method.
1034 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1035 should be retried.
1036 timeout (float): The timeout for this request.
1037 metadata (Sequence[Tuple[str, str]]): Strings which should be
1038 sent along with the request as metadata.
1040 Returns:
1041 ~.pubsub.ListTopicSubscriptionsResponse:
1042 Response for the ``ListTopicSubscriptions`` method.
1043 """
1045 http_options: List[Dict[str, str]] = [
1046 {
1047 "method": "get",
1048 "uri": "/v1/{topic=projects/*/topics/*}/subscriptions",
1049 },
1050 ]
1051 request, metadata = self._interceptor.pre_list_topic_subscriptions(
1052 request, metadata
1053 )
1054 pb_request = pubsub.ListTopicSubscriptionsRequest.pb(request)
1055 transcoded_request = path_template.transcode(http_options, pb_request)
1057 uri = transcoded_request["uri"]
1058 method = transcoded_request["method"]
1060 # Jsonify the query params
1061 query_params = json.loads(
1062 json_format.MessageToJson(
1063 transcoded_request["query_params"],
1064 including_default_value_fields=False,
1065 use_integers_for_enums=True,
1066 )
1067 )
1068 query_params.update(self._get_unset_required_fields(query_params))
1070 query_params["$alt"] = "json;enum-encoding=int"
1072 # Send the request
1073 headers = dict(metadata)
1074 headers["Content-Type"] = "application/json"
1075 response = getattr(self._session, method)(
1076 "{host}{uri}".format(host=self._host, uri=uri),
1077 timeout=timeout,
1078 headers=headers,
1079 params=rest_helpers.flatten_query_params(query_params, strict=True),
1080 )
1082 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1083 # subclass.
1084 if response.status_code >= 400:
1085 raise core_exceptions.from_http_response(response)
1087 # Return the response
1088 resp = pubsub.ListTopicSubscriptionsResponse()
1089 pb_resp = pubsub.ListTopicSubscriptionsResponse.pb(resp)
1091 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1092 resp = self._interceptor.post_list_topic_subscriptions(resp)
1093 return resp
1095 class _Publish(PublisherRestStub):
1096 def __hash__(self):
1097 return hash("Publish")
1099 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1101 @classmethod
1102 def _get_unset_required_fields(cls, message_dict):
1103 return {
1104 k: v
1105 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1106 if k not in message_dict
1107 }
1109 def __call__(
1110 self,
1111 request: pubsub.PublishRequest,
1112 *,
1113 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1114 timeout: Optional[float] = None,
1115 metadata: Sequence[Tuple[str, str]] = (),
1116 ) -> pubsub.PublishResponse:
1117 r"""Call the publish method over HTTP.
1119 Args:
1120 request (~.pubsub.PublishRequest):
1121 The request object. Request for the Publish method.
1122 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1123 should be retried.
1124 timeout (float): The timeout for this request.
1125 metadata (Sequence[Tuple[str, str]]): Strings which should be
1126 sent along with the request as metadata.
1128 Returns:
1129 ~.pubsub.PublishResponse:
1130 Response for the ``Publish`` method.
1131 """
1133 http_options: List[Dict[str, str]] = [
1134 {
1135 "method": "post",
1136 "uri": "/v1/{topic=projects/*/topics/*}:publish",
1137 "body": "*",
1138 },
1139 ]
1140 request, metadata = self._interceptor.pre_publish(request, metadata)
1141 pb_request = pubsub.PublishRequest.pb(request)
1142 transcoded_request = path_template.transcode(http_options, pb_request)
1144 # Jsonify the request body
1146 body = json_format.MessageToJson(
1147 transcoded_request["body"],
1148 including_default_value_fields=False,
1149 use_integers_for_enums=True,
1150 )
1151 uri = transcoded_request["uri"]
1152 method = transcoded_request["method"]
1154 # Jsonify the query params
1155 query_params = json.loads(
1156 json_format.MessageToJson(
1157 transcoded_request["query_params"],
1158 including_default_value_fields=False,
1159 use_integers_for_enums=True,
1160 )
1161 )
1162 query_params.update(self._get_unset_required_fields(query_params))
1164 query_params["$alt"] = "json;enum-encoding=int"
1166 # Send the request
1167 headers = dict(metadata)
1168 headers["Content-Type"] = "application/json"
1169 response = getattr(self._session, method)(
1170 "{host}{uri}".format(host=self._host, uri=uri),
1171 timeout=timeout,
1172 headers=headers,
1173 params=rest_helpers.flatten_query_params(query_params, strict=True),
1174 data=body,
1175 )
1177 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1178 # subclass.
1179 if response.status_code >= 400:
1180 raise core_exceptions.from_http_response(response)
1182 # Return the response
1183 resp = pubsub.PublishResponse()
1184 pb_resp = pubsub.PublishResponse.pb(resp)
1186 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1187 resp = self._interceptor.post_publish(resp)
1188 return resp
1190 class _UpdateTopic(PublisherRestStub):
1191 def __hash__(self):
1192 return hash("UpdateTopic")
1194 __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
1196 @classmethod
1197 def _get_unset_required_fields(cls, message_dict):
1198 return {
1199 k: v
1200 for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
1201 if k not in message_dict
1202 }
1204 def __call__(
1205 self,
1206 request: pubsub.UpdateTopicRequest,
1207 *,
1208 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1209 timeout: Optional[float] = None,
1210 metadata: Sequence[Tuple[str, str]] = (),
1211 ) -> pubsub.Topic:
1212 r"""Call the update topic method over HTTP.
1214 Args:
1215 request (~.pubsub.UpdateTopicRequest):
1216 The request object. Request for the UpdateTopic method.
1217 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1218 should be retried.
1219 timeout (float): The timeout for this request.
1220 metadata (Sequence[Tuple[str, str]]): Strings which should be
1221 sent along with the request as metadata.
1223 Returns:
1224 ~.pubsub.Topic:
1225 A topic resource.
1226 """
1228 http_options: List[Dict[str, str]] = [
1229 {
1230 "method": "patch",
1231 "uri": "/v1/{topic.name=projects/*/topics/*}",
1232 "body": "*",
1233 },
1234 ]
1235 request, metadata = self._interceptor.pre_update_topic(request, metadata)
1236 pb_request = pubsub.UpdateTopicRequest.pb(request)
1237 transcoded_request = path_template.transcode(http_options, pb_request)
1239 # Jsonify the request body
1241 body = json_format.MessageToJson(
1242 transcoded_request["body"],
1243 including_default_value_fields=False,
1244 use_integers_for_enums=True,
1245 )
1246 uri = transcoded_request["uri"]
1247 method = transcoded_request["method"]
1249 # Jsonify the query params
1250 query_params = json.loads(
1251 json_format.MessageToJson(
1252 transcoded_request["query_params"],
1253 including_default_value_fields=False,
1254 use_integers_for_enums=True,
1255 )
1256 )
1257 query_params.update(self._get_unset_required_fields(query_params))
1259 query_params["$alt"] = "json;enum-encoding=int"
1261 # Send the request
1262 headers = dict(metadata)
1263 headers["Content-Type"] = "application/json"
1264 response = getattr(self._session, method)(
1265 "{host}{uri}".format(host=self._host, uri=uri),
1266 timeout=timeout,
1267 headers=headers,
1268 params=rest_helpers.flatten_query_params(query_params, strict=True),
1269 data=body,
1270 )
1272 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1273 # subclass.
1274 if response.status_code >= 400:
1275 raise core_exceptions.from_http_response(response)
1277 # Return the response
1278 resp = pubsub.Topic()
1279 pb_resp = pubsub.Topic.pb(resp)
1281 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1282 resp = self._interceptor.post_update_topic(resp)
1283 return resp
1285 @property
1286 def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]:
1287 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1288 # In C++ this would require a dynamic_cast
1289 return self._CreateTopic(self._session, self._host, self._interceptor) # type: ignore
1291 @property
1292 def delete_topic(self) -> Callable[[pubsub.DeleteTopicRequest], empty_pb2.Empty]:
1293 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1294 # In C++ this would require a dynamic_cast
1295 return self._DeleteTopic(self._session, self._host, self._interceptor) # type: ignore
1297 @property
1298 def detach_subscription(
1299 self,
1300 ) -> Callable[
1301 [pubsub.DetachSubscriptionRequest], pubsub.DetachSubscriptionResponse
1302 ]:
1303 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1304 # In C++ this would require a dynamic_cast
1305 return self._DetachSubscription(self._session, self._host, self._interceptor) # type: ignore
1307 @property
1308 def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]:
1309 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1310 # In C++ this would require a dynamic_cast
1311 return self._GetTopic(self._session, self._host, self._interceptor) # type: ignore
1313 @property
1314 def list_topics(
1315 self,
1316 ) -> Callable[[pubsub.ListTopicsRequest], pubsub.ListTopicsResponse]:
1317 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1318 # In C++ this would require a dynamic_cast
1319 return self._ListTopics(self._session, self._host, self._interceptor) # type: ignore
1321 @property
1322 def list_topic_snapshots(
1323 self,
1324 ) -> Callable[
1325 [pubsub.ListTopicSnapshotsRequest], pubsub.ListTopicSnapshotsResponse
1326 ]:
1327 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1328 # In C++ this would require a dynamic_cast
1329 return self._ListTopicSnapshots(self._session, self._host, self._interceptor) # type: ignore
1331 @property
1332 def list_topic_subscriptions(
1333 self,
1334 ) -> Callable[
1335 [pubsub.ListTopicSubscriptionsRequest], pubsub.ListTopicSubscriptionsResponse
1336 ]:
1337 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1338 # In C++ this would require a dynamic_cast
1339 return self._ListTopicSubscriptions(self._session, self._host, self._interceptor) # type: ignore
1341 @property
1342 def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]:
1343 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1344 # In C++ this would require a dynamic_cast
1345 return self._Publish(self._session, self._host, self._interceptor) # type: ignore
1347 @property
1348 def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]:
1349 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1350 # In C++ this would require a dynamic_cast
1351 return self._UpdateTopic(self._session, self._host, self._interceptor) # type: ignore
1353 @property
1354 def get_iam_policy(self):
1355 return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
1357 class _GetIamPolicy(PublisherRestStub):
1358 def __call__(
1359 self,
1360 request: iam_policy_pb2.GetIamPolicyRequest,
1361 *,
1362 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1363 timeout: Optional[float] = None,
1364 metadata: Sequence[Tuple[str, str]] = (),
1365 ) -> policy_pb2.Policy:
1367 r"""Call the get iam policy method over HTTP.
1369 Args:
1370 request (iam_policy_pb2.GetIamPolicyRequest):
1371 The request object for GetIamPolicy method.
1372 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1373 should be retried.
1374 timeout (float): The timeout for this request.
1375 metadata (Sequence[Tuple[str, str]]): Strings which should be
1376 sent along with the request as metadata.
1378 Returns:
1379 policy_pb2.Policy: Response from GetIamPolicy method.
1380 """
1382 http_options: List[Dict[str, str]] = [
1383 {
1384 "method": "get",
1385 "uri": "/v1/{resource=projects/*/topics/*}:getIamPolicy",
1386 },
1387 {
1388 "method": "get",
1389 "uri": "/v1/{resource=projects/*/subscriptions/*}:getIamPolicy",
1390 },
1391 {
1392 "method": "get",
1393 "uri": "/v1/{resource=projects/*/snapshots/*}:getIamPolicy",
1394 },
1395 {
1396 "method": "get",
1397 "uri": "/v1/{resource=projects/*/schemas/*}:getIamPolicy",
1398 },
1399 ]
1401 request, metadata = self._interceptor.pre_get_iam_policy(request, metadata)
1402 request_kwargs = json_format.MessageToDict(request)
1403 transcoded_request = path_template.transcode(http_options, **request_kwargs)
1405 uri = transcoded_request["uri"]
1406 method = transcoded_request["method"]
1408 # Jsonify the query params
1409 query_params = json.loads(json.dumps(transcoded_request["query_params"]))
1411 # Send the request
1412 headers = dict(metadata)
1413 headers["Content-Type"] = "application/json"
1415 response = getattr(self._session, method)(
1416 "{host}{uri}".format(host=self._host, uri=uri),
1417 timeout=timeout,
1418 headers=headers,
1419 params=rest_helpers.flatten_query_params(query_params),
1420 )
1422 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1423 # subclass.
1424 if response.status_code >= 400:
1425 raise core_exceptions.from_http_response(response)
1427 resp = policy_pb2.Policy()
1428 resp = json_format.Parse(response.content.decode("utf-8"), resp)
1429 resp = self._interceptor.post_get_iam_policy(resp)
1430 return resp
1432 @property
1433 def set_iam_policy(self):
1434 return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
1436 class _SetIamPolicy(PublisherRestStub):
1437 def __call__(
1438 self,
1439 request: iam_policy_pb2.SetIamPolicyRequest,
1440 *,
1441 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1442 timeout: Optional[float] = None,
1443 metadata: Sequence[Tuple[str, str]] = (),
1444 ) -> policy_pb2.Policy:
1446 r"""Call the set iam policy method over HTTP.
1448 Args:
1449 request (iam_policy_pb2.SetIamPolicyRequest):
1450 The request object for SetIamPolicy method.
1451 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1452 should be retried.
1453 timeout (float): The timeout for this request.
1454 metadata (Sequence[Tuple[str, str]]): Strings which should be
1455 sent along with the request as metadata.
1457 Returns:
1458 policy_pb2.Policy: Response from SetIamPolicy method.
1459 """
1461 http_options: List[Dict[str, str]] = [
1462 {
1463 "method": "post",
1464 "uri": "/v1/{resource=projects/*/topics/*}:setIamPolicy",
1465 "body": "*",
1466 },
1467 {
1468 "method": "post",
1469 "uri": "/v1/{resource=projects/*/subscriptions/*}:setIamPolicy",
1470 "body": "*",
1471 },
1472 {
1473 "method": "post",
1474 "uri": "/v1/{resource=projects/*/snapshots/*}:setIamPolicy",
1475 "body": "*",
1476 },
1477 {
1478 "method": "post",
1479 "uri": "/v1/{resource=projects/*/schemas/*}:setIamPolicy",
1480 "body": "*",
1481 },
1482 ]
1484 request, metadata = self._interceptor.pre_set_iam_policy(request, metadata)
1485 request_kwargs = json_format.MessageToDict(request)
1486 transcoded_request = path_template.transcode(http_options, **request_kwargs)
1488 body = json.loads(json.dumps(transcoded_request["body"]))
1489 uri = transcoded_request["uri"]
1490 method = transcoded_request["method"]
1492 # Jsonify the query params
1493 query_params = json.loads(json.dumps(transcoded_request["query_params"]))
1495 # Send the request
1496 headers = dict(metadata)
1497 headers["Content-Type"] = "application/json"
1499 response = getattr(self._session, method)(
1500 "{host}{uri}".format(host=self._host, uri=uri),
1501 timeout=timeout,
1502 headers=headers,
1503 params=rest_helpers.flatten_query_params(query_params),
1504 data=body,
1505 )
1507 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1508 # subclass.
1509 if response.status_code >= 400:
1510 raise core_exceptions.from_http_response(response)
1512 resp = policy_pb2.Policy()
1513 resp = json_format.Parse(response.content.decode("utf-8"), resp)
1514 resp = self._interceptor.post_set_iam_policy(resp)
1515 return resp
1517 @property
1518 def test_iam_permissions(self):
1519 return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore
1521 class _TestIamPermissions(PublisherRestStub):
1522 def __call__(
1523 self,
1524 request: iam_policy_pb2.TestIamPermissionsRequest,
1525 *,
1526 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1527 timeout: Optional[float] = None,
1528 metadata: Sequence[Tuple[str, str]] = (),
1529 ) -> iam_policy_pb2.TestIamPermissionsResponse:
1531 r"""Call the test iam permissions method over HTTP.
1533 Args:
1534 request (iam_policy_pb2.TestIamPermissionsRequest):
1535 The request object for TestIamPermissions method.
1536 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1537 should be retried.
1538 timeout (float): The timeout for this request.
1539 metadata (Sequence[Tuple[str, str]]): Strings which should be
1540 sent along with the request as metadata.
1542 Returns:
1543 iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method.
1544 """
1546 http_options: List[Dict[str, str]] = [
1547 {
1548 "method": "post",
1549 "uri": "/v1/{resource=projects/*/subscriptions/*}:testIamPermissions",
1550 "body": "*",
1551 },
1552 {
1553 "method": "post",
1554 "uri": "/v1/{resource=projects/*/topics/*}:testIamPermissions",
1555 "body": "*",
1556 },
1557 {
1558 "method": "post",
1559 "uri": "/v1/{resource=projects/*/snapshots/*}:testIamPermissions",
1560 "body": "*",
1561 },
1562 {
1563 "method": "post",
1564 "uri": "/v1/{resource=projects/*/schemas/*}:testIamPermissions",
1565 "body": "*",
1566 },
1567 ]
1569 request, metadata = self._interceptor.pre_test_iam_permissions(
1570 request, metadata
1571 )
1572 request_kwargs = json_format.MessageToDict(request)
1573 transcoded_request = path_template.transcode(http_options, **request_kwargs)
1575 body = json.loads(json.dumps(transcoded_request["body"]))
1576 uri = transcoded_request["uri"]
1577 method = transcoded_request["method"]
1579 # Jsonify the query params
1580 query_params = json.loads(json.dumps(transcoded_request["query_params"]))
1582 # Send the request
1583 headers = dict(metadata)
1584 headers["Content-Type"] = "application/json"
1586 response = getattr(self._session, method)(
1587 "{host}{uri}".format(host=self._host, uri=uri),
1588 timeout=timeout,
1589 headers=headers,
1590 params=rest_helpers.flatten_query_params(query_params),
1591 data=body,
1592 )
1594 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1595 # subclass.
1596 if response.status_code >= 400:
1597 raise core_exceptions.from_http_response(response)
1599 resp = iam_policy_pb2.TestIamPermissionsResponse()
1600 resp = json_format.Parse(response.content.decode("utf-8"), resp)
1601 resp = self._interceptor.post_test_iam_permissions(resp)
1602 return resp
1604 @property
1605 def kind(self) -> str:
1606 return "rest"
1608 def close(self):
1609 self._session.close()
1612__all__ = ("PublisherRestTransport",)