Exemple #1
0
def process_firebase_messages(lqueue, stop_event):
    firebaseSession = AuthorizedSession(credentials)
    baseUrl = FIREBASE_BASE_URL.format(args.firebaseAppName)
    print("hi, this is before debug -----0")
    while not stop_event.is_set():
        try:
            packet = lqueue.get(False)
            print("hi, this is try debug -----1")
        except Empty:
            print("hi, this is except debug -----1")
            time.sleep(NOTHING_TO_DO_DELAY)
            pass
        else:
            if packet is None:
                print("hi, this is none packet debug -----1")
                continue
            print("hi, this is debug -----0.01")
            print("data from queue: " + format(packet))  #debug
            firebasePath = packet['config']['firebasePath']
            if packet['config']['topicAsChild']:
                firebasePath = urllib.parse.urljoin(
                    packet['config']['firebasePath'] + '/', packet['topic'])
            firebasePath = baseUrl + '/' + firebasePath + '.json'
            print("Sending {0} to this URL {1}".format(packet['payload'],
                                                       firebasePath))  #debug
            retry = 0
            print("hi, this is debug -----1")
            while True:
                print("hi, this is debug -----2")
                try:
                    if not args.dryRun:  # https://obd-driving-data-default-rtdb.firebaseio.com/readings.json
                        r = firebaseSession.post(firebasePath,
                                                 json=packet['payload'],
                                                 timeout=FIREBASE_TIMEOUT
                                                 )  #replace with firebase path
                        print("payload inserted : " + r.text)  #debug
                #except firebase_admin.exceptions.
                except requests.exceptions.Timeout:
                    print("Firebase Timeout")
                    if retry < FIREBASE_MAX_RETRY:
                        retry += 1
                        debug("Retrying")
                        time.sleep(NOTHING_TO_DO_DELAY)
                        continue
                except requests.exceptions.RequestException as e:
                    print("Firebase Exception" + str(e))
                except Exception as e:
                    print(e)
                    print("Firebase Unknown Exception")
                break
            queue.task_done()
    firebaseSession.close()
    print("Stopping Firebase Thread ...")
def process_firebase_messages(lqueue, stop_event):
  firebaseSession = AuthorizedSession(credentials)
  baseUrl = FIREBASE_BASE_URL.format(args.firebaseAppName)

  while not stop_event.is_set():
    try:
      packet = lqueue.get(False)
    except Empty:
      time.sleep(NOTHING_TO_DO_DELAY)
      pass
    else:
      if packet is None:
        continue
      debug("data from queue: " + format(packet))
      firebasePath = packet['config']['firebasePath']
      if packet['config']['topicAsChild']:
        firebasePath = urllib.parse.urljoin(packet['config']['firebasePath'] + '/', packet['topic'])
      firebasePath = baseUrl + '/' + firebasePath + '.json'
      debug ("Sending {0} to this URL {1}".format(packet['payload'], firebasePath))
      retry = 0
      while True:
        try:
          if not args.dryRun:
            r = firebaseSession.post(firebasePath, json=packet['payload'], timeout=FIREBASE_TIMEOUT)
            debug ("payload inserted : " + r.text)
        except requests.exceptions.Timeout:
          print ("Firebase Timeout")
          if retry < FIREBASE_MAX_RETRY:
            retry += 1
            debug ("Retrying")
            time.sleep(NOTHING_TO_DO_DELAY)
            continue
        except requests.exceptions.RequestException as e:
          print ("Firebase Exception" + str(e))
        except:
          print ("Firebase Unknown Exception")
        break
      queue.task_done()
  firebaseSession.close()
  debug("Stopping Firebase Thread ...")
