def updatePass(verticalType, objectId, objectResourcePayload): headers = { 'Accept': 'application/json', 'Content-Type': 'application/json; charset=UTF-8' } credentials = makeOauthCredential() response = None # Define get() REST call of target vertical uri = 'https://walletobjects.googleapis.com/walletobjects/v1' postfix = 'Object' path = createPath(verticalType, postfix, objectId) # There is no Google API for Passes Client Library for Python. # Authorize a http client with credential generated from Google API client library. ## see https://google-auth.readthedocs.io/en/latest/user-guide.html#making-authenticated-requests authed_session = AuthorizedSession(credentials) # make the GET request to make an get(); this returns a response object # other methods require different http methods; for example, get() requires authed_Session.get(...) # check the reference API to make the right REST call ## https://developers.google.com/pay/passes/reference/v1/ ## https://google-auth.readthedocs.io/en/latest/user-guide.html#making-authenticated-requests response = authed_session.put( uri + path, # REST API endpoint headers=headers, # Header; optional json=objectResourcePayload) return response
class RoutersRestTransport(RoutersTransport): """REST backend transport for Routers. The Routers 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 """ 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, ) -> 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're developing your own client library. """ # 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, ) 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) def aggregated_list( self, request: compute.AggregatedListRoutersRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.RouterAggregatedList: r"""Call the aggregated list method over HTTP. Args: request (~.compute.AggregatedListRoutersRequest): The request object. A request message for Routers.AggregatedList. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.RouterAggregatedList: Contains a list of routers. """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/aggregated/routers".format( host=self._host, project=request.project, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.AggregatedListRoutersRequest.filter in request: query_params["filter"] = request.filter if compute.AggregatedListRoutersRequest.include_all_scopes in request: query_params["includeAllScopes"] = request.include_all_scopes if compute.AggregatedListRoutersRequest.max_results in request: query_params["maxResults"] = request.max_results if compute.AggregatedListRoutersRequest.order_by in request: query_params["orderBy"] = request.order_by if compute.AggregatedListRoutersRequest.page_token in request: query_params["pageToken"] = request.page_token if compute.AggregatedListRoutersRequest.return_partial_success in request: query_params[ "returnPartialSuccess"] = request.return_partial_success # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = [ "{k}={v}".format(k=k, v=v) for k, v in query_params.items() ] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.get( url, headers=headers, ) # 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.RouterAggregatedList.from_json( response.content, ignore_unknown_fields=True) def delete( self, request: compute.DeleteRouterRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the delete method over HTTP. Args: request (~.compute.DeleteRouterRequest): The request object. A request message for Routers.Delete. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/routers/{router}".format( host=self._host, project=request.project, region=request.region, router=request.router, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.DeleteRouterRequest.request_id in request: query_params["requestId"] = request.request_id # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = [ "{k}={v}".format(k=k, v=v) for k, v in query_params.items() ] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.delete( url, headers=headers, ) # 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) def get( self, request: compute.GetRouterRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Router: r"""Call the get method over HTTP. Args: request (~.compute.GetRouterRequest): The request object. A request message for Routers.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.Router: Represents a Cloud Router resource. For more information about Cloud Router, read the Cloud Router overview. """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/routers/{router}".format( host=self._host, project=request.project, region=request.region, router=request.router, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = [ "{k}={v}".format(k=k, v=v) for k, v in query_params.items() ] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.get( url, headers=headers, ) # 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.Router.from_json(response.content, ignore_unknown_fields=True) def get_nat_mapping_info( self, request: compute.GetNatMappingInfoRoutersRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.VmEndpointNatMappingsList: r"""Call the get nat mapping info method over HTTP. Args: request (~.compute.GetNatMappingInfoRoutersRequest): The request object. A request message for Routers.GetNatMappingInfo. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.VmEndpointNatMappingsList: Contains a list of VmEndpointNatMappings. """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/routers/{router}/getNatMappingInfo".format( host=self._host, project=request.project, region=request.region, router=request.router, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.GetNatMappingInfoRoutersRequest.filter in request: query_params["filter"] = request.filter if compute.GetNatMappingInfoRoutersRequest.max_results in request: query_params["maxResults"] = request.max_results if compute.GetNatMappingInfoRoutersRequest.order_by in request: query_params["orderBy"] = request.order_by if compute.GetNatMappingInfoRoutersRequest.page_token in request: query_params["pageToken"] = request.page_token if compute.GetNatMappingInfoRoutersRequest.return_partial_success in request: query_params[ "returnPartialSuccess"] = request.return_partial_success # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = [ "{k}={v}".format(k=k, v=v) for k, v in query_params.items() ] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.get( url, headers=headers, ) # 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.VmEndpointNatMappingsList.from_json( response.content, ignore_unknown_fields=True) def get_router_status( self, request: compute.GetRouterStatusRouterRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.RouterStatusResponse: r"""Call the get router status method over HTTP. Args: request (~.compute.GetRouterStatusRouterRequest): The request object. A request message for Routers.GetRouterStatus. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.RouterStatusResponse: """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/routers/{router}/getRouterStatus".format( host=self._host, project=request.project, region=request.region, router=request.router, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = [ "{k}={v}".format(k=k, v=v) for k, v in query_params.items() ] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.get( url, headers=headers, ) # 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.RouterStatusResponse.from_json( response.content, ignore_unknown_fields=True) def insert( self, request: compute.InsertRouterRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the insert method over HTTP. Args: request (~.compute.InsertRouterRequest): The request object. A request message for Routers.Insert. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.Router.to_json( request.router_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/routers".format( host=self._host, project=request.project, region=request.region, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.InsertRouterRequest.request_id in request: query_params["requestId"] = request.request_id # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = [ "{k}={v}".format(k=k, v=v) for k, v in query_params.items() ] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.post( url, headers=headers, 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) def list( self, request: compute.ListRoutersRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.RouterList: r"""Call the list method over HTTP. Args: request (~.compute.ListRoutersRequest): The request object. A request message for Routers.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.RouterList: Contains a list of Router resources. """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/routers".format( host=self._host, project=request.project, region=request.region, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.ListRoutersRequest.filter in request: query_params["filter"] = request.filter if compute.ListRoutersRequest.max_results in request: query_params["maxResults"] = request.max_results if compute.ListRoutersRequest.order_by in request: query_params["orderBy"] = request.order_by if compute.ListRoutersRequest.page_token in request: query_params["pageToken"] = request.page_token if compute.ListRoutersRequest.return_partial_success in request: query_params[ "returnPartialSuccess"] = request.return_partial_success # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = [ "{k}={v}".format(k=k, v=v) for k, v in query_params.items() ] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.get( url, headers=headers, ) # 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.RouterList.from_json(response.content, ignore_unknown_fields=True) def patch( self, request: compute.PatchRouterRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the patch method over HTTP. Args: request (~.compute.PatchRouterRequest): The request object. A request message for Routers.Patch. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.Router.to_json( request.router_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/routers/{router}".format( host=self._host, project=request.project, region=request.region, router=request.router, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.PatchRouterRequest.request_id in request: query_params["requestId"] = request.request_id # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = [ "{k}={v}".format(k=k, v=v) for k, v in query_params.items() ] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.patch( url, headers=headers, 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) def preview( self, request: compute.PreviewRouterRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.RoutersPreviewResponse: r"""Call the preview method over HTTP. Args: request (~.compute.PreviewRouterRequest): The request object. A request message for Routers.Preview. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.RoutersPreviewResponse: """ # Jsonify the request body body = compute.Router.to_json( request.router_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/routers/{router}/preview".format( host=self._host, project=request.project, region=request.region, router=request.router, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = [ "{k}={v}".format(k=k, v=v) for k, v in query_params.items() ] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.post( url, headers=headers, 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.RoutersPreviewResponse.from_json( response.content, ignore_unknown_fields=True) def update( self, request: compute.UpdateRouterRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the update method over HTTP. Args: request (~.compute.UpdateRouterRequest): The request object. A request message for Routers.Update. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.Router.to_json( request.router_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/routers/{router}".format( host=self._host, project=request.project, region=request.region, router=request.router, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.UpdateRouterRequest.request_id in request: query_params["requestId"] = request.request_id # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = [ "{k}={v}".format(k=k, v=v) for k, v in query_params.items() ] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.put( url, headers=headers, 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 RegionUrlMapsRestTransport(RegionUrlMapsTransport): """REST backend transport for RegionUrlMaps. The RegionUrlMaps 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 """ 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, ) -> 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're developing your own client library. """ # 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, ) 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) def delete( self, request: compute.DeleteRegionUrlMapRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the delete method over HTTP. Args: request (~.compute.DeleteRegionUrlMapRequest): The request object. A request message for RegionUrlMaps.Delete. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/urlMaps/{url_map}".format( host=self._host, project=request.project, region=request.region, url_map=request.url_map, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.DeleteRegionUrlMapRequest.request_id in request: query_params["requestId"] = request.request_id # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() # Return the response return compute.Operation.from_json(response.content, ignore_unknown_fields=True) def get( self, request: compute.GetRegionUrlMapRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.UrlMap: r"""Call the get method over HTTP. Args: request (~.compute.GetRegionUrlMapRequest): The request object. A request message for RegionUrlMaps.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.UrlMap: Represents a URL Map resource. Google Compute Engine has two URL Map resources: - `Global </compute/docs/reference/rest/{$api_version}/urlMaps>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionUrlMaps>`__ A URL map resource is a component of certain types of GCP load balancers and Traffic Director. - urlMaps are used by external HTTP(S) load balancers and Traffic Director. \* regionUrlMaps are used by internal HTTP(S) load balancers. For a list of supported URL map features by load balancer type, see the Load balancing features: Routing and traffic management table. For a list of supported URL map features for Traffic Director, see the Traffic Director features: Routing and traffic management table. This resource defines mappings from host names and URL paths to either a backend service or a backend bucket. To use the global urlMaps resource, the backend service must have a loadBalancingScheme of either EXTERNAL or INTERNAL_SELF_MANAGED. To use the regionUrlMaps resource, the backend service must have a loadBalancingScheme of INTERNAL_MANAGED. For more information, read URL Map Concepts. """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/urlMaps/{url_map}".format( host=self._host, project=request.project, region=request.region, url_map=request.url_map, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() # Return the response return compute.UrlMap.from_json(response.content, ignore_unknown_fields=True) def insert( self, request: compute.InsertRegionUrlMapRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the insert method over HTTP. Args: request (~.compute.InsertRegionUrlMapRequest): The request object. A request message for RegionUrlMaps.Insert. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.UrlMap.to_json( request.url_map_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/urlMaps".format( host=self._host, project=request.project, region=request.region, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.InsertRegionUrlMapRequest.request_id in request: query_params["requestId"] = request.request_id # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request response = self._session.post(url, data=body,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() # Return the response return compute.Operation.from_json(response.content, ignore_unknown_fields=True) def list( self, request: compute.ListRegionUrlMapsRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.UrlMapList: r"""Call the list method over HTTP. Args: request (~.compute.ListRegionUrlMapsRequest): The request object. A request message for RegionUrlMaps.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.UrlMapList: Contains a list of UrlMap resources. """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/urlMaps".format( host=self._host, project=request.project, region=request.region, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.ListRegionUrlMapsRequest.filter in request: query_params["filter"] = request.filter if compute.ListRegionUrlMapsRequest.max_results in request: query_params["maxResults"] = request.max_results if compute.ListRegionUrlMapsRequest.order_by in request: query_params["orderBy"] = request.order_by if compute.ListRegionUrlMapsRequest.page_token in request: query_params["pageToken"] = request.page_token if compute.ListRegionUrlMapsRequest.return_partial_success in request: query_params["returnPartialSuccess"] = request.return_partial_success # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() # Return the response return compute.UrlMapList.from_json( response.content, ignore_unknown_fields=True ) def patch( self, request: compute.PatchRegionUrlMapRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the patch method over HTTP. Args: request (~.compute.PatchRegionUrlMapRequest): The request object. A request message for RegionUrlMaps.Patch. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.UrlMap.to_json( request.url_map_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/urlMaps/{url_map}".format( host=self._host, project=request.project, region=request.region, url_map=request.url_map, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.PatchRegionUrlMapRequest.request_id in request: query_params["requestId"] = request.request_id # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request response = self._session.patch(url, data=body,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() # Return the response return compute.Operation.from_json(response.content, ignore_unknown_fields=True) def update( self, request: compute.UpdateRegionUrlMapRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the update method over HTTP. Args: request (~.compute.UpdateRegionUrlMapRequest): The request object. A request message for RegionUrlMaps.Update. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.UrlMap.to_json( request.url_map_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/urlMaps/{url_map}".format( host=self._host, project=request.project, region=request.region, url_map=request.url_map, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.UpdateRegionUrlMapRequest.request_id in request: query_params["requestId"] = request.request_id # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request response = self._session.put(url, data=body,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() # Return the response return compute.Operation.from_json(response.content, ignore_unknown_fields=True) def validate( self, request: compute.ValidateRegionUrlMapRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.UrlMapsValidateResponse: r"""Call the validate method over HTTP. Args: request (~.compute.ValidateRegionUrlMapRequest): The request object. A request message for RegionUrlMaps.Validate. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.UrlMapsValidateResponse: """ # Jsonify the request body body = compute.RegionUrlMapsValidateRequest.to_json( request.region_url_maps_validate_request_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/urlMaps/{url_map}/validate".format( host=self._host, project=request.project, region=request.region, url_map=request.url_map, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here # discards default values # TODO(yon-mg): add test for proper url encoded strings query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request response = self._session.post(url, data=body,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() # Return the response return compute.UrlMapsValidateResponse.from_json( response.content, ignore_unknown_fields=True )
class Comms(object): def __init__(self, settings): if isinstance(settings, str): try: settings = json.loads(settings) except JSONDecodeError: pass if not isinstance(settings, dict): raise Exception('Could not parse settings into JSON-dict') try: credentials = service_account.Credentials.from_service_account_info( settings, scopes=[ 'https://www.googleapis.com/auth/wallet_object.issuer' ], ) self.__session = AuthorizedSession(credentials) self.__signer = crypt.RSASigner.from_service_account_info(settings) self.client_email = settings.get('client_email') except ValueError: raise Exception( 'Could not setup Comms. Did you properly setup the necessary credentials?' ) def get_item(self, item_type, item_name): if not (hasattr(ClassType, str(item_type)) or hasattr(ObjectType, str(item_type))): raise Exception('Invalid Class or Object Type') result = self.__session.get( 'https://walletobjects.googleapis.com/walletobjects/v1/%s/%s' % (item_type, item_name)) if result.status_code == 200: return result.json() elif result.status_code == 404: return False else: return None def list_items(self, item_type, issuer_id=None, class_id=None): if not (hasattr(ClassType, str(item_type)) or hasattr(ObjectType, str(item_type))): raise Exception("Invalid Class or Object Type") if not (bool(issuer_id) ^ bool(class_id)): raise Exception("issuer_id or class_id must be provided") if issuer_id: key = 'issuerId' val = issuer_id elif class_id: key = 'classId' val = class_id else: raise Exception() result = self.__session.get( 'https://walletobjects.googleapis.com/walletobjects/v1/%s?%s=%s' % (item_type, key, val)) if result.status_code == 200: return result.json() elif result.status_code == 404: return False else: return None def put_item(self, item_type, item_name, payload): if not (hasattr(ClassType, str(item_type)) or hasattr(ObjectType, str(item_type))): raise Exception('Invalid Class or Object Type') item = self.get_item(item_type, item_name) if item is None: raise Exception('API Error') elif not item: result = self.__session.post( 'https://walletobjects.googleapis.com/walletobjects/v1/%s?strict=true' % item_type, json=json.loads(str(payload))) else: result = self.__session.put( 'https://walletobjects.googleapis.com/walletobjects/v1/%s/%s?strict=true' % (item_type, item_name), json=json.loads(str(payload))) result.raise_for_status() return result.json() def sign_jwt(self, payload): payload = json.loads(str(payload)) encoded = jwt.encode(self.__signer, payload) if not encoded: return False return encoded.decode("utf-8")
class RegionHealthChecksRestTransport(RegionHealthChecksTransport): """REST backend transport for RegionHealthChecks. The RegionHealthChecks 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 """ 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, ) -> 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're developing your own client library. """ # 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) def delete( self, request: compute.DeleteRegionHealthCheckRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the delete method over HTTP. Args: request (~.compute.DeleteRegionHealthCheckRequest): The request object. A request message for RegionHealthChecks.Delete. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/healthChecks/{health_check}".format( host=self._host, project=request.project, region=request.region, health_check=request.health_check, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.DeleteRegionHealthCheckRequest.request_id in request: query_params["requestId"] = request.request_id # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.delete(url, headers=headers, 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) def get( self, request: compute.GetRegionHealthCheckRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.HealthCheck: r"""Call the get method over HTTP. Args: request (~.compute.GetRegionHealthCheckRequest): The request object. A request message for RegionHealthChecks.Get. See the method description for details. 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/{$api_version}/healthChecks>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/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``). Network load balancers must use legacy HTTP health checks (httpHealthChecks). For more information, see Health checks overview. """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/healthChecks/{health_check}".format( host=self._host, project=request.project, region=request.region, health_check=request.health_check, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.get(url, headers=headers, 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 ) def insert( self, request: compute.InsertRegionHealthCheckRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the insert method over HTTP. Args: request (~.compute.InsertRegionHealthCheckRequest): The request object. A request message for RegionHealthChecks.Insert. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.HealthCheck.to_json( request.health_check_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/healthChecks".format( host=self._host, project=request.project, region=request.region, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.InsertRegionHealthCheckRequest.request_id in request: query_params["requestId"] = request.request_id # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.post( url, headers=headers, 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) def list( self, request: compute.ListRegionHealthChecksRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.HealthCheckList: r"""Call the list method over HTTP. Args: request (~.compute.ListRegionHealthChecksRequest): The request object. A request message for RegionHealthChecks.List. See the method description for details. 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. """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/healthChecks".format( host=self._host, project=request.project, region=request.region, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.ListRegionHealthChecksRequest.filter in request: query_params["filter"] = request.filter if compute.ListRegionHealthChecksRequest.max_results in request: query_params["maxResults"] = request.max_results if compute.ListRegionHealthChecksRequest.order_by in request: query_params["orderBy"] = request.order_by if compute.ListRegionHealthChecksRequest.page_token in request: query_params["pageToken"] = request.page_token if compute.ListRegionHealthChecksRequest.return_partial_success in request: query_params["returnPartialSuccess"] = request.return_partial_success # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.get(url, headers=headers, 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 ) def patch( self, request: compute.PatchRegionHealthCheckRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the patch method over HTTP. Args: request (~.compute.PatchRegionHealthCheckRequest): The request object. A request message for RegionHealthChecks.Patch. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.HealthCheck.to_json( request.health_check_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/healthChecks/{health_check}".format( host=self._host, project=request.project, region=request.region, health_check=request.health_check, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.PatchRegionHealthCheckRequest.request_id in request: query_params["requestId"] = request.request_id # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.patch( url, headers=headers, 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) def update( self, request: compute.UpdateRegionHealthCheckRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the update method over HTTP. Args: request (~.compute.UpdateRegionHealthCheckRequest): The request object. A request message for RegionHealthChecks.Update. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.HealthCheck.to_json( request.health_check_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/regions/{region}/healthChecks/{health_check}".format( host=self._host, project=request.project, region=request.region, health_check=request.health_check, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.UpdateRegionHealthCheckRequest.request_id in request: query_params["requestId"] = request.request_id # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.put( url, headers=headers, 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 BackendServicesRestTransport(BackendServicesTransport): """REST backend transport for BackendServices. The BackendServices 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 """ 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, ) -> 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're developing your own client library. """ # 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) def add_signed_url_key( self, request: compute.AddSignedUrlKeyBackendServiceRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the add signed url key method over HTTP. Args: request (~.compute.AddSignedUrlKeyBackendServiceRequest): The request object. A request message for BackendServices.AddSignedUrlKey. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.SignedUrlKey.to_json( request.signed_url_key_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/global/backendServices/{backend_service}/addSignedUrlKey".format( host=self._host, project=request.project, backend_service=request.backend_service, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.AddSignedUrlKeyBackendServiceRequest.request_id in request: query_params["requestId"] = request.request_id # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.post( url, headers=headers, 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) def aggregated_list( self, request: compute.AggregatedListBackendServicesRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.BackendServiceAggregatedList: r"""Call the aggregated list method over HTTP. Args: request (~.compute.AggregatedListBackendServicesRequest): The request object. A request message for BackendServices.AggregatedList. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.BackendServiceAggregatedList: Contains a list of BackendServicesScopedList. """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/aggregated/backendServices".format( host=self._host, project=request.project, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.AggregatedListBackendServicesRequest.filter in request: query_params["filter"] = request.filter if compute.AggregatedListBackendServicesRequest.include_all_scopes in request: query_params["includeAllScopes"] = request.include_all_scopes if compute.AggregatedListBackendServicesRequest.max_results in request: query_params["maxResults"] = request.max_results if compute.AggregatedListBackendServicesRequest.order_by in request: query_params["orderBy"] = request.order_by if compute.AggregatedListBackendServicesRequest.page_token in request: query_params["pageToken"] = request.page_token if (compute.AggregatedListBackendServicesRequest.return_partial_success in request): query_params[ "returnPartialSuccess"] = request.return_partial_success # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.get( url, headers=headers, 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.BackendServiceAggregatedList.from_json( response.content, ignore_unknown_fields=True) def delete( self, request: compute.DeleteBackendServiceRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the delete method over HTTP. Args: request (~.compute.DeleteBackendServiceRequest): The request object. A request message for BackendServices.Delete. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/global/backendServices/{backend_service}".format( host=self._host, project=request.project, backend_service=request.backend_service, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.DeleteBackendServiceRequest.request_id in request: query_params["requestId"] = request.request_id # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.delete( url, headers=headers, 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) def delete_signed_url_key( self, request: compute.DeleteSignedUrlKeyBackendServiceRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the delete signed url key method over HTTP. Args: request (~.compute.DeleteSignedUrlKeyBackendServiceRequest): The request object. A request message for BackendServices.DeleteSignedUrlKey. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/global/backendServices/{backend_service}/deleteSignedUrlKey".format( host=self._host, project=request.project, backend_service=request.backend_service, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} query_params["keyName"] = request.key_name if compute.DeleteSignedUrlKeyBackendServiceRequest.request_id in request: query_params["requestId"] = request.request_id # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.post( url, headers=headers, 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) def get( self, request: compute.GetBackendServiceRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.BackendService: r"""Call the get method over HTTP. Args: request (~.compute.GetBackendServiceRequest): The request object. A request message for BackendServices.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.BackendService: Represents a Backend Service resource. A backend service defines how Google Cloud load balancers distribute traffic. The backend service configuration contains a set of values, such as the protocol used to connect to backends, various distribution and session settings, health checks, and timeouts. These settings provide fine-grained control over how your load balancer behaves. Most of the settings have default values that allow for easy configuration if you need to get started quickly. Backend services in Google Compute Engine can be either regionally or globally scoped. - `Global </compute/docs/reference/rest/{$api_version}/backendServices>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionBackendServices>`__ For more information, see Backend Services. (== resource_for {$api_version}.backendService ==) """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/global/backendServices/{backend_service}".format( host=self._host, project=request.project, backend_service=request.backend_service, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.get( url, headers=headers, 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.BackendService.from_json(response.content, ignore_unknown_fields=True) def get_health( self, request: compute.GetHealthBackendServiceRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.BackendServiceGroupHealth: r"""Call the get health method over HTTP. Args: request (~.compute.GetHealthBackendServiceRequest): The request object. A request message for BackendServices.GetHealth. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.BackendServiceGroupHealth: """ # Jsonify the request body body = compute.ResourceGroupReference.to_json( request.resource_group_reference_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/global/backendServices/{backend_service}/getHealth".format( host=self._host, project=request.project, backend_service=request.backend_service, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.post( url, headers=headers, 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.BackendServiceGroupHealth.from_json( response.content, ignore_unknown_fields=True) def insert( self, request: compute.InsertBackendServiceRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the insert method over HTTP. Args: request (~.compute.InsertBackendServiceRequest): The request object. A request message for BackendServices.Insert. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.BackendService.to_json( request.backend_service_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/global/backendServices".format( host=self._host, project=request.project, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.InsertBackendServiceRequest.request_id in request: query_params["requestId"] = request.request_id # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.post( url, headers=headers, 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) def list( self, request: compute.ListBackendServicesRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.BackendServiceList: r"""Call the list method over HTTP. Args: request (~.compute.ListBackendServicesRequest): The request object. A request message for BackendServices.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.BackendServiceList: Contains a list of BackendService resources. """ # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/global/backendServices".format( host=self._host, project=request.project, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.ListBackendServicesRequest.filter in request: query_params["filter"] = request.filter if compute.ListBackendServicesRequest.max_results in request: query_params["maxResults"] = request.max_results if compute.ListBackendServicesRequest.order_by in request: query_params["orderBy"] = request.order_by if compute.ListBackendServicesRequest.page_token in request: query_params["pageToken"] = request.page_token if compute.ListBackendServicesRequest.return_partial_success in request: query_params[ "returnPartialSuccess"] = request.return_partial_success # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.get( url, headers=headers, 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.BackendServiceList.from_json(response.content, ignore_unknown_fields=True) def patch( self, request: compute.PatchBackendServiceRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the patch method over HTTP. Args: request (~.compute.PatchBackendServiceRequest): The request object. A request message for BackendServices.Patch. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.BackendService.to_json( request.backend_service_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/global/backendServices/{backend_service}".format( host=self._host, project=request.project, backend_service=request.backend_service, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.PatchBackendServiceRequest.request_id in request: query_params["requestId"] = request.request_id # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.patch( url, headers=headers, 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) def set_security_policy( self, request: compute.SetSecurityPolicyBackendServiceRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the set security policy method over HTTP. Args: request (~.compute.SetSecurityPolicyBackendServiceRequest): The request object. A request message for BackendServices.SetSecurityPolicy. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.SecurityPolicyReference.to_json( request.security_policy_reference_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/global/backendServices/{backend_service}/setSecurityPolicy".format( host=self._host, project=request.project, backend_service=request.backend_service, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.SetSecurityPolicyBackendServiceRequest.request_id in request: query_params["requestId"] = request.request_id # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.post( url, headers=headers, 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) def update( self, request: compute.UpdateBackendServiceRequest, *, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the update method over HTTP. Args: request (~.compute.UpdateBackendServiceRequest): The request object. A request message for BackendServices.Update. See the method description for details. 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/{$api_version}/globalOperations>`__ \* `Regional </compute/docs/reference/rest/{$api_version}/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/{$api_version}/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. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Jsonify the request body body = compute.BackendService.to_json( request.backend_service_resource, including_default_value_fields=False, use_integers_for_enums=False, ) # TODO(yon-mg): need to handle grpc transcoding and parse url correctly # current impl assumes basic case of grpc transcoding url = "https://{host}/compute/v1/projects/{project}/global/backendServices/{backend_service}".format( host=self._host, project=request.project, backend_service=request.backend_service, ) # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE query_params = {} if compute.UpdateBackendServiceRequest.request_id in request: query_params["requestId"] = request.request_id # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = self._session.put( url, headers=headers, 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)
# format the json we're sending it data = {} details = {} details['weight'] = arguments['<weight>'] details['message'] = arguments['<message>'] details['bmi'] = bmi details['bmr'] = bmr details['tdee'] = tdee data[key] = details; json_data = json.dumps(data); # Define the required scopes scopes = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/firebase.database" ] # Authenticate a credential with the service account credentials = service_account.Credentials.from_service_account_file( "./secrets/metrac-io-firebase-adminsdk-3o30f-0ea8c2fa69.json", scopes=scopes) # Use the credentials object to authenticate a Requests session. authed_session = AuthorizedSession(credentials) response = authed_session.put(url+ext, json_data) print response response = authed_session.get(url+ext) print response.content
def upload(): #read chunk size - dropzone also provides the current chunk size in request. Fallback incase someone uses http client with wrong value file_chunk = request.files.get('form-file') file_chunk.seek(0, os.SEEK_END) file_length = file_chunk.tell() #return seek pointer to zero file_chunk.seek(0) dzuuid = request.form.get('dzuuid') if not file_chunk or not dzuuid: return "Error 1", 400 #get the mime type for the file file_ext = file_chunk.filename.split(".")[-1] if file_ext in video_mime_type_map: full_mimetype = video_mime_type_map[file_ext] else: return "Error 2", 400 if dzuuid in resumable_upload_object_dict: # just stream the next chunk sess_uri = resumable_upload_object_dict[dzuuid]["sess_uri"] last_byte = resumable_upload_object_dict[dzuuid]["last_chunk"] tot_size = resumable_upload_object_dict[dzuuid]["tot_size"] authed_session = AuthorizedSession(credentials) cn_length = file_length headers = { "Content-Length": str(cn_length), "Content-Range": f"bytes {int(last_byte)+1}-{int(last_byte)+int(cn_length)}/{tot_size}", "Content-Type": full_mimetype } resp = authed_session.put(sess_uri, data=file_chunk.read(), headers=headers) if resp.status_code in ( 200, 201, ): del resumable_upload_object_dict[dzuuid] #if file was smaller than chunksize, delete the uploaded files #this is a fallback to avoid filling my drive. Delete loop below in your setup blobs = storage_bucket.list_blobs() for blob in blobs: try: print("Deleting: ", blob.public_url) except: pass try: blob.delete() except: pass return 'ok' elif resp.status_code == 308: #update last chunk and return ok last_byte_header = resp.headers.get("Range") last_byte = last_byte_header.split("=")[1].split("-")[1] resumable_upload_object_dict[dzuuid]["last_chunk"] = last_byte return 'ok' else: return "Error 3", 400 else: # save to datastore since its first instance, create resumable upload object and start streaming uuid_filename = uuid4().hex + "." + file_ext sess_uri = start_resumable_upload_session(uuid_filename, full_mimetype) authed_session = AuthorizedSession(credentials) cn_length = file_length tot_size = int(request.form.get("dztotalfilesize")) adjusted_tot_size = tot_size - 1 adjusted_cn_length = cn_length - 1 headers = { "Content-Length": str(cn_length), "Content-Range": f"bytes 0-{adjusted_cn_length}/{tot_size}", "Content-Type": full_mimetype } resp = authed_session.put(sess_uri, data=file_chunk.read(), headers=headers) if resp.status_code in ( 308, 200, 201, ): try: last_byte_header = resp.headers.get("Range") last_byte = last_byte_header.split("=")[1].split("-")[1] except: last_byte = 0 #set to zero, this exception is when chunk is smaller than chunk size. resumable_upload_object_dict[dzuuid] = { "sess_uri": sess_uri, "last_chunk": last_byte, "tot_size": tot_size } #pop from dict if response is code 200 or 201 . These status codes are returned when upload has completed if resp.status_code in ( 200, 201, ): print("Deleting resumable upload uri :: ") del resumable_upload_object_dict[dzuuid] #if file was smaller than chunksize, delete the uploaded files #this is a fallback to avoid filling my drive. Delete loop below in your setup blobs = storage_bucket.list_blobs() for blob in blobs: try: print("Deleting: ", blob.public_url) except: pass try: blob.delete() except: pass # extract opptional form fields == these can be saved to sql db or even to datastore. Liberty is yours name = str(request.form.get("form-name", "")) email = str(request.form.get("form-email", "")) country = str(request.form.get("form-country", "")) msg = str(request.form.get("form-message", "")) file_url = f"https://storage.googleapis.com/test-bucket-alpha-1/{uuid_filename}" return 'ok' else: return "Error 4", 400