Exemple #3
0
class ExternalVpnGatewaysRestTransport(ExternalVpnGatewaysTransport):
    """REST backend transport for ExternalVpnGateways.

    The ExternalVpnGateways API.

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends JSON representations of protocol buffers over HTTP/1.1
    """

    _STUBS: Dict[str, ExternalVpnGatewaysRestStub] = {}

    def __init__(
        self,
        *,
        host: str = "compute.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: str = None,
        scopes: Sequence[str] = None,
        client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        url_scheme: str = "https",
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.

            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional(Sequence[str])): A list of scopes. This argument is
                ignored if ``channel`` is provided.
            client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
                certificate to configure mutual TLS HTTP channel. It is ignored
                if ``channel`` is provided.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you are developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.
            url_scheme: the protocol scheme for the API endpoint.  Normally
                "https", but for testing or local servers,
                "http" can be specified.
        """
        # Run the base constructor
        # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
        # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
        # credentials object
        super().__init__(
            host=host,
            credentials=credentials,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
        )
        self._session = AuthorizedSession(
            self._credentials, default_host=self.DEFAULT_HOST
        )
        if client_cert_source_for_mtls:
            self._session.configure_mtls_channel(client_cert_source_for_mtls)
        self._prep_wrapped_messages(client_info)

    class _Delete(ExternalVpnGatewaysRestStub):
        def __hash__(self):
            return hash("Delete")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.DeleteExternalVpnGatewayRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the delete method over HTTP.

            Args:
                request (~.compute.DeleteExternalVpnGatewayRequest):
                    The request object. A request message for
                ExternalVpnGateways.Delete. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options = [
                {
                    "method": "delete",
                    "uri": "/compute/v1/projects/{project}/global/externalVpnGateways/{external_vpn_gateway}",
                },
            ]

            request_kwargs = compute.DeleteExternalVpnGatewayRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.DeleteExternalVpnGatewayRequest.to_json(
                    compute.DeleteExternalVpnGatewayRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Operation.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _Get(ExternalVpnGatewaysRestStub):
        def __hash__(self):
            return hash("Get")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.GetExternalVpnGatewayRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.ExternalVpnGateway:
            r"""Call the get method over HTTP.

            Args:
                request (~.compute.GetExternalVpnGatewayRequest):
                    The request object. A request message for
                ExternalVpnGateways.Get. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.ExternalVpnGateway:
                    Represents an external VPN gateway.
                External VPN gateway is the on-premises
                VPN gateway(s) or another cloud
                provider's VPN gateway that connects to
                your Google Cloud VPN gateway. To create
                a highly available VPN from Google Cloud
                Platform to your VPN gateway or another
                cloud provider's VPN gateway, you must
                create a external VPN gateway resource
                with information about the other
                gateway. For more information about
                using external VPN gateways, see
                Creating an HA VPN gateway and tunnel
                pair to a peer VPN.

            """

            http_options = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/global/externalVpnGateways/{external_vpn_gateway}",
                },
            ]

            request_kwargs = compute.GetExternalVpnGatewayRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.GetExternalVpnGatewayRequest.to_json(
                    compute.GetExternalVpnGatewayRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.ExternalVpnGateway.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _Insert(ExternalVpnGatewaysRestStub):
        def __hash__(self):
            return hash("Insert")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.InsertExternalVpnGatewayRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the insert method over HTTP.

            Args:
                request (~.compute.InsertExternalVpnGatewayRequest):
                    The request object. A request message for
                ExternalVpnGateways.Insert. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options = [
                {
                    "method": "post",
                    "uri": "/compute/v1/projects/{project}/global/externalVpnGateways",
                    "body": "external_vpn_gateway_resource",
                },
            ]

            request_kwargs = compute.InsertExternalVpnGatewayRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            # Jsonify the request body
            body = compute.ExternalVpnGateway.to_json(
                compute.ExternalVpnGateway(transcoded_request["body"]),
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.InsertExternalVpnGatewayRequest.to_json(
                    compute.InsertExternalVpnGatewayRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Operation.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _List(ExternalVpnGatewaysRestStub):
        def __hash__(self):
            return hash("List")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.ListExternalVpnGatewaysRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.ExternalVpnGatewayList:
            r"""Call the list method over HTTP.

            Args:
                request (~.compute.ListExternalVpnGatewaysRequest):
                    The request object. A request message for
                ExternalVpnGateways.List. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.ExternalVpnGatewayList:
                    Response to the list request, and
                contains a list of externalVpnGateways.

            """

            http_options = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/global/externalVpnGateways",
                },
            ]

            request_kwargs = compute.ListExternalVpnGatewaysRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.ListExternalVpnGatewaysRequest.to_json(
                    compute.ListExternalVpnGatewaysRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.ExternalVpnGatewayList.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _SetLabels(ExternalVpnGatewaysRestStub):
        def __hash__(self):
            return hash("SetLabels")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.SetLabelsExternalVpnGatewayRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the set labels method over HTTP.

            Args:
                request (~.compute.SetLabelsExternalVpnGatewayRequest):
                    The request object. A request message for
                ExternalVpnGateways.SetLabels. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options = [
                {
                    "method": "post",
                    "uri": "/compute/v1/projects/{project}/global/externalVpnGateways/{resource}/setLabels",
                    "body": "global_set_labels_request_resource",
                },
            ]

            request_kwargs = compute.SetLabelsExternalVpnGatewayRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            # Jsonify the request body
            body = compute.GlobalSetLabelsRequest.to_json(
                compute.GlobalSetLabelsRequest(transcoded_request["body"]),
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.SetLabelsExternalVpnGatewayRequest.to_json(
                    compute.SetLabelsExternalVpnGatewayRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Operation.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _TestIamPermissions(ExternalVpnGatewaysRestStub):
        def __hash__(self):
            return hash("TestIamPermissions")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.TestIamPermissionsExternalVpnGatewayRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.TestPermissionsResponse:
            r"""Call the test iam permissions method over HTTP.

            Args:
                request (~.compute.TestIamPermissionsExternalVpnGatewayRequest):
                    The request object. A request message for
                ExternalVpnGateways.TestIamPermissions.
                See the method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.TestPermissionsResponse:

            """

            http_options = [
                {
                    "method": "post",
                    "uri": "/compute/v1/projects/{project}/global/externalVpnGateways/{resource}/testIamPermissions",
                    "body": "test_permissions_request_resource",
                },
            ]

            request_kwargs = compute.TestIamPermissionsExternalVpnGatewayRequest.to_dict(
                request
            )
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            # Jsonify the request body
            body = compute.TestPermissionsRequest.to_json(
                compute.TestPermissionsRequest(transcoded_request["body"]),
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.TestIamPermissionsExternalVpnGatewayRequest.to_json(
                    compute.TestIamPermissionsExternalVpnGatewayRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.TestPermissionsResponse.from_json(
                response.content, ignore_unknown_fields=True
            )

    @property
    def delete(
        self,
    ) -> Callable[[compute.DeleteExternalVpnGatewayRequest], compute.Operation]:
        stub = self._STUBS.get("delete")
        if not stub:
            stub = self._STUBS["delete"] = self._Delete(self._session, self._host)

        return stub

    @property
    def get(
        self,
    ) -> Callable[[compute.GetExternalVpnGatewayRequest], compute.ExternalVpnGateway]:
        stub = self._STUBS.get("get")
        if not stub:
            stub = self._STUBS["get"] = self._Get(self._session, self._host)

        return stub

    @property
    def insert(
        self,
    ) -> Callable[[compute.InsertExternalVpnGatewayRequest], compute.Operation]:
        stub = self._STUBS.get("insert")
        if not stub:
            stub = self._STUBS["insert"] = self._Insert(self._session, self._host)

        return stub

    @property
    def list(
        self,
    ) -> Callable[
        [compute.ListExternalVpnGatewaysRequest], compute.ExternalVpnGatewayList
    ]:
        stub = self._STUBS.get("list")
        if not stub:
            stub = self._STUBS["list"] = self._List(self._session, self._host)

        return stub

    @property
    def set_labels(
        self,
    ) -> Callable[[compute.SetLabelsExternalVpnGatewayRequest], compute.Operation]:
        stub = self._STUBS.get("set_labels")
        if not stub:
            stub = self._STUBS["set_labels"] = self._SetLabels(
                self._session, self._host
            )

        return stub

    @property
    def test_iam_permissions(
        self,
    ) -> Callable[
        [compute.TestIamPermissionsExternalVpnGatewayRequest],
        compute.TestPermissionsResponse,
    ]:
        stub = self._STUBS.get("test_iam_permissions")
        if not stub:
            stub = self._STUBS["test_iam_permissions"] = self._TestIamPermissions(
                self._session, self._host
            )

        return stub

    def close(self):
        self._session.close()
Exemple #4
0
class ZonesRestTransport(ZonesTransport):
    """REST backend transport for Zones.

    The Zones API.

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends JSON representations of protocol buffers over HTTP/1.1
    """

    _STUBS: Dict[str, ZonesRestStub] = {}

    def __init__(
        self,
        *,
        host: str = "compute.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: str = None,
        scopes: Sequence[str] = None,
        client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        url_scheme: str = "https",
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.

            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional(Sequence[str])): A list of scopes. This argument is
                ignored if ``channel`` is provided.
            client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
                certificate to configure mutual TLS HTTP channel. It is ignored
                if ``channel`` is provided.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you are developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.
            url_scheme: the protocol scheme for the API endpoint.  Normally
                "https", but for testing or local servers,
                "http" can be specified.
        """
        # Run the base constructor
        # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
        # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
        # credentials object
        super().__init__(
            host=host,
            credentials=credentials,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
        )
        self._session = AuthorizedSession(self._credentials,
                                          default_host=self.DEFAULT_HOST)
        if client_cert_source_for_mtls:
            self._session.configure_mtls_channel(client_cert_source_for_mtls)
        self._prep_wrapped_messages(client_info)

    class _Get(ZonesRestStub):
        def __hash__(self):
            return hash("Get")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
                self,
                request: compute.GetZoneRequest,
                *,
                retry: OptionalRetry = gapic_v1.method.DEFAULT,
                timeout: float = None,
                metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Zone:
            r"""Call the get method over HTTP.

            Args:
                request (~.compute.GetZoneRequest):
                    The request object. A request message for Zones.Get. See
                the method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Zone:
                    Represents a Zone resource. A zone is
                a deployment area. These deployment
                areas are subsets of a region. For
                example the zone us-east1-a is located
                in the us-east1 region. For more
                information, read Regions and Zones.

            """

            http_options = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/zones/{zone}",
                },
            ]

            request_kwargs = compute.GetZoneRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.GetZoneRequest.to_json(
                    compute.GetZoneRequest(transcoded_request["query_params"]),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                ))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Zone.from_json(response.content,
                                          ignore_unknown_fields=True)

    class _List(ZonesRestStub):
        def __hash__(self):
            return hash("List")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
                self,
                request: compute.ListZonesRequest,
                *,
                retry: OptionalRetry = gapic_v1.method.DEFAULT,
                timeout: float = None,
                metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.ZoneList:
            r"""Call the list method over HTTP.

            Args:
                request (~.compute.ListZonesRequest):
                    The request object. A request message for Zones.List. See
                the method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.ZoneList:
                    Contains a list of zone resources.
            """

            http_options = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/zones",
                },
            ]

            request_kwargs = compute.ListZonesRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.ListZonesRequest.to_json(
                    compute.ListZonesRequest(
                        transcoded_request["query_params"]),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                ))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.ZoneList.from_json(response.content,
                                              ignore_unknown_fields=True)

    @property
    def get(self) -> Callable[[compute.GetZoneRequest], compute.Zone]:
        stub = self._STUBS.get("get")
        if not stub:
            stub = self._STUBS["get"] = self._Get(self._session, self._host)

        return stub

    @property
    def list(self) -> Callable[[compute.ListZonesRequest], compute.ZoneList]:
        stub = self._STUBS.get("list")
        if not stub:
            stub = self._STUBS["list"] = self._List(self._session, self._host)

        return stub

    def close(self):
        self._session.close()
Exemple #5
0
class ReservationsRestTransport(ReservationsTransport):
    """REST backend transport for Reservations.

    The Reservations API.

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends JSON representations of protocol buffers over HTTP/1.1
    """

    _STUBS: Dict[str, ReservationsRestStub] = {}

    def __init__(
        self,
        *,
        host: str = "compute.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: str = None,
        scopes: Sequence[str] = None,
        client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        url_scheme: str = "https",
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.

            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional(Sequence[str])): A list of scopes. This argument is
                ignored if ``channel`` is provided.
            client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
                certificate to configure mutual TLS HTTP channel. It is ignored
                if ``channel`` is provided.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you are developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.
            url_scheme: the protocol scheme for the API endpoint.  Normally
                "https", but for testing or local servers,
                "http" can be specified.
        """
        # Run the base constructor
        # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
        # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
        # credentials object
        super().__init__(
            host=host,
            credentials=credentials,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
        )
        self._session = AuthorizedSession(
            self._credentials, default_host=self.DEFAULT_HOST
        )
        if client_cert_source_for_mtls:
            self._session.configure_mtls_channel(client_cert_source_for_mtls)
        self._prep_wrapped_messages(client_info)

    class _AggregatedList(ReservationsRestStub):
        def __hash__(self):
            return hash("AggregatedList")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.AggregatedListReservationsRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.ReservationAggregatedList:
            r"""Call the aggregated list method over HTTP.

            Args:
                request (~.compute.AggregatedListReservationsRequest):
                    The request object. A request message for
                Reservations.AggregatedList. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.ReservationAggregatedList:
                    Contains a list of reservations.
            """

            http_options = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/aggregated/reservations",
                },
            ]

            request_kwargs = compute.AggregatedListReservationsRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.AggregatedListReservationsRequest.to_json(
                    compute.AggregatedListReservationsRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.ReservationAggregatedList.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _Delete(ReservationsRestStub):
        def __hash__(self):
            return hash("Delete")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.DeleteReservationRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the delete method over HTTP.

            Args:
                request (~.compute.DeleteReservationRequest):
                    The request object. A request message for
                Reservations.Delete. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options = [
                {
                    "method": "delete",
                    "uri": "/compute/v1/projects/{project}/zones/{zone}/reservations/{reservation}",
                },
            ]

            request_kwargs = compute.DeleteReservationRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.DeleteReservationRequest.to_json(
                    compute.DeleteReservationRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Operation.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _Get(ReservationsRestStub):
        def __hash__(self):
            return hash("Get")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.GetReservationRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Reservation:
            r"""Call the get method over HTTP.

            Args:
                request (~.compute.GetReservationRequest):
                    The request object. A request message for
                Reservations.Get. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Reservation:
                    Represents a reservation resource. A
                reservation ensures that capacity is
                held in a specific zone even if the
                reserved VMs are not running. For more
                information, read Reserving zonal
                resources.

            """

            http_options = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/zones/{zone}/reservations/{reservation}",
                },
            ]

            request_kwargs = compute.GetReservationRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.GetReservationRequest.to_json(
                    compute.GetReservationRequest(transcoded_request["query_params"]),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Reservation.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _GetIamPolicy(ReservationsRestStub):
        def __hash__(self):
            return hash("GetIamPolicy")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.GetIamPolicyReservationRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Policy:
            r"""Call the get iam policy method over HTTP.

            Args:
                request (~.compute.GetIamPolicyReservationRequest):
                    The request object. A request message for
                Reservations.GetIamPolicy. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Policy:
                    An Identity and Access Management (IAM) policy, which
                specifies access controls for Google Cloud resources. A
                ``Policy`` is a collection of ``bindings``. A
                ``binding`` binds one or more ``members`` to a single
                ``role``. Members can be user accounts, service
                accounts, Google groups, and domains (such as G Suite).
                A ``role`` is a named list of permissions; each ``role``
                can be an IAM predefined role or a user-created custom
                role. For some types of Google Cloud resources, a
                ``binding`` can also specify a ``condition``, which is a
                logical expression that allows access to a resource only
                if the expression evaluates to ``true``. A condition can
                add constraints based on attributes of the request, the
                resource, or both. To learn which resources support
                conditions in their IAM policies, see the `IAM
                documentation <https://cloud.google.com/iam/help/conditions/resource-policies>`__.
                **JSON example:** { "bindings": [ { "role":
                "roles/resourcemanager.organizationAdmin", "members": [
                "user:[email protected]", "group:[email protected]",
                "domain:google.com",
                "serviceAccount:[email protected]"
                ] }, { "role":
                "roles/resourcemanager.organizationViewer", "members": [
                "user:[email protected]" ], "condition": { "title":
                "expirable access", "description": "Does not grant
                access after Sep 2020", "expression": "request.time <
                timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag":
                "BwWWja0YfJA=", "version": 3 } **YAML example:**
                bindings: - members: - user:[email protected] -
                group:[email protected] - domain:google.com -
                serviceAccount:[email protected]
                role: roles/resourcemanager.organizationAdmin - members:
                - user:[email protected] role:
                roles/resourcemanager.organizationViewer condition:
                title: expirable access description: Does not grant
                access after Sep 2020 expression: request.time <
                timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA=
                version: 3 For a description of IAM and its features,
                see the `IAM
                documentation <https://cloud.google.com/iam/docs/>`__.

            """

            http_options = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/zones/{zone}/reservations/{resource}/getIamPolicy",
                },
            ]

            request_kwargs = compute.GetIamPolicyReservationRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.GetIamPolicyReservationRequest.to_json(
                    compute.GetIamPolicyReservationRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Policy.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _Insert(ReservationsRestStub):
        def __hash__(self):
            return hash("Insert")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.InsertReservationRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the insert method over HTTP.

            Args:
                request (~.compute.InsertReservationRequest):
                    The request object. A request message for
                Reservations.Insert. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options = [
                {
                    "method": "post",
                    "uri": "/compute/v1/projects/{project}/zones/{zone}/reservations",
                    "body": "reservation_resource",
                },
            ]

            request_kwargs = compute.InsertReservationRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            # Jsonify the request body
            body = compute.Reservation.to_json(
                compute.Reservation(transcoded_request["body"]),
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.InsertReservationRequest.to_json(
                    compute.InsertReservationRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Operation.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _List(ReservationsRestStub):
        def __hash__(self):
            return hash("List")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.ListReservationsRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.ReservationList:
            r"""Call the list method over HTTP.

            Args:
                request (~.compute.ListReservationsRequest):
                    The request object. A request message for
                Reservations.List. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.ReservationList:

            """

            http_options = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/zones/{zone}/reservations",
                },
            ]

            request_kwargs = compute.ListReservationsRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.ListReservationsRequest.to_json(
                    compute.ListReservationsRequest(transcoded_request["query_params"]),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.ReservationList.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _Resize(ReservationsRestStub):
        def __hash__(self):
            return hash("Resize")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.ResizeReservationRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the resize method over HTTP.

            Args:
                request (~.compute.ResizeReservationRequest):
                    The request object. A request message for
                Reservations.Resize. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options = [
                {
                    "method": "post",
                    "uri": "/compute/v1/projects/{project}/zones/{zone}/reservations/{reservation}/resize",
                    "body": "reservations_resize_request_resource",
                },
            ]

            request_kwargs = compute.ResizeReservationRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            # Jsonify the request body
            body = compute.ReservationsResizeRequest.to_json(
                compute.ReservationsResizeRequest(transcoded_request["body"]),
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.ResizeReservationRequest.to_json(
                    compute.ResizeReservationRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Operation.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _SetIamPolicy(ReservationsRestStub):
        def __hash__(self):
            return hash("SetIamPolicy")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.SetIamPolicyReservationRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Policy:
            r"""Call the set iam policy method over HTTP.

            Args:
                request (~.compute.SetIamPolicyReservationRequest):
                    The request object. A request message for
                Reservations.SetIamPolicy. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Policy:
                    An Identity and Access Management (IAM) policy, which
                specifies access controls for Google Cloud resources. A
                ``Policy`` is a collection of ``bindings``. A
                ``binding`` binds one or more ``members`` to a single
                ``role``. Members can be user accounts, service
                accounts, Google groups, and domains (such as G Suite).
                A ``role`` is a named list of permissions; each ``role``
                can be an IAM predefined role or a user-created custom
                role. For some types of Google Cloud resources, a
                ``binding`` can also specify a ``condition``, which is a
                logical expression that allows access to a resource only
                if the expression evaluates to ``true``. A condition can
                add constraints based on attributes of the request, the
                resource, or both. To learn which resources support
                conditions in their IAM policies, see the `IAM
                documentation <https://cloud.google.com/iam/help/conditions/resource-policies>`__.
                **JSON example:** { "bindings": [ { "role":
                "roles/resourcemanager.organizationAdmin", "members": [
                "user:[email protected]", "group:[email protected]",
                "domain:google.com",
                "serviceAccount:[email protected]"
                ] }, { "role":
                "roles/resourcemanager.organizationViewer", "members": [
                "user:[email protected]" ], "condition": { "title":
                "expirable access", "description": "Does not grant
                access after Sep 2020", "expression": "request.time <
                timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag":
                "BwWWja0YfJA=", "version": 3 } **YAML example:**
                bindings: - members: - user:[email protected] -
                group:[email protected] - domain:google.com -
                serviceAccount:[email protected]
                role: roles/resourcemanager.organizationAdmin - members:
                - user:[email protected] role:
                roles/resourcemanager.organizationViewer condition:
                title: expirable access description: Does not grant
                access after Sep 2020 expression: request.time <
                timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA=
                version: 3 For a description of IAM and its features,
                see the `IAM
                documentation <https://cloud.google.com/iam/docs/>`__.

            """

            http_options = [
                {
                    "method": "post",
                    "uri": "/compute/v1/projects/{project}/zones/{zone}/reservations/{resource}/setIamPolicy",
                    "body": "zone_set_policy_request_resource",
                },
            ]

            request_kwargs = compute.SetIamPolicyReservationRequest.to_dict(request)
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            # Jsonify the request body
            body = compute.ZoneSetPolicyRequest.to_json(
                compute.ZoneSetPolicyRequest(transcoded_request["body"]),
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.SetIamPolicyReservationRequest.to_json(
                    compute.SetIamPolicyReservationRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Policy.from_json(
                response.content, ignore_unknown_fields=True
            )

    class _TestIamPermissions(ReservationsRestStub):
        def __hash__(self):
            return hash("TestIamPermissions")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.TestIamPermissionsReservationRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.TestPermissionsResponse:
            r"""Call the test iam permissions method over HTTP.

            Args:
                request (~.compute.TestIamPermissionsReservationRequest):
                    The request object. A request message for
                Reservations.TestIamPermissions. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.TestPermissionsResponse:

            """

            http_options = [
                {
                    "method": "post",
                    "uri": "/compute/v1/projects/{project}/zones/{zone}/reservations/{resource}/testIamPermissions",
                    "body": "test_permissions_request_resource",
                },
            ]

            request_kwargs = compute.TestIamPermissionsReservationRequest.to_dict(
                request
            )
            transcoded_request = path_template.transcode(http_options, **request_kwargs)

            # Jsonify the request body
            body = compute.TestPermissionsRequest.to_json(
                compute.TestPermissionsRequest(transcoded_request["body"]),
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.TestIamPermissionsReservationRequest.to_json(
                    compute.TestIamPermissionsReservationRequest(
                        transcoded_request["query_params"]
                    ),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.TestPermissionsResponse.from_json(
                response.content, ignore_unknown_fields=True
            )

    @property
    def aggregated_list(
        self,
    ) -> Callable[
        [compute.AggregatedListReservationsRequest], compute.ReservationAggregatedList
    ]:
        stub = self._STUBS.get("aggregated_list")
        if not stub:
            stub = self._STUBS["aggregated_list"] = self._AggregatedList(
                self._session, self._host
            )

        return stub

    @property
    def delete(self) -> Callable[[compute.DeleteReservationRequest], compute.Operation]:
        stub = self._STUBS.get("delete")
        if not stub:
            stub = self._STUBS["delete"] = self._Delete(self._session, self._host)

        return stub

    @property
    def get(self) -> Callable[[compute.GetReservationRequest], compute.Reservation]:
        stub = self._STUBS.get("get")
        if not stub:
            stub = self._STUBS["get"] = self._Get(self._session, self._host)

        return stub

    @property
    def get_iam_policy(
        self,
    ) -> Callable[[compute.GetIamPolicyReservationRequest], compute.Policy]:
        stub = self._STUBS.get("get_iam_policy")
        if not stub:
            stub = self._STUBS["get_iam_policy"] = self._GetIamPolicy(
                self._session, self._host
            )

        return stub

    @property
    def insert(self) -> Callable[[compute.InsertReservationRequest], compute.Operation]:
        stub = self._STUBS.get("insert")
        if not stub:
            stub = self._STUBS["insert"] = self._Insert(self._session, self._host)

        return stub

    @property
    def list(
        self,
    ) -> Callable[[compute.ListReservationsRequest], compute.ReservationList]:
        stub = self._STUBS.get("list")
        if not stub:
            stub = self._STUBS["list"] = self._List(self._session, self._host)

        return stub

    @property
    def resize(self) -> Callable[[compute.ResizeReservationRequest], compute.Operation]:
        stub = self._STUBS.get("resize")
        if not stub:
            stub = self._STUBS["resize"] = self._Resize(self._session, self._host)

        return stub

    @property
    def set_iam_policy(
        self,
    ) -> Callable[[compute.SetIamPolicyReservationRequest], compute.Policy]:
        stub = self._STUBS.get("set_iam_policy")
        if not stub:
            stub = self._STUBS["set_iam_policy"] = self._SetIamPolicy(
                self._session, self._host
            )

        return stub

    @property
    def test_iam_permissions(
        self,
    ) -> Callable[
        [compute.TestIamPermissionsReservationRequest], compute.TestPermissionsResponse
    ]:
        stub = self._STUBS.get("test_iam_permissions")
        if not stub:
            stub = self._STUBS["test_iam_permissions"] = self._TestIamPermissions(
                self._session, self._host
            )

        return stub

    def close(self):
        self._session.close()
class LoggingServiceV2RestTransport(LoggingServiceV2Transport):
    """REST backend transport for LoggingServiceV2.

    Service for ingesting and querying logs.

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends JSON representations of protocol buffers over HTTP/1.1
    """
    _STUBS: Dict[str, LoggingServiceV2RestStub] = {}

    def __init__(
        self,
        *,
        host: str = 'logging.googleapis.com',
        credentials: ga_credentials.Credentials = None,
        credentials_file: str = None,
        scopes: Sequence[str] = None,
        client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        url_scheme: str = 'https',
        interceptor: Optional[LoggingServiceV2RestInterceptor] = None,
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.

            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional(Sequence[str])): A list of scopes. This argument is
                ignored if ``channel`` is provided.
            client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
                certificate to configure mutual TLS HTTP channel. It is ignored
                if ``channel`` is provided.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you are developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.
            url_scheme: the protocol scheme for the API endpoint.  Normally
                "https", but for testing or local servers,
                "http" can be specified.
        """
        # Run the base constructor
        # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
        # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
        # credentials object
        maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$",
                                   host)
        if maybe_url_match is None:
            raise ValueError(
                f"Unexpected hostname structure: {host}")  # pragma: NO COVER

        url_match_items = maybe_url_match.groupdict()

        host = f"{url_scheme}://{host}" if not url_match_items[
            "scheme"] else host

        super().__init__(
            host=host,
            credentials=credentials,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
        )
        self._session = AuthorizedSession(self._credentials,
                                          default_host=self.DEFAULT_HOST)
        if client_cert_source_for_mtls:
            self._session.configure_mtls_channel(client_cert_source_for_mtls)
        self._interceptor = interceptor or LoggingServiceV2RestInterceptor()
        self._prep_wrapped_messages(client_info)

    class _DeleteLog(LoggingServiceV2RestStub):
        def __hash__(self):
            return hash("DeleteLog")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
                self,
                request: logging.DeleteLogRequest,
                *,
                retry: OptionalRetry = gapic_v1.method.DEFAULT,
                timeout: float = None,
                metadata: Sequence[Tuple[str, str]] = (),
        ):
            r"""Call the delete log method over HTTP.

            Args:
                request (~.logging.DeleteLogRequest):
                    The request object. The parameters to DeleteLog.
                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.
            """

            http_options: List[Dict[str, str]] = [
                {
                    'method': 'delete',
                    'uri': '/v2/{log_name=projects/*/logs/*}',
                },
                {
                    'method': 'delete',
                    'uri': '/v2/{log_name=*/*/logs/*}',
                },
                {
                    'method': 'delete',
                    'uri': '/v2/{log_name=organizations/*/logs/*}',
                },
                {
                    'method': 'delete',
                    'uri': '/v2/{log_name=folders/*/logs/*}',
                },
                {
                    'method': 'delete',
                    'uri': '/v2/{log_name=billingAccounts/*/logs/*}',
                },
            ]
            request, metadata = self._interceptor.pre_delete_log(
                request, metadata)
            request_kwargs = logging.DeleteLogRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            uri = transcoded_request['uri']
            method = transcoded_request['method']

            # Jsonify the query params
            query_params = json.loads(
                logging.DeleteLogRequest.to_json(
                    logging.DeleteLogRequest(
                        transcoded_request['query_params']),
                    including_default_value_fields=False,
                    use_integers_for_enums=False))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers['Content-Type'] = 'application/json'
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

    class _ListLogEntries(LoggingServiceV2RestStub):
        def __hash__(self):
            return hash("ListLogEntries")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: logging.ListLogEntriesRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> logging.ListLogEntriesResponse:
            r"""Call the list log entries method over HTTP.

            Args:
                request (~.logging.ListLogEntriesRequest):
                    The request object. The parameters to ``ListLogEntries``.
                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.logging.ListLogEntriesResponse:
                    Result returned from ``ListLogEntries``.
            """

            http_options: List[Dict[str, str]] = [
                {
                    'method': 'post',
                    'uri': '/v2beta1/entries:list',
                    'body': '*',
                },
                {
                    'method': 'post',
                    'uri': '/v2/entries:list',
                    'body': '*',
                },
            ]
            request, metadata = self._interceptor.pre_list_log_entries(
                request, metadata)
            request_kwargs = logging.ListLogEntriesRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            # Jsonify the request body
            body = logging.ListLogEntriesRequest.to_json(
                logging.ListLogEntriesRequest(transcoded_request['body']),
                including_default_value_fields=False,
                use_integers_for_enums=False)
            uri = transcoded_request['uri']
            method = transcoded_request['method']

            # Jsonify the query params
            query_params = json.loads(
                logging.ListLogEntriesRequest.to_json(
                    logging.ListLogEntriesRequest(
                        transcoded_request['query_params']),
                    including_default_value_fields=False,
                    use_integers_for_enums=False))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers['Content-Type'] = 'application/json'
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = logging.ListLogEntriesResponse.from_json(
                response.content, ignore_unknown_fields=True)
            resp = self._interceptor.post_list_log_entries(resp)
            return resp

    class _ListLogs(LoggingServiceV2RestStub):
        def __hash__(self):
            return hash("ListLogs")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: logging.ListLogsRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> logging.ListLogsResponse:
            r"""Call the list logs method over HTTP.

            Args:
                request (~.logging.ListLogsRequest):
                    The request object. The parameters to ListLogs.
                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.logging.ListLogsResponse:
                    Result returned from ListLogs.
            """

            http_options: List[Dict[str, str]] = [
                {
                    'method': 'get',
                    'uri': '/v2/{parent=*/*}/logs',
                },
                {
                    'method': 'get',
                    'uri': '/v2/{parent=projects/*}/logs',
                },
                {
                    'method': 'get',
                    'uri': '/v2/{parent=organizations/*}/logs',
                },
                {
                    'method': 'get',
                    'uri': '/v2/{parent=folders/*}/logs',
                },
                {
                    'method': 'get',
                    'uri': '/v2/{parent=billingAccounts/*}/logs',
                },
                {
                    'method':
                    'get',
                    'uri':
                    '/v2/{parent=projects/*/locations/*/buckets/*/views/*}/logs',
                },
                {
                    'method':
                    'get',
                    'uri':
                    '/v2/{parent=organizations/*/locations/*/buckets/*/views/*}/logs',
                },
                {
                    'method':
                    'get',
                    'uri':
                    '/v2/{parent=folders/*/locations/*/buckets/*/views/*}/logs',
                },
                {
                    'method':
                    'get',
                    'uri':
                    '/v2/{parent=billingAccounts/*/locations/*/buckets/*/views/*}/logs',
                },
            ]
            request, metadata = self._interceptor.pre_list_logs(
                request, metadata)
            request_kwargs = logging.ListLogsRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            uri = transcoded_request['uri']
            method = transcoded_request['method']

            # Jsonify the query params
            query_params = json.loads(
                logging.ListLogsRequest.to_json(
                    logging.ListLogsRequest(
                        transcoded_request['query_params']),
                    including_default_value_fields=False,
                    use_integers_for_enums=False))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers['Content-Type'] = 'application/json'
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = logging.ListLogsResponse.from_json(
                response.content, ignore_unknown_fields=True)
            resp = self._interceptor.post_list_logs(resp)
            return resp

    class _ListMonitoredResourceDescriptors(LoggingServiceV2RestStub):
        def __hash__(self):
            return hash("ListMonitoredResourceDescriptors")

        def __call__(
            self,
            request: logging.ListMonitoredResourceDescriptorsRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> logging.ListMonitoredResourceDescriptorsResponse:
            r"""Call the list monitored resource
        descriptors method over HTTP.

            Args:
                request (~.logging.ListMonitoredResourceDescriptorsRequest):
                    The request object. The parameters to
                ListMonitoredResourceDescriptors

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.logging.ListMonitoredResourceDescriptorsResponse:
                    Result returned from
                ListMonitoredResourceDescriptors.

            """

            http_options: List[Dict[str, str]] = [
                {
                    'method': 'get',
                    'uri': '/v2/monitoredResourceDescriptors',
                },
            ]
            request, metadata = self._interceptor.pre_list_monitored_resource_descriptors(
                request, metadata)
            request_kwargs = logging.ListMonitoredResourceDescriptorsRequest.to_dict(
                request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            uri = transcoded_request['uri']
            method = transcoded_request['method']

            # Jsonify the query params
            query_params = json.loads(
                logging.ListMonitoredResourceDescriptorsRequest.to_json(
                    logging.ListMonitoredResourceDescriptorsRequest(
                        transcoded_request['query_params']),
                    including_default_value_fields=False,
                    use_integers_for_enums=False))

            # Send the request
            headers = dict(metadata)
            headers['Content-Type'] = 'application/json'
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = logging.ListMonitoredResourceDescriptorsResponse.from_json(
                response.content, ignore_unknown_fields=True)
            resp = self._interceptor.post_list_monitored_resource_descriptors(
                resp)
            return resp

    class _TailLogEntries(LoggingServiceV2RestStub):
        def __hash__(self):
            return hash("TailLogEntries")

        def __call__(
            self,
            request: logging.TailLogEntriesRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> rest_streaming.ResponseIterator:
            raise NotImplementedError(
                "Client streaming over REST is not yet defined for python client"
            )

    class _WriteLogEntries(LoggingServiceV2RestStub):
        def __hash__(self):
            return hash("WriteLogEntries")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: logging.WriteLogEntriesRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> logging.WriteLogEntriesResponse:
            r"""Call the write log entries method over HTTP.

            Args:
                request (~.logging.WriteLogEntriesRequest):
                    The request object. The parameters to WriteLogEntries.
                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.logging.WriteLogEntriesResponse:
                    Result returned from WriteLogEntries.
            """

            http_options: List[Dict[str, str]] = [
                {
                    'method': 'post',
                    'uri': '/v2/entries:write',
                    'body': '*',
                },
                {
                    'method': 'post',
                    'uri': '/v2beta1/entries:write',
                    'body': '*',
                },
            ]
            request, metadata = self._interceptor.pre_write_log_entries(
                request, metadata)
            request_kwargs = logging.WriteLogEntriesRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            # Jsonify the request body
            body = logging.WriteLogEntriesRequest.to_json(
                logging.WriteLogEntriesRequest(transcoded_request['body']),
                including_default_value_fields=False,
                use_integers_for_enums=False)
            uri = transcoded_request['uri']
            method = transcoded_request['method']

            # Jsonify the query params
            query_params = json.loads(
                logging.WriteLogEntriesRequest.to_json(
                    logging.WriteLogEntriesRequest(
                        transcoded_request['query_params']),
                    including_default_value_fields=False,
                    use_integers_for_enums=False))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers['Content-Type'] = 'application/json'
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = logging.WriteLogEntriesResponse.from_json(
                response.content, ignore_unknown_fields=True)
            resp = self._interceptor.post_write_log_entries(resp)
            return resp

    @property
    def delete_log(
            self) -> Callable[[logging.DeleteLogRequest], empty_pb2.Empty]:
        stub = self._STUBS.get("delete_log")
        if not stub:
            stub = self._STUBS["delete_log"] = self._DeleteLog(
                self._session, self._host, self._interceptor)

        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return stub  # type: ignore

    @property
    def list_log_entries(
        self
    ) -> Callable[[logging.ListLogEntriesRequest],
                  logging.ListLogEntriesResponse]:
        stub = self._STUBS.get("list_log_entries")
        if not stub:
            stub = self._STUBS["list_log_entries"] = self._ListLogEntries(
                self._session, self._host, self._interceptor)

        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return stub  # type: ignore

    @property
    def list_logs(
            self
    ) -> Callable[[logging.ListLogsRequest], logging.ListLogsResponse]:
        stub = self._STUBS.get("list_logs")
        if not stub:
            stub = self._STUBS["list_logs"] = self._ListLogs(
                self._session, self._host, self._interceptor)

        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return stub  # type: ignore

    @property
    def list_monitored_resource_descriptors(
        self
    ) -> Callable[[logging.ListMonitoredResourceDescriptorsRequest],
                  logging.ListMonitoredResourceDescriptorsResponse]:
        stub = self._STUBS.get("list_monitored_resource_descriptors")
        if not stub:
            stub = self._STUBS[
                "list_monitored_resource_descriptors"] = self._ListMonitoredResourceDescriptors(
                    self._session, self._host, self._interceptor)

        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return stub  # type: ignore

    @property
    def tail_log_entries(
        self
    ) -> Callable[[logging.TailLogEntriesRequest],
                  logging.TailLogEntriesResponse]:
        stub = self._STUBS.get("tail_log_entries")
        if not stub:
            stub = self._STUBS["tail_log_entries"] = self._TailLogEntries(
                self._session, self._host, self._interceptor)

        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return stub  # type: ignore

    @property
    def write_log_entries(
        self
    ) -> Callable[[logging.WriteLogEntriesRequest],
                  logging.WriteLogEntriesResponse]:
        stub = self._STUBS.get("write_log_entries")
        if not stub:
            stub = self._STUBS["write_log_entries"] = self._WriteLogEntries(
                self._session, self._host, self._interceptor)

        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return stub  # type: ignore

    def close(self):
        self._session.close()
Exemple #7
0
class HealthChecksRestTransport(HealthChecksTransport):
    """REST backend transport for HealthChecks.

    The HealthChecks API.

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends JSON representations of protocol buffers over HTTP/1.1
    """

    _STUBS: Dict[str, HealthChecksRestStub] = {}

    def __init__(
        self,
        *,
        host: str = "compute.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: str = None,
        scopes: Sequence[str] = None,
        client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        url_scheme: str = "https",
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.

            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional(Sequence[str])): A list of scopes. This argument is
                ignored if ``channel`` is provided.
            client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
                certificate to configure mutual TLS HTTP channel. It is ignored
                if ``channel`` is provided.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you are developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.
            url_scheme: the protocol scheme for the API endpoint.  Normally
                "https", but for testing or local servers,
                "http" can be specified.
        """
        # Run the base constructor
        # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
        # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
        # credentials object
        super().__init__(
            host=host,
            credentials=credentials,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
        )
        self._session = AuthorizedSession(self._credentials,
                                          default_host=self.DEFAULT_HOST)
        if client_cert_source_for_mtls:
            self._session.configure_mtls_channel(client_cert_source_for_mtls)
        self._prep_wrapped_messages(client_info)

    class _AggregatedList(HealthChecksRestStub):
        def __hash__(self):
            return hash("AggregatedList")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.AggregatedListHealthChecksRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.HealthChecksAggregatedList:
            r"""Call the aggregated list method over HTTP.

            Args:
                request (~.compute.AggregatedListHealthChecksRequest):
                    The request object. A request message for
                HealthChecks.AggregatedList. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.HealthChecksAggregatedList:

            """

            http_options = [
                {
                    "method":
                    "get",
                    "uri":
                    "/compute/v1/projects/{project}/aggregated/healthChecks",
                },
            ]

            request_kwargs = compute.AggregatedListHealthChecksRequest.to_dict(
                request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.AggregatedListHealthChecksRequest.to_json(
                    compute.AggregatedListHealthChecksRequest(
                        transcoded_request["query_params"]),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                ))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.HealthChecksAggregatedList.from_json(
                response.content, ignore_unknown_fields=True)

    class _Delete(HealthChecksRestStub):
        def __hash__(self):
            return hash("Delete")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
                self,
                request: compute.DeleteHealthCheckRequest,
                *,
                retry: OptionalRetry = gapic_v1.method.DEFAULT,
                timeout: float = None,
                metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the delete method over HTTP.

            Args:
                request (~.compute.DeleteHealthCheckRequest):
                    The request object. A request message for
                HealthChecks.Delete. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options = [
                {
                    "method":
                    "delete",
                    "uri":
                    "/compute/v1/projects/{project}/global/healthChecks/{health_check}",
                },
            ]

            request_kwargs = compute.DeleteHealthCheckRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.DeleteHealthCheckRequest.to_json(
                    compute.DeleteHealthCheckRequest(
                        transcoded_request["query_params"]),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                ))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Operation.from_json(response.content,
                                               ignore_unknown_fields=True)

    class _Get(HealthChecksRestStub):
        def __hash__(self):
            return hash("Get")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
                self,
                request: compute.GetHealthCheckRequest,
                *,
                retry: OptionalRetry = gapic_v1.method.DEFAULT,
                timeout: float = None,
                metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.HealthCheck:
            r"""Call the get method over HTTP.

            Args:
                request (~.compute.GetHealthCheckRequest):
                    The request object. A request message for
                HealthChecks.Get. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.HealthCheck:
                    Represents a Health Check resource. Google Compute
                Engine has two Health Check resources: \*
                `Global </compute/docs/reference/rest/v1/healthChecks>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionHealthChecks>`__
                Internal HTTP(S) load balancers must use regional health
                checks (``compute.v1.regionHealthChecks``). Traffic
                Director must use global health checks
                (``compute.v1.HealthChecks``). Internal TCP/UDP load
                balancers can use either regional or global health
                checks (``compute.v1.regionHealthChecks`` or
                ``compute.v1.HealthChecks``). External HTTP(S), TCP
                proxy, and SSL proxy load balancers as well as managed
                instance group auto-healing must use global health
                checks (``compute.v1.HealthChecks``). Backend
                service-based network load balancers must use regional
                health checks (``compute.v1.regionHealthChecks``).
                Target pool-based network load balancers must use legacy
                HTTP health checks (``compute.v1.httpHealthChecks``).
                For more information, see Health checks overview.

            """

            http_options = [
                {
                    "method":
                    "get",
                    "uri":
                    "/compute/v1/projects/{project}/global/healthChecks/{health_check}",
                },
            ]

            request_kwargs = compute.GetHealthCheckRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.GetHealthCheckRequest.to_json(
                    compute.GetHealthCheckRequest(
                        transcoded_request["query_params"]),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                ))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.HealthCheck.from_json(response.content,
                                                 ignore_unknown_fields=True)

    class _Insert(HealthChecksRestStub):
        def __hash__(self):
            return hash("Insert")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
                self,
                request: compute.InsertHealthCheckRequest,
                *,
                retry: OptionalRetry = gapic_v1.method.DEFAULT,
                timeout: float = None,
                metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the insert method over HTTP.

            Args:
                request (~.compute.InsertHealthCheckRequest):
                    The request object. A request message for
                HealthChecks.Insert. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options = [
                {
                    "method": "post",
                    "uri":
                    "/compute/v1/projects/{project}/global/healthChecks",
                    "body": "health_check_resource",
                },
            ]

            request_kwargs = compute.InsertHealthCheckRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            # Jsonify the request body
            body = compute.HealthCheck.to_json(
                compute.HealthCheck(transcoded_request["body"]),
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.InsertHealthCheckRequest.to_json(
                    compute.InsertHealthCheckRequest(
                        transcoded_request["query_params"]),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                ))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Operation.from_json(response.content,
                                               ignore_unknown_fields=True)

    class _List(HealthChecksRestStub):
        def __hash__(self):
            return hash("List")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.ListHealthChecksRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: float = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.HealthCheckList:
            r"""Call the list method over HTTP.

            Args:
                request (~.compute.ListHealthChecksRequest):
                    The request object. A request message for
                HealthChecks.List. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.HealthCheckList:
                    Contains a list of HealthCheck
                resources.

            """

            http_options = [
                {
                    "method": "get",
                    "uri":
                    "/compute/v1/projects/{project}/global/healthChecks",
                },
            ]

            request_kwargs = compute.ListHealthChecksRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.ListHealthChecksRequest.to_json(
                    compute.ListHealthChecksRequest(
                        transcoded_request["query_params"]),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                ))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.HealthCheckList.from_json(
                response.content, ignore_unknown_fields=True)

    class _Patch(HealthChecksRestStub):
        def __hash__(self):
            return hash("Patch")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
                self,
                request: compute.PatchHealthCheckRequest,
                *,
                retry: OptionalRetry = gapic_v1.method.DEFAULT,
                timeout: float = None,
                metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the patch method over HTTP.

            Args:
                request (~.compute.PatchHealthCheckRequest):
                    The request object. A request message for
                HealthChecks.Patch. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options = [
                {
                    "method": "patch",
                    "uri":
                    "/compute/v1/projects/{project}/global/healthChecks/{health_check}",
                    "body": "health_check_resource",
                },
            ]

            request_kwargs = compute.PatchHealthCheckRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            # Jsonify the request body
            body = compute.HealthCheck.to_json(
                compute.HealthCheck(transcoded_request["body"]),
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.PatchHealthCheckRequest.to_json(
                    compute.PatchHealthCheckRequest(
                        transcoded_request["query_params"]),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                ))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Operation.from_json(response.content,
                                               ignore_unknown_fields=True)

    class _Update(HealthChecksRestStub):
        def __hash__(self):
            return hash("Update")

        __REQUIRED_FIELDS_DEFAULT_VALUES = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
                self,
                request: compute.UpdateHealthCheckRequest,
                *,
                retry: OptionalRetry = gapic_v1.method.DEFAULT,
                timeout: float = None,
                metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the update method over HTTP.

            Args:
                request (~.compute.UpdateHealthCheckRequest):
                    The request object. A request message for
                HealthChecks.Update. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options = [
                {
                    "method": "put",
                    "uri":
                    "/compute/v1/projects/{project}/global/healthChecks/{health_check}",
                    "body": "health_check_resource",
                },
            ]

            request_kwargs = compute.UpdateHealthCheckRequest.to_dict(request)
            transcoded_request = path_template.transcode(
                http_options, **request_kwargs)

            # Jsonify the request body
            body = compute.HealthCheck.to_json(
                compute.HealthCheck(transcoded_request["body"]),
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                compute.UpdateHealthCheckRequest.to_json(
                    compute.UpdateHealthCheckRequest(
                        transcoded_request["query_params"]),
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                ))

            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                # Replace with proper schema configuration (http/https) logic
                "https://{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)
            # Return the response
            return compute.Operation.from_json(response.content,
                                               ignore_unknown_fields=True)

    @property
    def aggregated_list(
        self,
    ) -> Callable[[compute.AggregatedListHealthChecksRequest],
                  compute.HealthChecksAggregatedList]:
        stub = self._STUBS.get("aggregated_list")
        if not stub:
            stub = self._STUBS["aggregated_list"] = self._AggregatedList(
                self._session, self._host)

        return stub

    @property
    def delete(
        self
    ) -> Callable[[compute.DeleteHealthCheckRequest], compute.Operation]:
        stub = self._STUBS.get("delete")
        if not stub:
            stub = self._STUBS["delete"] = self._Delete(
                self._session, self._host)

        return stub

    @property
    def get(
        self
    ) -> Callable[[compute.GetHealthCheckRequest], compute.HealthCheck]:
        stub = self._STUBS.get("get")
        if not stub:
            stub = self._STUBS["get"] = self._Get(self._session, self._host)

        return stub

    @property
    def insert(
        self
    ) -> Callable[[compute.InsertHealthCheckRequest], compute.Operation]:
        stub = self._STUBS.get("insert")
        if not stub:
            stub = self._STUBS["insert"] = self._Insert(
                self._session, self._host)

        return stub

    @property
    def list(
        self,
    ) -> Callable[[compute.ListHealthChecksRequest], compute.HealthCheckList]:
        stub = self._STUBS.get("list")
        if not stub:
            stub = self._STUBS["list"] = self._List(self._session, self._host)

        return stub

    @property
    def patch(
        self
    ) -> Callable[[compute.PatchHealthCheckRequest], compute.Operation]:
        stub = self._STUBS.get("patch")
        if not stub:
            stub = self._STUBS["patch"] = self._Patch(self._session,
                                                      self._host)

        return stub

    @property
    def update(
        self
    ) -> Callable[[compute.UpdateHealthCheckRequest], compute.Operation]:
        stub = self._STUBS.get("update")
        if not stub:
            stub = self._STUBS["update"] = self._Update(
                self._session, self._host)

        return stub

    def close(self):
        self._session.close()
Exemple #8
0
class GooglePlayService(InAppService):
    scopes = ['https://www.googleapis.com/auth/androidpublisher']
    base_uri = 'https://www.googleapis.com/androidpublisher/v3/applications'
    products_uri = '/%packageName%/inappproducts'
    product_purchase_uri = '/%packageName%/purchases/products/%productId%/tokens/%token%'
    subscription_purchase_uri = '/%packageName%/purchases/subscriptions/%subscriptionId%/'+\
                                'tokens/%token%'

    service_account_info = None
    service_account_file = None
    credentials = None
    authed_session = None
    package_name = None

    def __init__(self,
                 service_account_info=None,
                 service_account_file=None,
                 package_name=None,
                 scopes=None,
                 base_uri=None,
                 products_uri=None,
                 product_purchase_uri=None,
                 subscription_purchase_uri=None):
        if scopes is not None:
            self.scopes = scopes
        if base_uri is not None:
            self.base_uri = base_uri
        if products_uri is not None:
            self.products_uri = products_uri
        if product_purchase_uri is not None:
            self.product_purchase_uri = product_purchase_uri
        if subscription_purchase_uri is not None:
            self.subscription_purchase_uri = subscription_purchase_uri
        if service_account_info is not None:
            self.service_account_info = service_account_info
        if service_account_file is not None:
            self.service_account_file = service_account_file
        if package_name is not None:
            self.package_name = package_name
        if self.service_account_info is not None or self.service_account_file is not None:
            self.authed_session = self.create_session()

    def set_service_account_info(self, service_account_info):
        self.service_account_info = service_account_info
        return self

    def set_service_account_file(self, service_account_file):
        self.service_account_file = service_account_file
        return self

    def generate_credentials(self):
        if self.service_account_info is not None:
            self.credentials = service_account.Credentials.from_service_account_info(
                self.service_account_info, scopes=self.scopes)
        elif self.service_account_file is not None:
            self.credentials = service_account.Credentials.from_service_account_file(
                self.service_account_file, scopes=self.scopes)
        return self.credentials

    def create_session(self):
        if self.credentials is None:
            self.credentials = self.generate_credentials()
        if self.credentials is not None:
            self.authed_session = AuthorizedSession(self.credentials)
            return self.authed_session
        if not self.authed_session:
            self.authed_session = None
        return self.authed_session

    def refresh_session(self):
        self.authed_session = self.create_session()

    def close_session(self):
        return self.authed_session.close()

    def get_products(self, package_name=None):
        package_name = package_name if package_name is not None else self.package_name
        response = self.request(
            self.base_uri +
            self.products_uri.replace('%packageName%', package_name))
        return self.get_products_response(response)

    def get_product_purchase(self, product_id, token, package_name=None):
        package_name = package_name if package_name is not None else self.package_name
        response = self.request(
            self.base_uri +
            self.product_purchase_uri.replace('%packageName%', package_name).
            replace('%productId%', product_id).replace('%token%', token))
        return self.get_product_response(response)

    def get_subscription_purchase(self,
                                  subscription_id,
                                  token,
                                  package_name=None):
        package_name = package_name if package_name is not None else self.package_name
        response = self.request(
            self.base_uri + self.subscription_purchase_uri.
            replace('%packageName%', package_name).replace(
                '%subscriptionId%', subscription_id).replace('%token%', token))
        return self.get_subscription_response(response,
                                              additional_data={
                                                  'package_name':
                                                  package_name,
                                                  'subscription_id':
                                                  subscription_id
                                              })

    def request(self, query):
        if self.authed_session is not None:
            response = self.authed_session.get(query)
            return response
        else:
            raise BaseException("authed_session is not defined")

    def get_products_response(self, response, additional_data=None):
        data = None
        if response.ok:
            data = response.json()['inappproduct']
        return super(GooglePlayService,
                     self).get_products_response(response, data)

    def get_product_response(self, response, additional_data=None):
        data = None
        if response.ok:
            data = response.json()
        return super(GooglePlayService,
                     self).get_product_response(response, data)

    def get_subscription_response(self, response, additional_data=None):
        data = None
        try:
            if response.ok:
                response_data = response.json()
                cancellation_date_ms = (
                    int(response_data['userCancellationTimeMillis'])
                    if 'userCancellationTimeMillis' in response_data else None)
                cancellation_date = (int(cancellation_date_ms /
                                         1000) if cancellation_date_ms
                                     is not None else None)
                expires_date_ms = (int(response_data['expiryTimeMillis'])
                                   if 'expiryTimeMillis' in response_data else
                                   None)
                expires_date = (int(expires_date_ms / 1000)
                                if expires_date_ms is not None else None)
                cancellation_reason = (response_data['cancelReason']
                                       if 'cancelReason' in response_data else
                                       None)
                payment_state = (response_data['paymentState']
                                 if 'paymentState' in response_data else None)
                payment_state = (response_data['paymentState']
                                 if 'paymentState' in response_data else None)
                if cancellation_reason is None:
                    status = SubscriptionStatus.ACTIVE
                elif cancellation_reason is not None:
                    status = SubscriptionStatus.CANCELLED
                is_active = status == SubscriptionStatus.ACTIVE
                data = {
                    'purchase_id':
                    response_data['orderId'],
                    'original_purchase_id':
                    response_data['orderId'],
                    'purchase_date_ms':
                    int(response_data['startTimeMillis']),
                    'purchase_date':
                    int(int(response_data['startTimeMillis']) / 1000),
                    'original_purchase_date_ms':
                    int(response_data['startTimeMillis']),
                    'original_purchase_date':
                    int(int(response_data['startTimeMillis']) / 1000),
                    'auto_renewing':
                    response_data['autoRenewing'],
                    'expires_date_ms':
                    expires_date_ms,
                    'expires_date':
                    expires_date,
                    'country_code':
                    response_data['countryCode'],
                    'price_currency_code':
                    response_data['priceCurrencyCode'],
                    'price_amount':
                    float(
                        int(int(response_data['priceAmountMicros']) / 1000) /
                        100),
                    'cancellation_date_ms':
                    cancellation_date_ms,
                    'cancellation_date':
                    cancellation_date,
                    'cancellation_reason':
                    cancellation_reason,
                    'payment_state':
                    payment_state,
                    'status':
                    status,
                    'is_active':
                    is_active,
                    'is_trial_period':
                    None,
                    'expiration_intent':
                    None
                }
                if additional_data is not None:
                    if 'package_name' in additional_data:
                        data.update(
                            {'bundle_id': additional_data['package_name']})
                    if 'subscription_id' in additional_data:
                        data.update({
                            'subscription_id':
                            additional_data['subscription_id']
                        })
            return super(GooglePlayService,
                         self).get_subscription_response(response, data)
        except Exception:
            return super(GooglePlayService,
                         self).get_subscription_response(response)