text
stringlengths
81
112k
Set a value into a document for a field_path def set_field_value(document_data, field_path, value): """Set a value into a document for a field_path""" current = document_data for element in field_path.parts[:-1]: current = current.setdefault(element, {}) if value is _EmptyDict: value = {} current[field_path.parts[-1]] = value
Make ``Write`` protobufs for ``create()`` methods. Args: document_path (str): A fully-qualified document path. document_data (dict): Property names and values to use for creating a document. Returns: List[google.cloud.firestore_v1beta1.types.Write]: One or two ``Write`` protobuf instances for ``create()``. def pbs_for_create(document_path, document_data): """Make ``Write`` protobufs for ``create()`` methods. Args: document_path (str): A fully-qualified document path. document_data (dict): Property names and values to use for creating a document. Returns: List[google.cloud.firestore_v1beta1.types.Write]: One or two ``Write`` protobuf instances for ``create()``. """ extractor = DocumentExtractor(document_data) if extractor.deleted_fields: raise ValueError("Cannot apply DELETE_FIELD in a create request.") write_pbs = [] # Conformance tests require skipping the 'update_pb' if the document # contains only transforms. if extractor.empty_document or extractor.set_fields: write_pbs.append(extractor.get_update_pb(document_path, exists=False)) if extractor.has_transforms: exists = None if write_pbs else False transform_pb = extractor.get_transform_pb(document_path, exists) write_pbs.append(transform_pb) return write_pbs
Make ``Write`` protobufs for ``set()`` methods. Args: document_path (str): A fully-qualified document path. document_data (dict): Property names and values to use for replacing a document. Returns: List[google.cloud.firestore_v1beta1.types.Write]: One or two ``Write`` protobuf instances for ``set()``. def pbs_for_set_no_merge(document_path, document_data): """Make ``Write`` protobufs for ``set()`` methods. Args: document_path (str): A fully-qualified document path. document_data (dict): Property names and values to use for replacing a document. Returns: List[google.cloud.firestore_v1beta1.types.Write]: One or two ``Write`` protobuf instances for ``set()``. """ extractor = DocumentExtractor(document_data) if extractor.deleted_fields: raise ValueError( "Cannot apply DELETE_FIELD in a set request without " "specifying 'merge=True' or 'merge=[field_paths]'." ) # Conformance tests require send the 'update_pb' even if the document # contains only transforms. write_pbs = [extractor.get_update_pb(document_path)] if extractor.has_transforms: transform_pb = extractor.get_transform_pb(document_path) write_pbs.append(transform_pb) return write_pbs
Make ``Write`` protobufs for ``set()`` methods. Args: document_path (str): A fully-qualified document path. document_data (dict): Property names and values to use for replacing a document. merge (Optional[bool] or Optional[List<apispec>]): If True, merge all fields; else, merge only the named fields. Returns: List[google.cloud.firestore_v1beta1.types.Write]: One or two ``Write`` protobuf instances for ``set()``. def pbs_for_set_with_merge(document_path, document_data, merge): """Make ``Write`` protobufs for ``set()`` methods. Args: document_path (str): A fully-qualified document path. document_data (dict): Property names and values to use for replacing a document. merge (Optional[bool] or Optional[List<apispec>]): If True, merge all fields; else, merge only the named fields. Returns: List[google.cloud.firestore_v1beta1.types.Write]: One or two ``Write`` protobuf instances for ``set()``. """ extractor = DocumentExtractorForMerge(document_data) extractor.apply_merge(merge) merge_empty = not document_data write_pbs = [] if extractor.has_updates or merge_empty: write_pbs.append( extractor.get_update_pb(document_path, allow_empty_mask=merge_empty) ) if extractor.transform_paths: transform_pb = extractor.get_transform_pb(document_path) write_pbs.append(transform_pb) return write_pbs
Make ``Write`` protobufs for ``update()`` methods. Args: document_path (str): A fully-qualified document path. field_updates (dict): Field names or paths to update and values to update with. option (optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. Returns: List[google.cloud.firestore_v1beta1.types.Write]: One or two ``Write`` protobuf instances for ``update()``. def pbs_for_update(document_path, field_updates, option): """Make ``Write`` protobufs for ``update()`` methods. Args: document_path (str): A fully-qualified document path. field_updates (dict): Field names or paths to update and values to update with. option (optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. Returns: List[google.cloud.firestore_v1beta1.types.Write]: One or two ``Write`` protobuf instances for ``update()``. """ extractor = DocumentExtractorForUpdate(field_updates) if extractor.empty_document: raise ValueError("Cannot update with an empty document.") if option is None: # Default is to use ``exists=True``. option = ExistsOption(exists=True) write_pbs = [] if extractor.field_paths or extractor.deleted_fields: update_pb = extractor.get_update_pb(document_path) option.modify_write(update_pb) write_pbs.append(update_pb) if extractor.has_transforms: transform_pb = extractor.get_transform_pb(document_path) if not write_pbs: # NOTE: set the write option on the ``transform_pb`` only if there # is no ``update_pb`` option.modify_write(transform_pb) write_pbs.append(transform_pb) return write_pbs
Make a ``Write`` protobuf for ``delete()`` methods. Args: document_path (str): A fully-qualified document path. option (optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. Returns: google.cloud.firestore_v1beta1.types.Write: A ``Write`` protobuf instance for the ``delete()``. def pb_for_delete(document_path, option): """Make a ``Write`` protobuf for ``delete()`` methods. Args: document_path (str): A fully-qualified document path. option (optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. Returns: google.cloud.firestore_v1beta1.types.Write: A ``Write`` protobuf instance for the ``delete()``. """ write_pb = write_pb2.Write(delete=document_path) if option is not None: option.modify_write(write_pb) return write_pb
Get the transaction ID from a ``Transaction`` object. Args: transaction (Optional[~.firestore_v1beta1.transaction.\ Transaction]): An existing transaction that this query will run in. read_operation (Optional[bool]): Indicates if the transaction ID will be used in a read operation. Defaults to :data:`True`. Returns: Optional[bytes]: The ID of the transaction, or :data:`None` if the ``transaction`` is :data:`None`. Raises: ValueError: If the ``transaction`` is not in progress (only if ``transaction`` is not :data:`None`). ReadAfterWriteError: If the ``transaction`` has writes stored on it and ``read_operation`` is :data:`True`. def get_transaction_id(transaction, read_operation=True): """Get the transaction ID from a ``Transaction`` object. Args: transaction (Optional[~.firestore_v1beta1.transaction.\ Transaction]): An existing transaction that this query will run in. read_operation (Optional[bool]): Indicates if the transaction ID will be used in a read operation. Defaults to :data:`True`. Returns: Optional[bytes]: The ID of the transaction, or :data:`None` if the ``transaction`` is :data:`None`. Raises: ValueError: If the ``transaction`` is not in progress (only if ``transaction`` is not :data:`None`). ReadAfterWriteError: If the ``transaction`` has writes stored on it and ``read_operation`` is :data:`True`. """ if transaction is None: return None else: if not transaction.in_progress: raise ValueError(INACTIVE_TXN) if read_operation and len(transaction._write_pbs) > 0: raise ReadAfterWriteError(READ_AFTER_WRITE_ERROR) return transaction.id
Modify a ``Write`` protobuf based on the state of this write option. The ``last_update_time`` is added to ``write_pb`` as an "update time" precondition. When set, the target document must exist and have been last updated at that time. Args: write_pb (google.cloud.firestore_v1beta1.types.Write): A ``Write`` protobuf instance to be modified with a precondition determined by the state of this option. unused_kwargs (Dict[str, Any]): Keyword arguments accepted by other subclasses that are unused here. def modify_write(self, write_pb, **unused_kwargs): """Modify a ``Write`` protobuf based on the state of this write option. The ``last_update_time`` is added to ``write_pb`` as an "update time" precondition. When set, the target document must exist and have been last updated at that time. Args: write_pb (google.cloud.firestore_v1beta1.types.Write): A ``Write`` protobuf instance to be modified with a precondition determined by the state of this option. unused_kwargs (Dict[str, Any]): Keyword arguments accepted by other subclasses that are unused here. """ current_doc = types.Precondition(update_time=self._last_update_time) write_pb.current_document.CopyFrom(current_doc)
Modify a ``Write`` protobuf based on the state of this write option. If: * ``exists=True``, adds a precondition that requires existence * ``exists=False``, adds a precondition that requires non-existence Args: write_pb (google.cloud.firestore_v1beta1.types.Write): A ``Write`` protobuf instance to be modified with a precondition determined by the state of this option. unused_kwargs (Dict[str, Any]): Keyword arguments accepted by other subclasses that are unused here. def modify_write(self, write_pb, **unused_kwargs): """Modify a ``Write`` protobuf based on the state of this write option. If: * ``exists=True``, adds a precondition that requires existence * ``exists=False``, adds a precondition that requires non-existence Args: write_pb (google.cloud.firestore_v1beta1.types.Write): A ``Write`` protobuf instance to be modified with a precondition determined by the state of this option. unused_kwargs (Dict[str, Any]): Keyword arguments accepted by other subclasses that are unused here. """ current_doc = types.Precondition(exists=self._exists) write_pb.current_document.CopyFrom(current_doc)
Return a fully-qualified uptime_check_config string. def uptime_check_config_path(cls, project, uptime_check_config): """Return a fully-qualified uptime_check_config string.""" return google.api_core.path_template.expand( "projects/{project}/uptimeCheckConfigs/{uptime_check_config}", project=project, uptime_check_config=uptime_check_config, )
Creates a new uptime check configuration. Example: >>> from google.cloud import monitoring_v3 >>> >>> client = monitoring_v3.UptimeCheckServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `uptime_check_config`: >>> uptime_check_config = {} >>> >>> response = client.create_uptime_check_config(parent, uptime_check_config) Args: parent (str): The project in which to create the uptime check. The format is ``projects/[PROJECT_ID]``. uptime_check_config (Union[dict, ~google.cloud.monitoring_v3.types.UptimeCheckConfig]): The new uptime check configuration. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.monitoring_v3.types.UptimeCheckConfig` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.monitoring_v3.types.UptimeCheckConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def create_uptime_check_config( self, parent, uptime_check_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new uptime check configuration. Example: >>> from google.cloud import monitoring_v3 >>> >>> client = monitoring_v3.UptimeCheckServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `uptime_check_config`: >>> uptime_check_config = {} >>> >>> response = client.create_uptime_check_config(parent, uptime_check_config) Args: parent (str): The project in which to create the uptime check. The format is ``projects/[PROJECT_ID]``. uptime_check_config (Union[dict, ~google.cloud.monitoring_v3.types.UptimeCheckConfig]): The new uptime check configuration. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.monitoring_v3.types.UptimeCheckConfig` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.monitoring_v3.types.UptimeCheckConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ if metadata is None: metadata = [] metadata = list(metadata) # Wrap the transport method to add retry and timeout logic. if "create_uptime_check_config" not in self._inner_api_calls: self._inner_api_calls[ "create_uptime_check_config" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_uptime_check_config, default_retry=self._method_configs["CreateUptimeCheckConfig"].retry, default_timeout=self._method_configs["CreateUptimeCheckConfig"].timeout, client_info=self._client_info, ) request = uptime_service_pb2.CreateUptimeCheckConfigRequest( parent=parent, uptime_check_config=uptime_check_config ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_uptime_check_config"]( request, retry=retry, timeout=timeout, metadata=metadata )
Performs asynchronous video annotation. Progress and results can be retrieved through the ``google.longrunning.Operations`` interface. ``Operation.metadata`` contains ``AnnotateVideoProgress`` (progress). ``Operation.response`` contains ``AnnotateVideoResponse`` (results). Example: >>> from google.cloud import videointelligence_v1beta2 >>> from google.cloud.videointelligence_v1beta2 import enums >>> >>> client = videointelligence_v1beta2.VideoIntelligenceServiceClient() >>> >>> input_uri = 'gs://demomaker/cat.mp4' >>> features_element = enums.Feature.LABEL_DETECTION >>> features = [features_element] >>> >>> response = client.annotate_video(input_uri=input_uri, features=features) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: input_uri (str): Input video location. Currently, only `Google Cloud Storage <https://cloud.google.com/storage/>`__ URIs are supported, which must be specified in the following format: ``gs://bucket-id/object-id`` (other URI formats return ``google.rpc.Code.INVALID_ARGUMENT``). For more information, see `Request URIs <https://cloud.google.com/storage/docs/reference-uris>`__. A video URI may include wildcards in ``object-id``, and thus identify multiple videos. Supported wildcards: '\*' to match 0 or more characters; '?' to match 1 character. If unset, the input video should be embedded in the request as ``input_content``. If set, ``input_content`` should be unset. input_content (bytes): The video data bytes. If unset, the input video(s) should be specified via ``input_uri``. If set, ``input_uri`` should be unset. features (list[~google.cloud.videointelligence_v1beta2.types.Feature]): Requested video annotation features. video_context (Union[dict, ~google.cloud.videointelligence_v1beta2.types.VideoContext]): Additional video context and/or feature-specific parameters. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.videointelligence_v1beta2.types.VideoContext` output_uri (str): Optional location where the output (in JSON format) should be stored. Currently, only `Google Cloud Storage <https://cloud.google.com/storage/>`__ URIs are supported, which must be specified in the following format: ``gs://bucket-id/object-id`` (other URI formats return ``google.rpc.Code.INVALID_ARGUMENT``). For more information, see `Request URIs <https://cloud.google.com/storage/docs/reference-uris>`__. location_id (str): Optional cloud region where annotation should take place. Supported cloud regions: ``us-east1``, ``us-west1``, ``europe-west1``, ``asia-east1``. If no region is specified, a region will be determined based on video file location. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.videointelligence_v1beta2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def annotate_video( self, input_uri=None, input_content=None, features=None, video_context=None, output_uri=None, location_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Performs asynchronous video annotation. Progress and results can be retrieved through the ``google.longrunning.Operations`` interface. ``Operation.metadata`` contains ``AnnotateVideoProgress`` (progress). ``Operation.response`` contains ``AnnotateVideoResponse`` (results). Example: >>> from google.cloud import videointelligence_v1beta2 >>> from google.cloud.videointelligence_v1beta2 import enums >>> >>> client = videointelligence_v1beta2.VideoIntelligenceServiceClient() >>> >>> input_uri = 'gs://demomaker/cat.mp4' >>> features_element = enums.Feature.LABEL_DETECTION >>> features = [features_element] >>> >>> response = client.annotate_video(input_uri=input_uri, features=features) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: input_uri (str): Input video location. Currently, only `Google Cloud Storage <https://cloud.google.com/storage/>`__ URIs are supported, which must be specified in the following format: ``gs://bucket-id/object-id`` (other URI formats return ``google.rpc.Code.INVALID_ARGUMENT``). For more information, see `Request URIs <https://cloud.google.com/storage/docs/reference-uris>`__. A video URI may include wildcards in ``object-id``, and thus identify multiple videos. Supported wildcards: '\*' to match 0 or more characters; '?' to match 1 character. If unset, the input video should be embedded in the request as ``input_content``. If set, ``input_content`` should be unset. input_content (bytes): The video data bytes. If unset, the input video(s) should be specified via ``input_uri``. If set, ``input_uri`` should be unset. features (list[~google.cloud.videointelligence_v1beta2.types.Feature]): Requested video annotation features. video_context (Union[dict, ~google.cloud.videointelligence_v1beta2.types.VideoContext]): Additional video context and/or feature-specific parameters. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.videointelligence_v1beta2.types.VideoContext` output_uri (str): Optional location where the output (in JSON format) should be stored. Currently, only `Google Cloud Storage <https://cloud.google.com/storage/>`__ URIs are supported, which must be specified in the following format: ``gs://bucket-id/object-id`` (other URI formats return ``google.rpc.Code.INVALID_ARGUMENT``). For more information, see `Request URIs <https://cloud.google.com/storage/docs/reference-uris>`__. location_id (str): Optional cloud region where annotation should take place. Supported cloud regions: ``us-east1``, ``us-west1``, ``europe-west1``, ``asia-east1``. If no region is specified, a region will be determined based on video file location. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.videointelligence_v1beta2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "annotate_video" not in self._inner_api_calls: self._inner_api_calls[ "annotate_video" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.annotate_video, default_retry=self._method_configs["AnnotateVideo"].retry, default_timeout=self._method_configs["AnnotateVideo"].timeout, client_info=self._client_info, ) request = video_intelligence_pb2.AnnotateVideoRequest( input_uri=input_uri, input_content=input_content, features=features, video_context=video_context, output_uri=output_uri, location_id=location_id, ) operation = self._inner_api_calls["annotate_video"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, video_intelligence_pb2.AnnotateVideoResponse, metadata_type=video_intelligence_pb2.AnnotateVideoProgress, )
Legacy access to owner role. DEPRECATED: use ``policy["roles/owners"]`` instead. def owners(self): """Legacy access to owner role. DEPRECATED: use ``policy["roles/owners"]`` instead.""" result = set() for role in self._OWNER_ROLES: for member in self._bindings.get(role, ()): result.add(member) return frozenset(result)
Update owners. DEPRECATED: use ``policy["roles/owners"] = value`` instead. def owners(self, value): """Update owners. DEPRECATED: use ``policy["roles/owners"] = value`` instead.""" warnings.warn( _ASSIGNMENT_DEPRECATED_MSG.format("owners", OWNER_ROLE), DeprecationWarning ) self[OWNER_ROLE] = value
Legacy access to editor role. DEPRECATED: use ``policy["roles/editors"]`` instead. def editors(self): """Legacy access to editor role. DEPRECATED: use ``policy["roles/editors"]`` instead.""" result = set() for role in self._EDITOR_ROLES: for member in self._bindings.get(role, ()): result.add(member) return frozenset(result)
Update editors. DEPRECATED: use ``policy["roles/editors"] = value`` instead. def editors(self, value): """Update editors. DEPRECATED: use ``policy["roles/editors"] = value`` instead.""" warnings.warn( _ASSIGNMENT_DEPRECATED_MSG.format("editors", EDITOR_ROLE), DeprecationWarning, ) self[EDITOR_ROLE] = value
Legacy access to viewer role. DEPRECATED: use ``policy["roles/viewers"]`` instead def viewers(self): """Legacy access to viewer role. DEPRECATED: use ``policy["roles/viewers"]`` instead """ result = set() for role in self._VIEWER_ROLES: for member in self._bindings.get(role, ()): result.add(member) return frozenset(result)
Update viewers. DEPRECATED: use ``policy["roles/viewers"] = value`` instead. def viewers(self, value): """Update viewers. DEPRECATED: use ``policy["roles/viewers"] = value`` instead. """ warnings.warn( _ASSIGNMENT_DEPRECATED_MSG.format("viewers", VIEWER_ROLE), DeprecationWarning, ) self[VIEWER_ROLE] = value
Factory: create a policy from a JSON resource. Args: resource (dict): policy resource returned by ``getIamPolicy`` API. Returns: :class:`Policy`: the parsed policy def from_api_repr(cls, resource): """Factory: create a policy from a JSON resource. Args: resource (dict): policy resource returned by ``getIamPolicy`` API. Returns: :class:`Policy`: the parsed policy """ version = resource.get("version") etag = resource.get("etag") policy = cls(etag, version) for binding in resource.get("bindings", ()): role = binding["role"] members = sorted(binding["members"]) policy[role] = members return policy
Render a JSON policy resource. Returns: dict: a resource to be passed to the ``setIamPolicy`` API. def to_api_repr(self): """Render a JSON policy resource. Returns: dict: a resource to be passed to the ``setIamPolicy`` API. """ resource = {} if self.etag is not None: resource["etag"] = self.etag if self.version is not None: resource["version"] = self.version if self._bindings: bindings = resource["bindings"] = [] for role, members in sorted(self._bindings.items()): if members: bindings.append({"role": role, "members": sorted(set(members))}) if not bindings: del resource["bindings"] return resource
Get information about document references. Helper for :meth:`~.firestore_v1beta1.client.Client.get_all`. Args: references (List[.DocumentReference, ...]): Iterable of document references. Returns: Tuple[List[str, ...], Dict[str, .DocumentReference]]: A two-tuple of * fully-qualified documents paths for each reference in ``references`` * a mapping from the paths to the original reference. (If multiple ``references`` contains multiple references to the same document, that key will be overwritten in the result.) def _reference_info(references): """Get information about document references. Helper for :meth:`~.firestore_v1beta1.client.Client.get_all`. Args: references (List[.DocumentReference, ...]): Iterable of document references. Returns: Tuple[List[str, ...], Dict[str, .DocumentReference]]: A two-tuple of * fully-qualified documents paths for each reference in ``references`` * a mapping from the paths to the original reference. (If multiple ``references`` contains multiple references to the same document, that key will be overwritten in the result.) """ document_paths = [] reference_map = {} for reference in references: doc_path = reference._document_path document_paths.append(doc_path) reference_map[doc_path] = reference return document_paths, reference_map
Get a document reference from a dictionary. This just wraps a simple dictionary look-up with a helpful error that is specific to :meth:`~.firestore.client.Client.get_all`, the **public** caller of this function. Args: document_path (str): A fully-qualified document path. reference_map (Dict[str, .DocumentReference]): A mapping (produced by :func:`_reference_info`) of fully-qualified document paths to document references. Returns: .DocumentReference: The matching reference. Raises: ValueError: If ``document_path`` has not been encountered. def _get_reference(document_path, reference_map): """Get a document reference from a dictionary. This just wraps a simple dictionary look-up with a helpful error that is specific to :meth:`~.firestore.client.Client.get_all`, the **public** caller of this function. Args: document_path (str): A fully-qualified document path. reference_map (Dict[str, .DocumentReference]): A mapping (produced by :func:`_reference_info`) of fully-qualified document paths to document references. Returns: .DocumentReference: The matching reference. Raises: ValueError: If ``document_path`` has not been encountered. """ try: return reference_map[document_path] except KeyError: msg = _BAD_DOC_TEMPLATE.format(document_path) raise ValueError(msg)
Parse a `BatchGetDocumentsResponse` protobuf. Args: get_doc_response (~google.cloud.proto.firestore.v1beta1.\ firestore_pb2.BatchGetDocumentsResponse): A single response (from a stream) containing the "get" response for a document. reference_map (Dict[str, .DocumentReference]): A mapping (produced by :func:`_reference_info`) of fully-qualified document paths to document references. client (~.firestore_v1beta1.client.Client): A client that has a document factory. Returns: [.DocumentSnapshot]: The retrieved snapshot. Raises: ValueError: If the response has a ``result`` field (a oneof) other than ``found`` or ``missing``. def _parse_batch_get(get_doc_response, reference_map, client): """Parse a `BatchGetDocumentsResponse` protobuf. Args: get_doc_response (~google.cloud.proto.firestore.v1beta1.\ firestore_pb2.BatchGetDocumentsResponse): A single response (from a stream) containing the "get" response for a document. reference_map (Dict[str, .DocumentReference]): A mapping (produced by :func:`_reference_info`) of fully-qualified document paths to document references. client (~.firestore_v1beta1.client.Client): A client that has a document factory. Returns: [.DocumentSnapshot]: The retrieved snapshot. Raises: ValueError: If the response has a ``result`` field (a oneof) other than ``found`` or ``missing``. """ result_type = get_doc_response.WhichOneof("result") if result_type == "found": reference = _get_reference(get_doc_response.found.name, reference_map) data = _helpers.decode_dict(get_doc_response.found.fields, client) snapshot = DocumentSnapshot( reference, data, exists=True, read_time=get_doc_response.read_time, create_time=get_doc_response.found.create_time, update_time=get_doc_response.found.update_time, ) elif result_type == "missing": snapshot = DocumentSnapshot( None, None, exists=False, read_time=get_doc_response.read_time, create_time=None, update_time=None, ) else: raise ValueError( "`BatchGetDocumentsResponse.result` (a oneof) had a field other " "than `found` or `missing` set, or was unset" ) return snapshot
Lazy-loading getter GAPIC Firestore API. Returns: ~.gapic.firestore.v1beta1.firestore_client.FirestoreClient: The GAPIC client with the credentials of the current client. def _firestore_api(self): """Lazy-loading getter GAPIC Firestore API. Returns: ~.gapic.firestore.v1beta1.firestore_client.FirestoreClient: The GAPIC client with the credentials of the current client. """ if self._firestore_api_internal is None: self._firestore_api_internal = firestore_client.FirestoreClient( credentials=self._credentials ) return self._firestore_api_internal
The database string corresponding to this client's project. This value is lazy-loaded and cached. Will be of the form ``projects/{project_id}/databases/{database_id}`` but ``database_id == '(default)'`` for the time being. Returns: str: The fully-qualified database string for the current project. (The default database is also in this string.) def _database_string(self): """The database string corresponding to this client's project. This value is lazy-loaded and cached. Will be of the form ``projects/{project_id}/databases/{database_id}`` but ``database_id == '(default)'`` for the time being. Returns: str: The fully-qualified database string for the current project. (The default database is also in this string.) """ if self._database_string_internal is None: # NOTE: database_root_path() is a classmethod, so we don't use # self._firestore_api (it isn't necessary). db_str = firestore_client.FirestoreClient.database_root_path( self.project, self._database ) self._database_string_internal = db_str return self._database_string_internal
The RPC metadata for this client's associated database. Returns: Sequence[Tuple(str, str)]: RPC metadata with resource prefix for the database associated with this client. def _rpc_metadata(self): """The RPC metadata for this client's associated database. Returns: Sequence[Tuple(str, str)]: RPC metadata with resource prefix for the database associated with this client. """ if self._rpc_metadata_internal is None: self._rpc_metadata_internal = _helpers.metadata_with_prefix( self._database_string ) return self._rpc_metadata_internal
Get a reference to a collection. For a top-level collection: .. code-block:: python >>> client.collection('top') For a sub-collection: .. code-block:: python >>> client.collection('mydocs/doc/subcol') >>> # is the same as >>> client.collection('mydocs', 'doc', 'subcol') Sub-collections can be nested deeper in a similar fashion. Args: collection_path (Tuple[str, ...]): Can either be * A single ``/``-delimited path to a collection * A tuple of collection path segments Returns: ~.firestore_v1beta1.collection.CollectionReference: A reference to a collection in the Firestore database. def collection(self, *collection_path): """Get a reference to a collection. For a top-level collection: .. code-block:: python >>> client.collection('top') For a sub-collection: .. code-block:: python >>> client.collection('mydocs/doc/subcol') >>> # is the same as >>> client.collection('mydocs', 'doc', 'subcol') Sub-collections can be nested deeper in a similar fashion. Args: collection_path (Tuple[str, ...]): Can either be * A single ``/``-delimited path to a collection * A tuple of collection path segments Returns: ~.firestore_v1beta1.collection.CollectionReference: A reference to a collection in the Firestore database. """ if len(collection_path) == 1: path = collection_path[0].split(_helpers.DOCUMENT_PATH_DELIMITER) else: path = collection_path return CollectionReference(*path, client=self)
Get a reference to a document in a collection. For a top-level document: .. code-block:: python >>> client.document('collek/shun') >>> # is the same as >>> client.document('collek', 'shun') For a document in a sub-collection: .. code-block:: python >>> client.document('mydocs/doc/subcol/child') >>> # is the same as >>> client.document('mydocs', 'doc', 'subcol', 'child') Documents in sub-collections can be nested deeper in a similar fashion. Args: document_path (Tuple[str, ...]): Can either be * A single ``/``-delimited path to a document * A tuple of document path segments Returns: ~.firestore_v1beta1.document.DocumentReference: A reference to a document in a collection. def document(self, *document_path): """Get a reference to a document in a collection. For a top-level document: .. code-block:: python >>> client.document('collek/shun') >>> # is the same as >>> client.document('collek', 'shun') For a document in a sub-collection: .. code-block:: python >>> client.document('mydocs/doc/subcol/child') >>> # is the same as >>> client.document('mydocs', 'doc', 'subcol', 'child') Documents in sub-collections can be nested deeper in a similar fashion. Args: document_path (Tuple[str, ...]): Can either be * A single ``/``-delimited path to a document * A tuple of document path segments Returns: ~.firestore_v1beta1.document.DocumentReference: A reference to a document in a collection. """ if len(document_path) == 1: path = document_path[0].split(_helpers.DOCUMENT_PATH_DELIMITER) else: path = document_path return DocumentReference(*path, client=self)
Create a write option for write operations. Write operations include :meth:`~.DocumentReference.set`, :meth:`~.DocumentReference.update` and :meth:`~.DocumentReference.delete`. One of the following keyword arguments must be provided: * ``last_update_time`` (:class:`google.protobuf.timestamp_pb2.\ Timestamp`): A timestamp. When set, the target document must exist and have been last updated at that time. Protobuf ``update_time`` timestamps are typically returned from methods that perform write operations as part of a "write result" protobuf or directly. * ``exists`` (:class:`bool`): Indicates if the document being modified should already exist. Providing no argument would make the option have no effect (so it is not allowed). Providing multiple would be an apparent contradiction, since ``last_update_time`` assumes that the document **was** updated (it can't have been updated if it doesn't exist) and ``exists`` indicate that it is unknown if the document exists or not. Args: kwargs (Dict[str, Any]): The keyword arguments described above. Raises: TypeError: If anything other than exactly one argument is provided by the caller. def write_option(**kwargs): """Create a write option for write operations. Write operations include :meth:`~.DocumentReference.set`, :meth:`~.DocumentReference.update` and :meth:`~.DocumentReference.delete`. One of the following keyword arguments must be provided: * ``last_update_time`` (:class:`google.protobuf.timestamp_pb2.\ Timestamp`): A timestamp. When set, the target document must exist and have been last updated at that time. Protobuf ``update_time`` timestamps are typically returned from methods that perform write operations as part of a "write result" protobuf or directly. * ``exists`` (:class:`bool`): Indicates if the document being modified should already exist. Providing no argument would make the option have no effect (so it is not allowed). Providing multiple would be an apparent contradiction, since ``last_update_time`` assumes that the document **was** updated (it can't have been updated if it doesn't exist) and ``exists`` indicate that it is unknown if the document exists or not. Args: kwargs (Dict[str, Any]): The keyword arguments described above. Raises: TypeError: If anything other than exactly one argument is provided by the caller. """ if len(kwargs) != 1: raise TypeError(_BAD_OPTION_ERR) name, value = kwargs.popitem() if name == "last_update_time": return _helpers.LastUpdateOption(value) elif name == "exists": return _helpers.ExistsOption(value) else: extra = "{!r} was provided".format(name) raise TypeError(_BAD_OPTION_ERR, extra)
Retrieve a batch of documents. .. note:: Documents returned by this method are not guaranteed to be returned in the same order that they are given in ``references``. .. note:: If multiple ``references`` refer to the same document, the server will only return one result. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. If a ``transaction`` is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed). Args: references (List[.DocumentReference, ...]): Iterable of document references to be retrieved. field_paths (Optional[Iterable[str, ...]]): An iterable of field paths (``.``-delimited list of field names) to use as a projection of document fields in the returned results. If no value is provided, all fields will be returned. transaction (Optional[~.firestore_v1beta1.transaction.\ Transaction]): An existing transaction that these ``references`` will be retrieved in. Yields: .DocumentSnapshot: The next document snapshot that fulfills the query, or :data:`None` if the document does not exist. def get_all(self, references, field_paths=None, transaction=None): """Retrieve a batch of documents. .. note:: Documents returned by this method are not guaranteed to be returned in the same order that they are given in ``references``. .. note:: If multiple ``references`` refer to the same document, the server will only return one result. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. If a ``transaction`` is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed). Args: references (List[.DocumentReference, ...]): Iterable of document references to be retrieved. field_paths (Optional[Iterable[str, ...]]): An iterable of field paths (``.``-delimited list of field names) to use as a projection of document fields in the returned results. If no value is provided, all fields will be returned. transaction (Optional[~.firestore_v1beta1.transaction.\ Transaction]): An existing transaction that these ``references`` will be retrieved in. Yields: .DocumentSnapshot: The next document snapshot that fulfills the query, or :data:`None` if the document does not exist. """ document_paths, reference_map = _reference_info(references) mask = _get_doc_mask(field_paths) response_iterator = self._firestore_api.batch_get_documents( self._database_string, document_paths, mask, transaction=_helpers.get_transaction_id(transaction), metadata=self._rpc_metadata, ) for get_doc_response in response_iterator: yield _parse_batch_get(get_doc_response, reference_map, self)
List top-level collections of the client's database. Returns: Sequence[~.firestore_v1beta1.collection.CollectionReference]: iterator of subcollections of the current document. def collections(self): """List top-level collections of the client's database. Returns: Sequence[~.firestore_v1beta1.collection.CollectionReference]: iterator of subcollections of the current document. """ iterator = self._firestore_api.list_collection_ids( self._database_string, metadata=self._rpc_metadata ) iterator.client = self iterator.item_to_value = _item_to_collection_ref return iterator
Helper for :meth:`commit` et al. :raises: :exc:`ValueError` if the object's state is invalid for making API requests. def _check_state(self): """Helper for :meth:`commit` et al. :raises: :exc:`ValueError` if the object's state is invalid for making API requests. """ if self._transaction_id is None: raise ValueError("Transaction is not begun") if self.committed is not None: raise ValueError("Transaction is already committed") if self._rolled_back: raise ValueError("Transaction is already rolled back")
Begin a transaction on the database. :rtype: bytes :returns: the ID for the newly-begun transaction. :raises ValueError: if the transaction is already begun, committed, or rolled back. def begin(self): """Begin a transaction on the database. :rtype: bytes :returns: the ID for the newly-begun transaction. :raises ValueError: if the transaction is already begun, committed, or rolled back. """ if self._transaction_id is not None: raise ValueError("Transaction already begun") if self.committed is not None: raise ValueError("Transaction already committed") if self._rolled_back: raise ValueError("Transaction is already rolled back") database = self._session._database api = database.spanner_api metadata = _metadata_with_prefix(database.name) txn_options = TransactionOptions(read_write=TransactionOptions.ReadWrite()) response = api.begin_transaction( self._session.name, txn_options, metadata=metadata ) self._transaction_id = response.id return self._transaction_id
Roll back a transaction on the database. def rollback(self): """Roll back a transaction on the database.""" self._check_state() database = self._session._database api = database.spanner_api metadata = _metadata_with_prefix(database.name) api.rollback(self._session.name, self._transaction_id, metadata=metadata) self._rolled_back = True del self._session._transaction
Commit mutations to the database. :rtype: datetime :returns: timestamp of the committed changes. :raises ValueError: if there are no mutations to commit. def commit(self): """Commit mutations to the database. :rtype: datetime :returns: timestamp of the committed changes. :raises ValueError: if there are no mutations to commit. """ self._check_state() database = self._session._database api = database.spanner_api metadata = _metadata_with_prefix(database.name) response = api.commit( self._session.name, self._mutations, transaction_id=self._transaction_id, metadata=metadata, ) self.committed = _pb_timestamp_to_datetime(response.commit_timestamp) del self._session._transaction return self.committed
Helper for :meth:`execute_update`. :type params: dict, {str -> column value} :param params: values for parameter replacement. Keys must match the names used in ``dml``. :type param_types: dict[str -> Union[dict, .types.Type]] :param param_types: (Optional) maps explicit types for one or more param values; required if parameters are passed. :rtype: Union[None, :class:`Struct`] :returns: a struct message for the passed params, or None :raises ValueError: If ``param_types`` is None but ``params`` is not None. :raises ValueError: If ``params`` is None but ``param_types`` is not None. def _make_params_pb(params, param_types): """Helper for :meth:`execute_update`. :type params: dict, {str -> column value} :param params: values for parameter replacement. Keys must match the names used in ``dml``. :type param_types: dict[str -> Union[dict, .types.Type]] :param param_types: (Optional) maps explicit types for one or more param values; required if parameters are passed. :rtype: Union[None, :class:`Struct`] :returns: a struct message for the passed params, or None :raises ValueError: If ``param_types`` is None but ``params`` is not None. :raises ValueError: If ``params`` is None but ``param_types`` is not None. """ if params is not None: if param_types is None: raise ValueError("Specify 'param_types' when passing 'params'.") return Struct( fields={key: _make_value_pb(value) for key, value in params.items()} ) else: if param_types is not None: raise ValueError("Specify 'params' when passing 'param_types'.") return None
Perform an ``ExecuteSql`` API request with DML. :type dml: str :param dml: SQL DML statement :type params: dict, {str -> column value} :param params: values for parameter replacement. Keys must match the names used in ``dml``. :type param_types: dict[str -> Union[dict, .types.Type]] :param param_types: (Optional) maps explicit types for one or more param values; required if parameters are passed. :type query_mode: :class:`google.cloud.spanner_v1.proto.ExecuteSqlRequest.QueryMode` :param query_mode: Mode governing return of results / query plan. See https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode1 :rtype: int :returns: Count of rows affected by the DML statement. def execute_update(self, dml, params=None, param_types=None, query_mode=None): """Perform an ``ExecuteSql`` API request with DML. :type dml: str :param dml: SQL DML statement :type params: dict, {str -> column value} :param params: values for parameter replacement. Keys must match the names used in ``dml``. :type param_types: dict[str -> Union[dict, .types.Type]] :param param_types: (Optional) maps explicit types for one or more param values; required if parameters are passed. :type query_mode: :class:`google.cloud.spanner_v1.proto.ExecuteSqlRequest.QueryMode` :param query_mode: Mode governing return of results / query plan. See https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode1 :rtype: int :returns: Count of rows affected by the DML statement. """ params_pb = self._make_params_pb(params, param_types) database = self._session._database metadata = _metadata_with_prefix(database.name) transaction = self._make_txn_selector() api = database.spanner_api response = api.execute_sql( self._session.name, dml, transaction=transaction, params=params_pb, param_types=param_types, query_mode=query_mode, seqno=self._execute_sql_count, metadata=metadata, ) self._execute_sql_count += 1 return response.stats.row_count_exact
Perform a batch of DML statements via an ``ExecuteBatchDml`` request. :type statements: Sequence[Union[ str, Tuple[str, Dict[str, Any], Dict[str, Union[dict, .types.Type]]]]] :param statements: List of DML statements, with optional params / param types. If passed, 'params' is a dict mapping names to the values for parameter replacement. Keys must match the names used in the corresponding DML statement. If 'params' is passed, 'param_types' must also be passed, as a dict mapping names to the type of value passed in 'params'. :rtype: Tuple(status, Sequence[int]) :returns: Status code, plus counts of rows affected by each completed DML statement. Note that if the staus code is not ``OK``, the statement triggering the error will not have an entry in the list, nor will any statements following that one. def batch_update(self, statements): """Perform a batch of DML statements via an ``ExecuteBatchDml`` request. :type statements: Sequence[Union[ str, Tuple[str, Dict[str, Any], Dict[str, Union[dict, .types.Type]]]]] :param statements: List of DML statements, with optional params / param types. If passed, 'params' is a dict mapping names to the values for parameter replacement. Keys must match the names used in the corresponding DML statement. If 'params' is passed, 'param_types' must also be passed, as a dict mapping names to the type of value passed in 'params'. :rtype: Tuple(status, Sequence[int]) :returns: Status code, plus counts of rows affected by each completed DML statement. Note that if the staus code is not ``OK``, the statement triggering the error will not have an entry in the list, nor will any statements following that one. """ parsed = [] for statement in statements: if isinstance(statement, str): parsed.append({"sql": statement}) else: dml, params, param_types = statement params_pb = self._make_params_pb(params, param_types) parsed.append( {"sql": dml, "params": params_pb, "param_types": param_types} ) database = self._session._database metadata = _metadata_with_prefix(database.name) transaction = self._make_txn_selector() api = database.spanner_api response = api.execute_batch_dml( session=self._session.name, transaction=transaction, statements=parsed, seqno=self._execute_sql_count, metadata=metadata, ) self._execute_sql_count += 1 row_counts = [ result_set.stats.row_count_exact for result_set in response.result_sets ] return response.status, row_counts
Converts the :class:`TimestampRange` to a protobuf. :rtype: :class:`.data_v2_pb2.TimestampRange` :returns: The converted current object. def to_pb(self): """Converts the :class:`TimestampRange` to a protobuf. :rtype: :class:`.data_v2_pb2.TimestampRange` :returns: The converted current object. """ timestamp_range_kwargs = {} if self.start is not None: timestamp_range_kwargs["start_timestamp_micros"] = ( _microseconds_from_datetime(self.start) // 1000 * 1000 ) if self.end is not None: end_time = _microseconds_from_datetime(self.end) if end_time % 1000 != 0: end_time = end_time // 1000 * 1000 + 1000 timestamp_range_kwargs["end_timestamp_micros"] = end_time return data_v2_pb2.TimestampRange(**timestamp_range_kwargs)
Converts the row filter to a protobuf. First converts to a :class:`.data_v2_pb2.ColumnRange` and then uses it in the ``column_range_filter`` field. :rtype: :class:`.data_v2_pb2.RowFilter` :returns: The converted current object. def to_pb(self): """Converts the row filter to a protobuf. First converts to a :class:`.data_v2_pb2.ColumnRange` and then uses it in the ``column_range_filter`` field. :rtype: :class:`.data_v2_pb2.RowFilter` :returns: The converted current object. """ column_range_kwargs = {"family_name": self.column_family_id} if self.start_column is not None: if self.inclusive_start: key = "start_qualifier_closed" else: key = "start_qualifier_open" column_range_kwargs[key] = _to_bytes(self.start_column) if self.end_column is not None: if self.inclusive_end: key = "end_qualifier_closed" else: key = "end_qualifier_open" column_range_kwargs[key] = _to_bytes(self.end_column) column_range = data_v2_pb2.ColumnRange(**column_range_kwargs) return data_v2_pb2.RowFilter(column_range_filter=column_range)
Converts the row filter to a protobuf. First converts to a :class:`.data_v2_pb2.ValueRange` and then uses it to create a row filter protobuf. :rtype: :class:`.data_v2_pb2.RowFilter` :returns: The converted current object. def to_pb(self): """Converts the row filter to a protobuf. First converts to a :class:`.data_v2_pb2.ValueRange` and then uses it to create a row filter protobuf. :rtype: :class:`.data_v2_pb2.RowFilter` :returns: The converted current object. """ value_range_kwargs = {} if self.start_value is not None: if self.inclusive_start: key = "start_value_closed" else: key = "start_value_open" value_range_kwargs[key] = _to_bytes(self.start_value) if self.end_value is not None: if self.inclusive_end: key = "end_value_closed" else: key = "end_value_open" value_range_kwargs[key] = _to_bytes(self.end_value) value_range = data_v2_pb2.ValueRange(**value_range_kwargs) return data_v2_pb2.RowFilter(value_range_filter=value_range)
Converts the row filter to a protobuf. :rtype: :class:`.data_v2_pb2.RowFilter` :returns: The converted current object. def to_pb(self): """Converts the row filter to a protobuf. :rtype: :class:`.data_v2_pb2.RowFilter` :returns: The converted current object. """ chain = data_v2_pb2.RowFilter.Chain( filters=[row_filter.to_pb() for row_filter in self.filters] ) return data_v2_pb2.RowFilter(chain=chain)
Converts the row filter to a protobuf. :rtype: :class:`.data_v2_pb2.RowFilter` :returns: The converted current object. def to_pb(self): """Converts the row filter to a protobuf. :rtype: :class:`.data_v2_pb2.RowFilter` :returns: The converted current object. """ interleave = data_v2_pb2.RowFilter.Interleave( filters=[row_filter.to_pb() for row_filter in self.filters] ) return data_v2_pb2.RowFilter(interleave=interleave)
Converts the row filter to a protobuf. :rtype: :class:`.data_v2_pb2.RowFilter` :returns: The converted current object. def to_pb(self): """Converts the row filter to a protobuf. :rtype: :class:`.data_v2_pb2.RowFilter` :returns: The converted current object. """ condition_kwargs = {"predicate_filter": self.base_filter.to_pb()} if self.true_filter is not None: condition_kwargs["true_filter"] = self.true_filter.to_pb() if self.false_filter is not None: condition_kwargs["false_filter"] = self.false_filter.to_pb() condition = data_v2_pb2.RowFilter.Condition(**condition_kwargs) return data_v2_pb2.RowFilter(condition=condition)
Return a fully-qualified organization_deidentify_template string. def organization_deidentify_template_path(cls, organization, deidentify_template): """Return a fully-qualified organization_deidentify_template string.""" return google.api_core.path_template.expand( "organizations/{organization}/deidentifyTemplates/{deidentify_template}", organization=organization, deidentify_template=deidentify_template, )
Return a fully-qualified project_deidentify_template string. def project_deidentify_template_path(cls, project, deidentify_template): """Return a fully-qualified project_deidentify_template string.""" return google.api_core.path_template.expand( "projects/{project}/deidentifyTemplates/{deidentify_template}", project=project, deidentify_template=deidentify_template, )
Return a fully-qualified organization_inspect_template string. def organization_inspect_template_path(cls, organization, inspect_template): """Return a fully-qualified organization_inspect_template string.""" return google.api_core.path_template.expand( "organizations/{organization}/inspectTemplates/{inspect_template}", organization=organization, inspect_template=inspect_template, )
Return a fully-qualified project_inspect_template string. def project_inspect_template_path(cls, project, inspect_template): """Return a fully-qualified project_inspect_template string.""" return google.api_core.path_template.expand( "projects/{project}/inspectTemplates/{inspect_template}", project=project, inspect_template=inspect_template, )
Return a fully-qualified project_job_trigger string. def project_job_trigger_path(cls, project, job_trigger): """Return a fully-qualified project_job_trigger string.""" return google.api_core.path_template.expand( "projects/{project}/jobTriggers/{job_trigger}", project=project, job_trigger=job_trigger, )
Return a fully-qualified dlp_job string. def dlp_job_path(cls, project, dlp_job): """Return a fully-qualified dlp_job string.""" return google.api_core.path_template.expand( "projects/{project}/dlpJobs/{dlp_job}", project=project, dlp_job=dlp_job )
Return a fully-qualified organization_stored_info_type string. def organization_stored_info_type_path(cls, organization, stored_info_type): """Return a fully-qualified organization_stored_info_type string.""" return google.api_core.path_template.expand( "organizations/{organization}/storedInfoTypes/{stored_info_type}", organization=organization, stored_info_type=stored_info_type, )
Return a fully-qualified project_stored_info_type string. def project_stored_info_type_path(cls, project, stored_info_type): """Return a fully-qualified project_stored_info_type string.""" return google.api_core.path_template.expand( "projects/{project}/storedInfoTypes/{stored_info_type}", project=project, stored_info_type=stored_info_type, )
Redacts potentially sensitive info from an image. This method has limits on input size, processing time, and output size. See https://cloud.google.com/dlp/docs/redacting-sensitive-data-images to learn more. When no InfoTypes or CustomInfoTypes are specified in this request, the system will automatically choose what detectors to run. By default this may be all types, but may change over time as detectors are updated. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.redact_image(parent) Args: parent (str): The parent resource name, for example projects/my-project-id. inspect_config (Union[dict, ~google.cloud.dlp_v2.types.InspectConfig]): Configuration for the inspector. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.InspectConfig` image_redaction_configs (list[Union[dict, ~google.cloud.dlp_v2.types.ImageRedactionConfig]]): The configuration for specifying what content to redact from images. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.ImageRedactionConfig` include_findings (bool): Whether the response should include findings along with the redacted image. byte_item (Union[dict, ~google.cloud.dlp_v2.types.ByteContentItem]): The content must be PNG, JPEG, SVG or BMP. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.ByteContentItem` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.RedactImageResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def redact_image( self, parent, inspect_config=None, image_redaction_configs=None, include_findings=None, byte_item=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Redacts potentially sensitive info from an image. This method has limits on input size, processing time, and output size. See https://cloud.google.com/dlp/docs/redacting-sensitive-data-images to learn more. When no InfoTypes or CustomInfoTypes are specified in this request, the system will automatically choose what detectors to run. By default this may be all types, but may change over time as detectors are updated. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.redact_image(parent) Args: parent (str): The parent resource name, for example projects/my-project-id. inspect_config (Union[dict, ~google.cloud.dlp_v2.types.InspectConfig]): Configuration for the inspector. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.InspectConfig` image_redaction_configs (list[Union[dict, ~google.cloud.dlp_v2.types.ImageRedactionConfig]]): The configuration for specifying what content to redact from images. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.ImageRedactionConfig` include_findings (bool): Whether the response should include findings along with the redacted image. byte_item (Union[dict, ~google.cloud.dlp_v2.types.ByteContentItem]): The content must be PNG, JPEG, SVG or BMP. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.ByteContentItem` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.RedactImageResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "redact_image" not in self._inner_api_calls: self._inner_api_calls[ "redact_image" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.redact_image, default_retry=self._method_configs["RedactImage"].retry, default_timeout=self._method_configs["RedactImage"].timeout, client_info=self._client_info, ) request = dlp_pb2.RedactImageRequest( parent=parent, inspect_config=inspect_config, image_redaction_configs=image_redaction_configs, include_findings=include_findings, byte_item=byte_item, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["redact_image"]( request, retry=retry, timeout=timeout, metadata=metadata )
Re-identifies content that has been de-identified. See https://cloud.google.com/dlp/docs/pseudonymization#re-identification\_in\_free\_text\_code\_example to learn more. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.reidentify_content(parent) Args: parent (str): The parent resource name. reidentify_config (Union[dict, ~google.cloud.dlp_v2.types.DeidentifyConfig]): Configuration for the re-identification of the content item. This field shares the same proto message type that is used for de-identification, however its usage here is for the reversal of the previous de-identification. Re-identification is performed by examining the transformations used to de-identify the items and executing the reverse. This requires that only reversible transformations be provided here. The reversible transformations are: - ``CryptoReplaceFfxFpeConfig`` If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.DeidentifyConfig` inspect_config (Union[dict, ~google.cloud.dlp_v2.types.InspectConfig]): Configuration for the inspector. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.InspectConfig` item (Union[dict, ~google.cloud.dlp_v2.types.ContentItem]): The item to re-identify. Will be treated as text. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.ContentItem` inspect_template_name (str): Optional template to use. Any configuration directly specified in ``inspect_config`` will override those set in the template. Singular fields that are set in this request will replace their corresponding fields in the template. Repeated fields are appended. Singular sub-messages and groups are recursively merged. reidentify_template_name (str): Optional template to use. References an instance of ``DeidentifyTemplate``. Any configuration directly specified in ``reidentify_config`` or ``inspect_config`` will override those set in the template. Singular fields that are set in this request will replace their corresponding fields in the template. Repeated fields are appended. Singular sub-messages and groups are recursively merged. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.ReidentifyContentResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def reidentify_content( self, parent, reidentify_config=None, inspect_config=None, item=None, inspect_template_name=None, reidentify_template_name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Re-identifies content that has been de-identified. See https://cloud.google.com/dlp/docs/pseudonymization#re-identification\_in\_free\_text\_code\_example to learn more. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.reidentify_content(parent) Args: parent (str): The parent resource name. reidentify_config (Union[dict, ~google.cloud.dlp_v2.types.DeidentifyConfig]): Configuration for the re-identification of the content item. This field shares the same proto message type that is used for de-identification, however its usage here is for the reversal of the previous de-identification. Re-identification is performed by examining the transformations used to de-identify the items and executing the reverse. This requires that only reversible transformations be provided here. The reversible transformations are: - ``CryptoReplaceFfxFpeConfig`` If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.DeidentifyConfig` inspect_config (Union[dict, ~google.cloud.dlp_v2.types.InspectConfig]): Configuration for the inspector. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.InspectConfig` item (Union[dict, ~google.cloud.dlp_v2.types.ContentItem]): The item to re-identify. Will be treated as text. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.ContentItem` inspect_template_name (str): Optional template to use. Any configuration directly specified in ``inspect_config`` will override those set in the template. Singular fields that are set in this request will replace their corresponding fields in the template. Repeated fields are appended. Singular sub-messages and groups are recursively merged. reidentify_template_name (str): Optional template to use. References an instance of ``DeidentifyTemplate``. Any configuration directly specified in ``reidentify_config`` or ``inspect_config`` will override those set in the template. Singular fields that are set in this request will replace their corresponding fields in the template. Repeated fields are appended. Singular sub-messages and groups are recursively merged. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.ReidentifyContentResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "reidentify_content" not in self._inner_api_calls: self._inner_api_calls[ "reidentify_content" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.reidentify_content, default_retry=self._method_configs["ReidentifyContent"].retry, default_timeout=self._method_configs["ReidentifyContent"].timeout, client_info=self._client_info, ) request = dlp_pb2.ReidentifyContentRequest( parent=parent, reidentify_config=reidentify_config, inspect_config=inspect_config, item=item, inspect_template_name=inspect_template_name, reidentify_template_name=reidentify_template_name, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["reidentify_content"]( request, retry=retry, timeout=timeout, metadata=metadata )
Returns a list of the sensitive information types that the DLP API supports. See https://cloud.google.com/dlp/docs/infotypes-reference to learn more. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> response = client.list_info_types() Args: language_code (str): Optional BCP-47 language code for localized infoType friendly names. If omitted, or if localized strings are not available, en-US strings will be returned. filter_ (str): Optional filter to only return infoTypes supported by certain parts of the API. Defaults to supported\_by=INSPECT. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.ListInfoTypesResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def list_info_types( self, language_code=None, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Returns a list of the sensitive information types that the DLP API supports. See https://cloud.google.com/dlp/docs/infotypes-reference to learn more. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> response = client.list_info_types() Args: language_code (str): Optional BCP-47 language code for localized infoType friendly names. If omitted, or if localized strings are not available, en-US strings will be returned. filter_ (str): Optional filter to only return infoTypes supported by certain parts of the API. Defaults to supported\_by=INSPECT. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.ListInfoTypesResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "list_info_types" not in self._inner_api_calls: self._inner_api_calls[ "list_info_types" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_info_types, default_retry=self._method_configs["ListInfoTypes"].retry, default_timeout=self._method_configs["ListInfoTypes"].timeout, client_info=self._client_info, ) request = dlp_pb2.ListInfoTypesRequest( language_code=language_code, filter=filter_ ) return self._inner_api_calls["list_info_types"]( request, retry=retry, timeout=timeout, metadata=metadata )
Creates an InspectTemplate for re-using frequently used configuration for inspecting content, images, and storage. See https://cloud.google.com/dlp/docs/creating-templates to learn more. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.organization_path('[ORGANIZATION]') >>> >>> response = client.create_inspect_template(parent) Args: parent (str): The parent resource name, for example projects/my-project-id or organizations/my-org-id. inspect_template (Union[dict, ~google.cloud.dlp_v2.types.InspectTemplate]): The InspectTemplate to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.InspectTemplate` template_id (str): The template id can contain uppercase and lowercase letters, numbers, and hyphens; that is, it must match the regular expression: ``[a-zA-Z\\d-_]+``. The maximum length is 100 characters. Can be empty to allow the system to generate one. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.InspectTemplate` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def create_inspect_template( self, parent, inspect_template=None, template_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an InspectTemplate for re-using frequently used configuration for inspecting content, images, and storage. See https://cloud.google.com/dlp/docs/creating-templates to learn more. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.organization_path('[ORGANIZATION]') >>> >>> response = client.create_inspect_template(parent) Args: parent (str): The parent resource name, for example projects/my-project-id or organizations/my-org-id. inspect_template (Union[dict, ~google.cloud.dlp_v2.types.InspectTemplate]): The InspectTemplate to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.InspectTemplate` template_id (str): The template id can contain uppercase and lowercase letters, numbers, and hyphens; that is, it must match the regular expression: ``[a-zA-Z\\d-_]+``. The maximum length is 100 characters. Can be empty to allow the system to generate one. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.InspectTemplate` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_inspect_template" not in self._inner_api_calls: self._inner_api_calls[ "create_inspect_template" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_inspect_template, default_retry=self._method_configs["CreateInspectTemplate"].retry, default_timeout=self._method_configs["CreateInspectTemplate"].timeout, client_info=self._client_info, ) request = dlp_pb2.CreateInspectTemplateRequest( parent=parent, inspect_template=inspect_template, template_id=template_id ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_inspect_template"]( request, retry=retry, timeout=timeout, metadata=metadata )
Creates a new job to inspect storage or calculate risk metrics. See https://cloud.google.com/dlp/docs/inspecting-storage and https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. When no InfoTypes or CustomInfoTypes are specified in inspect jobs, the system will automatically choose what detectors to run. By default this may be all types, but may change over time as detectors are updated. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.create_dlp_job(parent) Args: parent (str): The parent resource name, for example projects/my-project-id. inspect_job (Union[dict, ~google.cloud.dlp_v2.types.InspectJobConfig]): If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.InspectJobConfig` risk_job (Union[dict, ~google.cloud.dlp_v2.types.RiskAnalysisJobConfig]): If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.RiskAnalysisJobConfig` job_id (str): The job id can contain uppercase and lowercase letters, numbers, and hyphens; that is, it must match the regular expression: ``[a-zA-Z\\d-_]+``. The maximum length is 100 characters. Can be empty to allow the system to generate one. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.DlpJob` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def create_dlp_job( self, parent, inspect_job=None, risk_job=None, job_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new job to inspect storage or calculate risk metrics. See https://cloud.google.com/dlp/docs/inspecting-storage and https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. When no InfoTypes or CustomInfoTypes are specified in inspect jobs, the system will automatically choose what detectors to run. By default this may be all types, but may change over time as detectors are updated. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.create_dlp_job(parent) Args: parent (str): The parent resource name, for example projects/my-project-id. inspect_job (Union[dict, ~google.cloud.dlp_v2.types.InspectJobConfig]): If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.InspectJobConfig` risk_job (Union[dict, ~google.cloud.dlp_v2.types.RiskAnalysisJobConfig]): If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.RiskAnalysisJobConfig` job_id (str): The job id can contain uppercase and lowercase letters, numbers, and hyphens; that is, it must match the regular expression: ``[a-zA-Z\\d-_]+``. The maximum length is 100 characters. Can be empty to allow the system to generate one. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.DlpJob` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_dlp_job" not in self._inner_api_calls: self._inner_api_calls[ "create_dlp_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_dlp_job, default_retry=self._method_configs["CreateDlpJob"].retry, default_timeout=self._method_configs["CreateDlpJob"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( inspect_job=inspect_job, risk_job=risk_job ) request = dlp_pb2.CreateDlpJobRequest( parent=parent, inspect_job=inspect_job, risk_job=risk_job, job_id=job_id ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_dlp_job"]( request, retry=retry, timeout=timeout, metadata=metadata )
Creates a job trigger to run DLP actions such as scanning storage for sensitive information on a set schedule. See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.create_job_trigger(parent) Args: parent (str): The parent resource name, for example projects/my-project-id. job_trigger (Union[dict, ~google.cloud.dlp_v2.types.JobTrigger]): The JobTrigger to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.JobTrigger` trigger_id (str): The trigger id can contain uppercase and lowercase letters, numbers, and hyphens; that is, it must match the regular expression: ``[a-zA-Z\\d-_]+``. The maximum length is 100 characters. Can be empty to allow the system to generate one. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.JobTrigger` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def create_job_trigger( self, parent, job_trigger=None, trigger_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a job trigger to run DLP actions such as scanning storage for sensitive information on a set schedule. See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.create_job_trigger(parent) Args: parent (str): The parent resource name, for example projects/my-project-id. job_trigger (Union[dict, ~google.cloud.dlp_v2.types.JobTrigger]): The JobTrigger to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.JobTrigger` trigger_id (str): The trigger id can contain uppercase and lowercase letters, numbers, and hyphens; that is, it must match the regular expression: ``[a-zA-Z\\d-_]+``. The maximum length is 100 characters. Can be empty to allow the system to generate one. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.JobTrigger` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_job_trigger" not in self._inner_api_calls: self._inner_api_calls[ "create_job_trigger" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_job_trigger, default_retry=self._method_configs["CreateJobTrigger"].retry, default_timeout=self._method_configs["CreateJobTrigger"].timeout, client_info=self._client_info, ) request = dlp_pb2.CreateJobTriggerRequest( parent=parent, job_trigger=job_trigger, trigger_id=trigger_id ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_job_trigger"]( request, retry=retry, timeout=timeout, metadata=metadata )
Creates a pre-built stored infoType to be used for inspection. See https://cloud.google.com/dlp/docs/creating-stored-infotypes to learn more. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.organization_path('[ORGANIZATION]') >>> >>> response = client.create_stored_info_type(parent) Args: parent (str): The parent resource name, for example projects/my-project-id or organizations/my-org-id. config (Union[dict, ~google.cloud.dlp_v2.types.StoredInfoTypeConfig]): Configuration of the storedInfoType to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.StoredInfoTypeConfig` stored_info_type_id (str): The storedInfoType ID can contain uppercase and lowercase letters, numbers, and hyphens; that is, it must match the regular expression: ``[a-zA-Z\\d-_]+``. The maximum length is 100 characters. Can be empty to allow the system to generate one. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.StoredInfoType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def create_stored_info_type( self, parent, config=None, stored_info_type_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a pre-built stored infoType to be used for inspection. See https://cloud.google.com/dlp/docs/creating-stored-infotypes to learn more. Example: >>> from google.cloud import dlp_v2 >>> >>> client = dlp_v2.DlpServiceClient() >>> >>> parent = client.organization_path('[ORGANIZATION]') >>> >>> response = client.create_stored_info_type(parent) Args: parent (str): The parent resource name, for example projects/my-project-id or organizations/my-org-id. config (Union[dict, ~google.cloud.dlp_v2.types.StoredInfoTypeConfig]): Configuration of the storedInfoType to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dlp_v2.types.StoredInfoTypeConfig` stored_info_type_id (str): The storedInfoType ID can contain uppercase and lowercase letters, numbers, and hyphens; that is, it must match the regular expression: ``[a-zA-Z\\d-_]+``. The maximum length is 100 characters. Can be empty to allow the system to generate one. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dlp_v2.types.StoredInfoType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_stored_info_type" not in self._inner_api_calls: self._inner_api_calls[ "create_stored_info_type" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_stored_info_type, default_retry=self._method_configs["CreateStoredInfoType"].retry, default_timeout=self._method_configs["CreateStoredInfoType"].timeout, client_info=self._client_info, ) request = dlp_pb2.CreateStoredInfoTypeRequest( parent=parent, config=config, stored_info_type_id=stored_info_type_id ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_stored_info_type"]( request, retry=retry, timeout=timeout, metadata=metadata )
Helper for trace-related API calls. See https://cloud.google.com/trace/docs/reference/v2/rpc/google.devtools. cloudtrace.v2 def trace_api(self): """ Helper for trace-related API calls. See https://cloud.google.com/trace/docs/reference/v2/rpc/google.devtools. cloudtrace.v2 """ if self._trace_api is None: self._trace_api = make_trace_api(self) return self._trace_api
Sends new spans to Stackdriver Trace or updates existing traces. If the name of a trace that you send matches that of an existing trace, new spans are added to the existing trace. Attempt to update existing spans results undefined behavior. If the name does not match, a new trace is created with given set of spans. Example: >>> from google.cloud import trace_v2 >>> >>> client = trace_v2.Client() >>> >>> name = 'projects/[PROJECT_ID]' >>> spans = {'spans': [{'endTime': '2017-11-21T23:50:58.890768Z', 'spanId': [SPAN_ID], 'startTime': '2017-11-21T23:50:58.890763Z', 'name': 'projects/[PROJECT_ID]/traces/ [TRACE_ID]/spans/[SPAN_ID]', 'displayName': {'value': 'sample span'}}]} >>> >>> client.batch_write_spans(name, spans) Args: name (str): Optional. Name of the project where the spans belong. The format is ``projects/PROJECT_ID``. spans (dict): A collection of spans. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def batch_write_spans(self, name, spans, retry=None, timeout=None): """ Sends new spans to Stackdriver Trace or updates existing traces. If the name of a trace that you send matches that of an existing trace, new spans are added to the existing trace. Attempt to update existing spans results undefined behavior. If the name does not match, a new trace is created with given set of spans. Example: >>> from google.cloud import trace_v2 >>> >>> client = trace_v2.Client() >>> >>> name = 'projects/[PROJECT_ID]' >>> spans = {'spans': [{'endTime': '2017-11-21T23:50:58.890768Z', 'spanId': [SPAN_ID], 'startTime': '2017-11-21T23:50:58.890763Z', 'name': 'projects/[PROJECT_ID]/traces/ [TRACE_ID]/spans/[SPAN_ID]', 'displayName': {'value': 'sample span'}}]} >>> >>> client.batch_write_spans(name, spans) Args: name (str): Optional. Name of the project where the spans belong. The format is ``projects/PROJECT_ID``. spans (dict): A collection of spans. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ self.trace_api.batch_write_spans( name=name, spans=spans, retry=retry, timeout=timeout )
Creates a new Span. Example: >>> from google.cloud import trace_v2 >>> >>> client = trace_v2.Client() >>> >>> name = 'projects/{project}/traces/{trace_id}/spans/{span_id}'. format('[PROJECT]', '[TRACE_ID]', '[SPAN_ID]') >>> span_id = '[SPAN_ID]' >>> display_name = {} >>> start_time = {} >>> end_time = {} >>> >>> response = client.create_span(name, span_id, display_name, start_time, end_time) Args: name (str): The resource name of the span in the following format: :: projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] [TRACE_ID] is a unique identifier for a trace within a project. [SPAN_ID] is a unique identifier for a span within a trace, assigned when the span is created. span_id (str): The [SPAN_ID] portion of the span's resource name. The ID is a 16-character hexadecimal encoding of an 8-byte array. display_name (dict): A description of the span's operation (up to 128 bytes). Stackdriver Trace displays the description in the {% dynamic print site_values.console_name %}. For example, the display name can be a qualified method name or a file name and a line number where the operation is called. A best practice is to use the same display name within an application and at the same call point. This makes it easier to correlate spans in different traces. Contains two fields, value is the truncated name, truncatedByteCount is the number of bytes removed from the original string. If 0, then the string was not shortened. start_time (:class:`~datetime.datetime`): The start time of the span. On the client side, this is the time kept by the local machine where the span execution starts. On the server side, this is the time when the server's application handler starts running. end_time (:class:`~datetime.datetime`): The end time of the span. On the client side, this is the time kept by the local machine where the span execution ends. On the server side, this is the time when the server application handler stops running. parent_span_id (str): The [SPAN_ID] of this span's parent span. If this is a root span, then this field must be empty. attributes (dict): A set of attributes on the span. There is a limit of 32 attributes per span. stack_trace (dict): Stack trace captured at the start of the span. Contains two fields, stackFrames is a list of stack frames in this call stack, a maximum of 128 frames are allowed per StackFrame; stackTraceHashId is used to conserve network bandwidth for duplicate stack traces within a single trace. time_events (dict): The included time events. There can be up to 32 annotations and 128 message events per span. links (dict): A maximum of 128 links are allowed per Span. status (dict): An optional final status for this span. same_process_as_parent_span (bool): A highly recommended but not required flag that identifies when a trace crosses a process boundary. True when the parent_span belongs to the same process as the current span. child_span_count (int): An optional number of child spans that were generated while this span was active. If set, allows implementation to detect missing child spans. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. Returns: A :class:`~google.cloud.trace_v2.types.Span` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def create_span( self, name, span_id, display_name, start_time, end_time, parent_span_id=None, attributes=None, stack_trace=None, time_events=None, links=None, status=None, same_process_as_parent_span=None, child_span_count=None, retry=None, timeout=None, ): """ Creates a new Span. Example: >>> from google.cloud import trace_v2 >>> >>> client = trace_v2.Client() >>> >>> name = 'projects/{project}/traces/{trace_id}/spans/{span_id}'. format('[PROJECT]', '[TRACE_ID]', '[SPAN_ID]') >>> span_id = '[SPAN_ID]' >>> display_name = {} >>> start_time = {} >>> end_time = {} >>> >>> response = client.create_span(name, span_id, display_name, start_time, end_time) Args: name (str): The resource name of the span in the following format: :: projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] [TRACE_ID] is a unique identifier for a trace within a project. [SPAN_ID] is a unique identifier for a span within a trace, assigned when the span is created. span_id (str): The [SPAN_ID] portion of the span's resource name. The ID is a 16-character hexadecimal encoding of an 8-byte array. display_name (dict): A description of the span's operation (up to 128 bytes). Stackdriver Trace displays the description in the {% dynamic print site_values.console_name %}. For example, the display name can be a qualified method name or a file name and a line number where the operation is called. A best practice is to use the same display name within an application and at the same call point. This makes it easier to correlate spans in different traces. Contains two fields, value is the truncated name, truncatedByteCount is the number of bytes removed from the original string. If 0, then the string was not shortened. start_time (:class:`~datetime.datetime`): The start time of the span. On the client side, this is the time kept by the local machine where the span execution starts. On the server side, this is the time when the server's application handler starts running. end_time (:class:`~datetime.datetime`): The end time of the span. On the client side, this is the time kept by the local machine where the span execution ends. On the server side, this is the time when the server application handler stops running. parent_span_id (str): The [SPAN_ID] of this span's parent span. If this is a root span, then this field must be empty. attributes (dict): A set of attributes on the span. There is a limit of 32 attributes per span. stack_trace (dict): Stack trace captured at the start of the span. Contains two fields, stackFrames is a list of stack frames in this call stack, a maximum of 128 frames are allowed per StackFrame; stackTraceHashId is used to conserve network bandwidth for duplicate stack traces within a single trace. time_events (dict): The included time events. There can be up to 32 annotations and 128 message events per span. links (dict): A maximum of 128 links are allowed per Span. status (dict): An optional final status for this span. same_process_as_parent_span (bool): A highly recommended but not required flag that identifies when a trace crosses a process boundary. True when the parent_span belongs to the same process as the current span. child_span_count (int): An optional number of child spans that were generated while this span was active. If set, allows implementation to detect missing child spans. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. Returns: A :class:`~google.cloud.trace_v2.types.Span` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ return self.trace_api.create_span( name=name, span_id=span_id, display_name=display_name, start_time=start_time, end_time=end_time, parent_span_id=parent_span_id, attributes=attributes, stack_trace=stack_trace, time_events=time_events, links=links, status=status, same_process_as_parent_span=same_process_as_parent_span, child_span_count=child_span_count, )
Report error payload. :type error_report: dict :param: error_report: dict payload of the error report formatted according to https://cloud.google.com/error-reporting/docs/formatting-error-messages This object should be built using :meth:~`google.cloud.error_reporting.client._build_error_report` def report_error_event(self, error_report): """Report error payload. :type error_report: dict :param: error_report: dict payload of the error report formatted according to https://cloud.google.com/error-reporting/docs/formatting-error-messages This object should be built using :meth:~`google.cloud.error_reporting.client._build_error_report` """ logger = self.logging_client.logger("errors") logger.log_struct(error_report)
Returns a routing header string for the given request parameters. Args: params (Mapping[str, Any]): A dictionary containing the request parameters used for routing. Returns: str: The routing header string. def to_routing_header(params): """Returns a routing header string for the given request parameters. Args: params (Mapping[str, Any]): A dictionary containing the request parameters used for routing. Returns: str: The routing header string. """ if sys.version_info[0] < 3: # Python 2 does not have the "safe" parameter for urlencode. return urlencode(params).replace("%2F", "/") return urlencode( params, # Per Google API policy (go/api-url-encoding), / is not encoded. safe="/", )
Construct a field description protobuf. :type name: str :param name: the name of the field :type field_type: :class:`type_pb2.Type` :param field_type: the type of the field :rtype: :class:`type_pb2.StructType.Field` :returns: the appropriate struct-field-type protobuf def StructField(name, field_type): # pylint: disable=invalid-name """Construct a field description protobuf. :type name: str :param name: the name of the field :type field_type: :class:`type_pb2.Type` :param field_type: the type of the field :rtype: :class:`type_pb2.StructType.Field` :returns: the appropriate struct-field-type protobuf """ return type_pb2.StructType.Field(name=name, type=field_type)
Construct a struct parameter type description protobuf. :type fields: list of :class:`type_pb2.StructType.Field` :param fields: the fields of the struct :rtype: :class:`type_pb2.Type` :returns: the appropriate struct-type protobuf def Struct(fields): # pylint: disable=invalid-name """Construct a struct parameter type description protobuf. :type fields: list of :class:`type_pb2.StructType.Field` :param fields: the fields of the struct :rtype: :class:`type_pb2.Type` :returns: the appropriate struct-type protobuf """ return type_pb2.Type( code=type_pb2.STRUCT, struct_type=type_pb2.StructType(fields=fields) )
Perform bi-directional speech recognition. This method allows you to receive results while sending audio; it is only available via. gRPC (not REST). .. warning:: This method is EXPERIMENTAL. Its interface might change in the future. Example: >>> from google.cloud.speech_v1 import enums >>> from google.cloud.speech_v1 import SpeechClient >>> from google.cloud.speech_v1 import types >>> client = SpeechClient() >>> config = types.StreamingRecognitionConfig( ... config=types.RecognitionConfig( ... encoding=enums.RecognitionConfig.AudioEncoding.FLAC, ... ), ... ) >>> request = types.StreamingRecognizeRequest(audio_content=b'...') >>> requests = [request] >>> for element in client.streaming_recognize(config, requests): ... # process element ... pass Args: config (:class:`~.types.StreamingRecognitionConfig`): The configuration to use for the stream. requests (Iterable[:class:`~.types.StreamingRecognizeRequest`]): The input objects. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. Returns: Iterable[:class:`~.types.StreamingRecognizeResponse`] Raises: :exc:`google.gax.errors.GaxError` if the RPC is aborted. :exc:`ValueError` if the parameters are invalid. def streaming_recognize( self, config, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, ): """Perform bi-directional speech recognition. This method allows you to receive results while sending audio; it is only available via. gRPC (not REST). .. warning:: This method is EXPERIMENTAL. Its interface might change in the future. Example: >>> from google.cloud.speech_v1 import enums >>> from google.cloud.speech_v1 import SpeechClient >>> from google.cloud.speech_v1 import types >>> client = SpeechClient() >>> config = types.StreamingRecognitionConfig( ... config=types.RecognitionConfig( ... encoding=enums.RecognitionConfig.AudioEncoding.FLAC, ... ), ... ) >>> request = types.StreamingRecognizeRequest(audio_content=b'...') >>> requests = [request] >>> for element in client.streaming_recognize(config, requests): ... # process element ... pass Args: config (:class:`~.types.StreamingRecognitionConfig`): The configuration to use for the stream. requests (Iterable[:class:`~.types.StreamingRecognizeRequest`]): The input objects. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. Returns: Iterable[:class:`~.types.StreamingRecognizeResponse`] Raises: :exc:`google.gax.errors.GaxError` if the RPC is aborted. :exc:`ValueError` if the parameters are invalid. """ return super(SpeechHelpers, self).streaming_recognize( self._streaming_request_iterable(config, requests), retry=retry, timeout=timeout, )
A generator that yields the config followed by the requests. Args: config (~.speech_v1.types.StreamingRecognitionConfig): The configuration to use for the stream. requests (Iterable[~.speech_v1.types.StreamingRecognizeRequest]): The input objects. Returns: Iterable[~.speech_v1.types.StreamingRecognizeRequest]): The correctly formatted input for :meth:`~.speech_v1.SpeechClient.streaming_recognize`. def _streaming_request_iterable(self, config, requests): """A generator that yields the config followed by the requests. Args: config (~.speech_v1.types.StreamingRecognitionConfig): The configuration to use for the stream. requests (Iterable[~.speech_v1.types.StreamingRecognizeRequest]): The input objects. Returns: Iterable[~.speech_v1.types.StreamingRecognizeRequest]): The correctly formatted input for :meth:`~.speech_v1.SpeechClient.streaming_recognize`. """ yield self.types.StreamingRecognizeRequest(streaming_config=config) for request in requests: yield request
Return a fully-qualified project_data_source string. def project_data_source_path(cls, project, data_source): """Return a fully-qualified project_data_source string.""" return google.api_core.path_template.expand( "projects/{project}/dataSources/{data_source}", project=project, data_source=data_source, )
Return a fully-qualified project_transfer_config string. def project_transfer_config_path(cls, project, transfer_config): """Return a fully-qualified project_transfer_config string.""" return google.api_core.path_template.expand( "projects/{project}/transferConfigs/{transfer_config}", project=project, transfer_config=transfer_config, )
Return a fully-qualified project_run string. def project_run_path(cls, project, transfer_config, run): """Return a fully-qualified project_run string.""" return google.api_core.path_template.expand( "projects/{project}/transferConfigs/{transfer_config}/runs/{run}", project=project, transfer_config=transfer_config, run=run, )
Creates a new data transfer configuration. Example: >>> from google.cloud import bigquery_datatransfer_v1 >>> >>> client = bigquery_datatransfer_v1.DataTransferServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `transfer_config`: >>> transfer_config = {} >>> >>> response = client.create_transfer_config(parent, transfer_config) Args: parent (str): The BigQuery project id where the transfer configuration should be created. Must be in the format /projects/{project\_id}/locations/{location\_id} If specified location and location of the destination bigquery dataset do not match - the request will fail. transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` authorization_code (str): Optional OAuth2 authorization code to use with this transfer configuration. This is required if new credentials are needed, as indicated by ``CheckValidCreds``. In order to obtain authorization\_code, please make a request to https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=<data\_source\_scopes>&redirect\_uri=<redirect\_uri> - client\_id should be OAuth client\_id of BigQuery DTS API for the given data source returned by ListDataSources method. - data\_source\_scopes are the scopes returned by ListDataSources method. - redirect\_uri is an optional parameter. If not specified, then authorization code is posted to the opener of authorization flow window. Otherwise it will be sent to the redirect uri. A special value of urn:ietf:wg:oauth:2.0:oob means that authorization code should be returned in the title bar of the browser, with the page text prompting the user to copy the code and paste it in the application. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def create_transfer_config( self, parent, transfer_config, authorization_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new data transfer configuration. Example: >>> from google.cloud import bigquery_datatransfer_v1 >>> >>> client = bigquery_datatransfer_v1.DataTransferServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `transfer_config`: >>> transfer_config = {} >>> >>> response = client.create_transfer_config(parent, transfer_config) Args: parent (str): The BigQuery project id where the transfer configuration should be created. Must be in the format /projects/{project\_id}/locations/{location\_id} If specified location and location of the destination bigquery dataset do not match - the request will fail. transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` authorization_code (str): Optional OAuth2 authorization code to use with this transfer configuration. This is required if new credentials are needed, as indicated by ``CheckValidCreds``. In order to obtain authorization\_code, please make a request to https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=<data\_source\_scopes>&redirect\_uri=<redirect\_uri> - client\_id should be OAuth client\_id of BigQuery DTS API for the given data source returned by ListDataSources method. - data\_source\_scopes are the scopes returned by ListDataSources method. - redirect\_uri is an optional parameter. If not specified, then authorization code is posted to the opener of authorization flow window. Otherwise it will be sent to the redirect uri. A special value of urn:ietf:wg:oauth:2.0:oob means that authorization code should be returned in the title bar of the browser, with the page text prompting the user to copy the code and paste it in the application. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_transfer_config" not in self._inner_api_calls: self._inner_api_calls[ "create_transfer_config" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_transfer_config, default_retry=self._method_configs["CreateTransferConfig"].retry, default_timeout=self._method_configs["CreateTransferConfig"].timeout, client_info=self._client_info, ) request = datatransfer_pb2.CreateTransferConfigRequest( parent=parent, transfer_config=transfer_config, authorization_code=authorization_code, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_transfer_config"]( request, retry=retry, timeout=timeout, metadata=metadata )
Updates a data transfer configuration. All fields must be set, even if they are not updated. Example: >>> from google.cloud import bigquery_datatransfer_v1 >>> >>> client = bigquery_datatransfer_v1.DataTransferServiceClient() >>> >>> # TODO: Initialize `transfer_config`: >>> transfer_config = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_transfer_config(transfer_config, update_mask) Args: transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` update_mask (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.FieldMask]): Required list of fields to be updated in this request. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_datatransfer_v1.types.FieldMask` authorization_code (str): Optional OAuth2 authorization code to use with this transfer configuration. If it is provided, the transfer configuration will be associated with the authorizing user. In order to obtain authorization\_code, please make a request to https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=<data\_source\_scopes>&redirect\_uri=<redirect\_uri> - client\_id should be OAuth client\_id of BigQuery DTS API for the given data source returned by ListDataSources method. - data\_source\_scopes are the scopes returned by ListDataSources method. - redirect\_uri is an optional parameter. If not specified, then authorization code is posted to the opener of authorization flow window. Otherwise it will be sent to the redirect uri. A special value of urn:ietf:wg:oauth:2.0:oob means that authorization code should be returned in the title bar of the browser, with the page text prompting the user to copy the code and paste it in the application. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def update_transfer_config( self, transfer_config, update_mask, authorization_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates a data transfer configuration. All fields must be set, even if they are not updated. Example: >>> from google.cloud import bigquery_datatransfer_v1 >>> >>> client = bigquery_datatransfer_v1.DataTransferServiceClient() >>> >>> # TODO: Initialize `transfer_config`: >>> transfer_config = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_transfer_config(transfer_config, update_mask) Args: transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` update_mask (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.FieldMask]): Required list of fields to be updated in this request. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_datatransfer_v1.types.FieldMask` authorization_code (str): Optional OAuth2 authorization code to use with this transfer configuration. If it is provided, the transfer configuration will be associated with the authorizing user. In order to obtain authorization\_code, please make a request to https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=<data\_source\_scopes>&redirect\_uri=<redirect\_uri> - client\_id should be OAuth client\_id of BigQuery DTS API for the given data source returned by ListDataSources method. - data\_source\_scopes are the scopes returned by ListDataSources method. - redirect\_uri is an optional parameter. If not specified, then authorization code is posted to the opener of authorization flow window. Otherwise it will be sent to the redirect uri. A special value of urn:ietf:wg:oauth:2.0:oob means that authorization code should be returned in the title bar of the browser, with the page text prompting the user to copy the code and paste it in the application. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "update_transfer_config" not in self._inner_api_calls: self._inner_api_calls[ "update_transfer_config" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_transfer_config, default_retry=self._method_configs["UpdateTransferConfig"].retry, default_timeout=self._method_configs["UpdateTransferConfig"].timeout, client_info=self._client_info, ) request = datatransfer_pb2.UpdateTransferConfigRequest( transfer_config=transfer_config, update_mask=update_mask, authorization_code=authorization_code, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("transfer_config.name", transfer_config.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["update_transfer_config"]( request, retry=retry, timeout=timeout, metadata=metadata )
Creates transfer runs for a time range [start\_time, end\_time]. For each date - or whatever granularity the data source supports - in the range, one transfer run is created. Note that runs are created per UTC time in the time range. Example: >>> from google.cloud import bigquery_datatransfer_v1 >>> >>> client = bigquery_datatransfer_v1.DataTransferServiceClient() >>> >>> parent = client.project_transfer_config_path('[PROJECT]', '[TRANSFER_CONFIG]') >>> >>> # TODO: Initialize `start_time`: >>> start_time = {} >>> >>> # TODO: Initialize `end_time`: >>> end_time = {} >>> >>> response = client.schedule_transfer_runs(parent, start_time, end_time) Args: parent (str): Transfer configuration name in the form: ``projects/{project_id}/transferConfigs/{config_id}``. start_time (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.Timestamp]): Start time of the range of transfer runs. For example, ``"2017-05-25T00:00:00+00:00"``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_datatransfer_v1.types.Timestamp` end_time (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.Timestamp]): End time of the range of transfer runs. For example, ``"2017-05-30T00:00:00+00:00"``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_datatransfer_v1.types.Timestamp` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.bigquery_datatransfer_v1.types.ScheduleTransferRunsResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def schedule_transfer_runs( self, parent, start_time, end_time, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates transfer runs for a time range [start\_time, end\_time]. For each date - or whatever granularity the data source supports - in the range, one transfer run is created. Note that runs are created per UTC time in the time range. Example: >>> from google.cloud import bigquery_datatransfer_v1 >>> >>> client = bigquery_datatransfer_v1.DataTransferServiceClient() >>> >>> parent = client.project_transfer_config_path('[PROJECT]', '[TRANSFER_CONFIG]') >>> >>> # TODO: Initialize `start_time`: >>> start_time = {} >>> >>> # TODO: Initialize `end_time`: >>> end_time = {} >>> >>> response = client.schedule_transfer_runs(parent, start_time, end_time) Args: parent (str): Transfer configuration name in the form: ``projects/{project_id}/transferConfigs/{config_id}``. start_time (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.Timestamp]): Start time of the range of transfer runs. For example, ``"2017-05-25T00:00:00+00:00"``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_datatransfer_v1.types.Timestamp` end_time (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.Timestamp]): End time of the range of transfer runs. For example, ``"2017-05-30T00:00:00+00:00"``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_datatransfer_v1.types.Timestamp` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.bigquery_datatransfer_v1.types.ScheduleTransferRunsResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "schedule_transfer_runs" not in self._inner_api_calls: self._inner_api_calls[ "schedule_transfer_runs" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.schedule_transfer_runs, default_retry=self._method_configs["ScheduleTransferRuns"].retry, default_timeout=self._method_configs["ScheduleTransferRuns"].timeout, client_info=self._client_info, ) request = datatransfer_pb2.ScheduleTransferRunsRequest( parent=parent, start_time=start_time, end_time=end_time ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["schedule_transfer_runs"]( request, retry=retry, timeout=timeout, metadata=metadata )
Gets the most recent threat list diffs. Example: >>> from google.cloud import webrisk_v1beta1 >>> from google.cloud.webrisk_v1beta1 import enums >>> >>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() >>> >>> # TODO: Initialize `threat_type`: >>> threat_type = enums.ThreatType.THREAT_TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `constraints`: >>> constraints = {} >>> >>> response = client.compute_threat_list_diff(threat_type, constraints) Args: threat_type (~google.cloud.webrisk_v1beta1.types.ThreatType): Required. The ThreatList to update. constraints (Union[dict, ~google.cloud.webrisk_v1beta1.types.Constraints]): The constraints associated with this request. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.webrisk_v1beta1.types.Constraints` version_token (bytes): The current version token of the client for the requested list (the client version that was received from the last successful diff). retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.webrisk_v1beta1.types.ComputeThreatListDiffResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def compute_threat_list_diff( self, threat_type, constraints, version_token=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the most recent threat list diffs. Example: >>> from google.cloud import webrisk_v1beta1 >>> from google.cloud.webrisk_v1beta1 import enums >>> >>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() >>> >>> # TODO: Initialize `threat_type`: >>> threat_type = enums.ThreatType.THREAT_TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `constraints`: >>> constraints = {} >>> >>> response = client.compute_threat_list_diff(threat_type, constraints) Args: threat_type (~google.cloud.webrisk_v1beta1.types.ThreatType): Required. The ThreatList to update. constraints (Union[dict, ~google.cloud.webrisk_v1beta1.types.Constraints]): The constraints associated with this request. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.webrisk_v1beta1.types.Constraints` version_token (bytes): The current version token of the client for the requested list (the client version that was received from the last successful diff). retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.webrisk_v1beta1.types.ComputeThreatListDiffResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "compute_threat_list_diff" not in self._inner_api_calls: self._inner_api_calls[ "compute_threat_list_diff" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.compute_threat_list_diff, default_retry=self._method_configs["ComputeThreatListDiff"].retry, default_timeout=self._method_configs["ComputeThreatListDiff"].timeout, client_info=self._client_info, ) request = webrisk_pb2.ComputeThreatListDiffRequest( threat_type=threat_type, constraints=constraints, version_token=version_token, ) return self._inner_api_calls["compute_threat_list_diff"]( request, retry=retry, timeout=timeout, metadata=metadata )
This method is used to check whether a URI is on a given threatList. Example: >>> from google.cloud import webrisk_v1beta1 >>> from google.cloud.webrisk_v1beta1 import enums >>> >>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() >>> >>> # TODO: Initialize `uri`: >>> uri = '' >>> >>> # TODO: Initialize `threat_types`: >>> threat_types = [] >>> >>> response = client.search_uris(uri, threat_types) Args: uri (str): The URI to be checked for matches. threat_types (list[~google.cloud.webrisk_v1beta1.types.ThreatType]): Required. The ThreatLists to search in. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.webrisk_v1beta1.types.SearchUrisResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def search_uris( self, uri, threat_types, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ This method is used to check whether a URI is on a given threatList. Example: >>> from google.cloud import webrisk_v1beta1 >>> from google.cloud.webrisk_v1beta1 import enums >>> >>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() >>> >>> # TODO: Initialize `uri`: >>> uri = '' >>> >>> # TODO: Initialize `threat_types`: >>> threat_types = [] >>> >>> response = client.search_uris(uri, threat_types) Args: uri (str): The URI to be checked for matches. threat_types (list[~google.cloud.webrisk_v1beta1.types.ThreatType]): Required. The ThreatLists to search in. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.webrisk_v1beta1.types.SearchUrisResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "search_uris" not in self._inner_api_calls: self._inner_api_calls[ "search_uris" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.search_uris, default_retry=self._method_configs["SearchUris"].retry, default_timeout=self._method_configs["SearchUris"].timeout, client_info=self._client_info, ) request = webrisk_pb2.SearchUrisRequest(uri=uri, threat_types=threat_types) return self._inner_api_calls["search_uris"]( request, retry=retry, timeout=timeout, metadata=metadata )
Gets the full hashes that match the requested hash prefix. This is used after a hash prefix is looked up in a threatList and there is a match. The client side threatList only holds partial hashes so the client must query this method to determine if there is a full hash match of a threat. Example: >>> from google.cloud import webrisk_v1beta1 >>> >>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() >>> >>> response = client.search_hashes() Args: hash_prefix (bytes): A hash prefix, consisting of the most significant 4-32 bytes of a SHA256 hash. For JSON requests, this field is base64-encoded. threat_types (list[~google.cloud.webrisk_v1beta1.types.ThreatType]): Required. The ThreatLists to search in. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.webrisk_v1beta1.types.SearchHashesResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def search_hashes( self, hash_prefix=None, threat_types=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the full hashes that match the requested hash prefix. This is used after a hash prefix is looked up in a threatList and there is a match. The client side threatList only holds partial hashes so the client must query this method to determine if there is a full hash match of a threat. Example: >>> from google.cloud import webrisk_v1beta1 >>> >>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() >>> >>> response = client.search_hashes() Args: hash_prefix (bytes): A hash prefix, consisting of the most significant 4-32 bytes of a SHA256 hash. For JSON requests, this field is base64-encoded. threat_types (list[~google.cloud.webrisk_v1beta1.types.ThreatType]): Required. The ThreatLists to search in. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.webrisk_v1beta1.types.SearchHashesResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "search_hashes" not in self._inner_api_calls: self._inner_api_calls[ "search_hashes" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.search_hashes, default_retry=self._method_configs["SearchHashes"].retry, default_timeout=self._method_configs["SearchHashes"].timeout, client_info=self._client_info, ) request = webrisk_pb2.SearchHashesRequest( hash_prefix=hash_prefix, threat_types=threat_types ) return self._inner_api_calls["search_hashes"]( request, retry=retry, timeout=timeout, metadata=metadata )
Return a fully-qualified asset string. def asset_path(cls, organization, asset): """Return a fully-qualified asset string.""" return google.api_core.path_template.expand( "organizations/{organization}/assets/{asset}", organization=organization, asset=asset, )
Return a fully-qualified asset_security_marks string. def asset_security_marks_path(cls, organization, asset): """Return a fully-qualified asset_security_marks string.""" return google.api_core.path_template.expand( "organizations/{organization}/assets/{asset}/securityMarks", organization=organization, asset=asset, )
Return a fully-qualified source string. def source_path(cls, organization, source): """Return a fully-qualified source string.""" return google.api_core.path_template.expand( "organizations/{organization}/sources/{source}", organization=organization, source=source, )
Return a fully-qualified finding string. def finding_path(cls, organization, source, finding): """Return a fully-qualified finding string.""" return google.api_core.path_template.expand( "organizations/{organization}/sources/{source}/findings/{finding}", organization=organization, source=source, finding=finding, )
Creates a source. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> >>> parent = client.organization_path('[ORGANIZATION]') >>> >>> # TODO: Initialize `source`: >>> source = {} >>> >>> response = client.create_source(parent, source) Args: parent (str): Resource name of the new source's parent. Its format should be "organizations/[organization\_id]". source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): The Source being created, only the display\_name and description will be used. All other fields will be ignored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1.types.Source` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.securitycenter_v1.types.Source` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def create_source( self, parent, source, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a source. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> >>> parent = client.organization_path('[ORGANIZATION]') >>> >>> # TODO: Initialize `source`: >>> source = {} >>> >>> response = client.create_source(parent, source) Args: parent (str): Resource name of the new source's parent. Its format should be "organizations/[organization\_id]". source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): The Source being created, only the display\_name and description will be used. All other fields will be ignored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1.types.Source` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.securitycenter_v1.types.Source` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_source" not in self._inner_api_calls: self._inner_api_calls[ "create_source" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_source, default_retry=self._method_configs["CreateSource"].retry, default_timeout=self._method_configs["CreateSource"].timeout, client_info=self._client_info, ) request = securitycenter_service_pb2.CreateSourceRequest( parent=parent, source=source ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_source"]( request, retry=retry, timeout=timeout, metadata=metadata )
Creates a finding. The corresponding source must exist for finding creation to succeed. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> >>> # TODO: Initialize `finding_id`: >>> finding_id = '' >>> >>> # TODO: Initialize `finding`: >>> finding = {} >>> >>> response = client.create_finding(parent, finding_id, finding) Args: parent (str): Resource name of the new finding's parent. Its format should be "organizations/[organization\_id]/sources/[source\_id]". finding_id (str): Unique identifier provided by the client within the parent scope. It must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. finding (Union[dict, ~google.cloud.securitycenter_v1.types.Finding]): The Finding being created. The name and security\_marks will be ignored as they are both output only fields on this resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1.types.Finding` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.securitycenter_v1.types.Finding` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def create_finding( self, parent, finding_id, finding, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a finding. The corresponding source must exist for finding creation to succeed. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> >>> # TODO: Initialize `finding_id`: >>> finding_id = '' >>> >>> # TODO: Initialize `finding`: >>> finding = {} >>> >>> response = client.create_finding(parent, finding_id, finding) Args: parent (str): Resource name of the new finding's parent. Its format should be "organizations/[organization\_id]/sources/[source\_id]". finding_id (str): Unique identifier provided by the client within the parent scope. It must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. finding (Union[dict, ~google.cloud.securitycenter_v1.types.Finding]): The Finding being created. The name and security\_marks will be ignored as they are both output only fields on this resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1.types.Finding` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.securitycenter_v1.types.Finding` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_finding" not in self._inner_api_calls: self._inner_api_calls[ "create_finding" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_finding, default_retry=self._method_configs["CreateFinding"].retry, default_timeout=self._method_configs["CreateFinding"].timeout, client_info=self._client_info, ) request = securitycenter_service_pb2.CreateFindingRequest( parent=parent, finding_id=finding_id, finding=finding ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_finding"]( request, retry=retry, timeout=timeout, metadata=metadata )
Runs asset discovery. The discovery is tracked with a long-running operation. This API can only be called with limited frequency for an organization. If it is called too frequently the caller will receive a TOO\_MANY\_REQUESTS error. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> >>> parent = client.organization_path('[ORGANIZATION]') >>> >>> response = client.run_asset_discovery(parent) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Name of the organization to run asset discovery for. Its format is "organizations/[organization\_id]". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.securitycenter_v1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def run_asset_discovery( self, parent, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Runs asset discovery. The discovery is tracked with a long-running operation. This API can only be called with limited frequency for an organization. If it is called too frequently the caller will receive a TOO\_MANY\_REQUESTS error. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> >>> parent = client.organization_path('[ORGANIZATION]') >>> >>> response = client.run_asset_discovery(parent) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Name of the organization to run asset discovery for. Its format is "organizations/[organization\_id]". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.securitycenter_v1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "run_asset_discovery" not in self._inner_api_calls: self._inner_api_calls[ "run_asset_discovery" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.run_asset_discovery, default_retry=self._method_configs["RunAssetDiscovery"].retry, default_timeout=self._method_configs["RunAssetDiscovery"].timeout, client_info=self._client_info, ) request = securitycenter_service_pb2.RunAssetDiscoveryRequest(parent=parent) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["run_asset_discovery"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=empty_pb2.Empty, )
Updates security marks. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> >>> # TODO: Initialize `security_marks`: >>> security_marks = {} >>> >>> response = client.update_security_marks(security_marks) Args: security_marks (Union[dict, ~google.cloud.securitycenter_v1.types.SecurityMarks]): The security marks resource to update. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1.types.SecurityMarks` update_mask (Union[dict, ~google.cloud.securitycenter_v1.types.FieldMask]): The FieldMask to use when updating the security marks resource. The field mask must not contain duplicate fields. If empty or set to "marks", all marks will be replaced. Individual marks can be updated using "marks.<mark\_key>". If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1.types.FieldMask` start_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): The time at which the updated SecurityMarks take effect. If not set uses current server time. Updates will be applied to the SecurityMarks that are active immediately preceding this time. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1.types.Timestamp` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.securitycenter_v1.types.SecurityMarks` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. def update_security_marks( self, security_marks, update_mask=None, start_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates security marks. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> >>> # TODO: Initialize `security_marks`: >>> security_marks = {} >>> >>> response = client.update_security_marks(security_marks) Args: security_marks (Union[dict, ~google.cloud.securitycenter_v1.types.SecurityMarks]): The security marks resource to update. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1.types.SecurityMarks` update_mask (Union[dict, ~google.cloud.securitycenter_v1.types.FieldMask]): The FieldMask to use when updating the security marks resource. The field mask must not contain duplicate fields. If empty or set to "marks", all marks will be replaced. Individual marks can be updated using "marks.<mark\_key>". If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1.types.FieldMask` start_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): The time at which the updated SecurityMarks take effect. If not set uses current server time. Updates will be applied to the SecurityMarks that are active immediately preceding this time. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1.types.Timestamp` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.securitycenter_v1.types.SecurityMarks` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "update_security_marks" not in self._inner_api_calls: self._inner_api_calls[ "update_security_marks" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_security_marks, default_retry=self._method_configs["UpdateSecurityMarks"].retry, default_timeout=self._method_configs["UpdateSecurityMarks"].timeout, client_info=self._client_info, ) request = securitycenter_service_pb2.UpdateSecurityMarksRequest( security_marks=security_marks, update_mask=update_mask, start_time=start_time, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("security_marks.name", security_marks.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["update_security_marks"]( request, retry=retry, timeout=timeout, metadata=metadata )
Return a page of log entry resources. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list :type projects: list of strings :param projects: project IDs to include. If not passed, defaults to the project bound to the client. :type filter_: str :param filter_: a filter expression. See https://cloud.google.com/logging/docs/view/advanced_filters :type order_by: str :param order_by: One of :data:`~google.cloud.logging.ASCENDING` or :data:`~google.cloud.logging.DESCENDING`. :type page_size: int :param page_size: maximum number of entries to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of entries. If not passed, the API will return the first page of entries. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.entries._BaseEntry` accessible to the current API. def list_entries( self, projects, filter_=None, order_by=None, page_size=None, page_token=None ): """Return a page of log entry resources. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list :type projects: list of strings :param projects: project IDs to include. If not passed, defaults to the project bound to the client. :type filter_: str :param filter_: a filter expression. See https://cloud.google.com/logging/docs/view/advanced_filters :type order_by: str :param order_by: One of :data:`~google.cloud.logging.ASCENDING` or :data:`~google.cloud.logging.DESCENDING`. :type page_size: int :param page_size: maximum number of entries to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of entries. If not passed, the API will return the first page of entries. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.entries._BaseEntry` accessible to the current API. """ extra_params = {"projectIds": projects} if filter_ is not None: extra_params["filter"] = filter_ if order_by is not None: extra_params["orderBy"] = order_by if page_size is not None: extra_params["pageSize"] = page_size path = "/entries:list" # We attach a mutable loggers dictionary so that as Logger # objects are created by entry_from_resource, they can be # re-used by other log entries from the same logger. loggers = {} item_to_value = functools.partial(_item_to_entry, loggers=loggers) iterator = page_iterator.HTTPIterator( client=self._client, api_request=self._client._connection.api_request, path=path, item_to_value=item_to_value, items_key="entries", page_token=page_token, extra_params=extra_params, ) # This method uses POST to make a read-only request. iterator._HTTP_METHOD = "POST" return iterator
API call: log an entry resource via a POST request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write :type entries: sequence of mapping :param entries: the log entry resources to log. :type logger_name: str :param logger_name: name of default logger to which to log the entries; individual entries may override. :type resource: mapping :param resource: default resource to associate with entries; individual entries may override. :type labels: mapping :param labels: default labels to associate with entries; individual entries may override. def write_entries(self, entries, logger_name=None, resource=None, labels=None): """API call: log an entry resource via a POST request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write :type entries: sequence of mapping :param entries: the log entry resources to log. :type logger_name: str :param logger_name: name of default logger to which to log the entries; individual entries may override. :type resource: mapping :param resource: default resource to associate with entries; individual entries may override. :type labels: mapping :param labels: default labels to associate with entries; individual entries may override. """ data = {"entries": list(entries)} if logger_name is not None: data["logName"] = logger_name if resource is not None: data["resource"] = resource if labels is not None: data["labels"] = labels self.api_request(method="POST", path="/entries:write", data=data)
API call: delete all entries in a logger via a DELETE request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete :type project: str :param project: ID of project containing the log entries to delete :type logger_name: str :param logger_name: name of logger containing the log entries to delete def logger_delete(self, project, logger_name): """API call: delete all entries in a logger via a DELETE request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete :type project: str :param project: ID of project containing the log entries to delete :type logger_name: str :param logger_name: name of logger containing the log entries to delete """ path = "/projects/%s/logs/%s" % (project, logger_name) self.api_request(method="DELETE", path=path)
List sinks for the project associated with this client. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/list :type project: str :param project: ID of the project whose sinks are to be listed. :type page_size: int :param page_size: maximum number of sinks to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of sinks. If not passed, the API will return the first page of sinks. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.sink.Sink` accessible to the current API. def list_sinks(self, project, page_size=None, page_token=None): """List sinks for the project associated with this client. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/list :type project: str :param project: ID of the project whose sinks are to be listed. :type page_size: int :param page_size: maximum number of sinks to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of sinks. If not passed, the API will return the first page of sinks. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.sink.Sink` accessible to the current API. """ extra_params = {} if page_size is not None: extra_params["pageSize"] = page_size path = "/projects/%s/sinks" % (project,) return page_iterator.HTTPIterator( client=self._client, api_request=self._client._connection.api_request, path=path, item_to_value=_item_to_sink, items_key="sinks", page_token=page_token, extra_params=extra_params, )
API call: retrieve a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/get :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :rtype: dict :returns: The JSON sink object returned from the API. def sink_get(self, project, sink_name): """API call: retrieve a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/get :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :rtype: dict :returns: The JSON sink object returned from the API. """ target = "/projects/%s/sinks/%s" % (project, sink_name) return self.api_request(method="GET", path=target)
API call: update a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the sink. :type destination: str :param destination: destination URI for the entries exported by the sink. :type unique_writer_identity: bool :param unique_writer_identity: (Optional) determines the kind of IAM identity returned as writer_identity in the new sink. :rtype: dict :returns: The returned (updated) resource. def sink_update( self, project, sink_name, filter_, destination, unique_writer_identity=False ): """API call: update a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the sink. :type destination: str :param destination: destination URI for the entries exported by the sink. :type unique_writer_identity: bool :param unique_writer_identity: (Optional) determines the kind of IAM identity returned as writer_identity in the new sink. :rtype: dict :returns: The returned (updated) resource. """ target = "/projects/%s/sinks/%s" % (project, sink_name) data = {"name": sink_name, "filter": filter_, "destination": destination} query_params = {"uniqueWriterIdentity": unique_writer_identity} return self.api_request( method="PUT", path=target, query_params=query_params, data=data )
API call: delete a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/delete :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink def sink_delete(self, project, sink_name): """API call: delete a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/delete :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink """ target = "/projects/%s/sinks/%s" % (project, sink_name) self.api_request(method="DELETE", path=target)
List metrics for the project associated with this client. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list :type project: str :param project: ID of the project whose metrics are to be listed. :type page_size: int :param page_size: maximum number of metrics to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of metrics. If not passed, the API will return the first page of metrics. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.metric.Metric` accessible to the current API. def list_metrics(self, project, page_size=None, page_token=None): """List metrics for the project associated with this client. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list :type project: str :param project: ID of the project whose metrics are to be listed. :type page_size: int :param page_size: maximum number of metrics to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of metrics. If not passed, the API will return the first page of metrics. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.metric.Metric` accessible to the current API. """ extra_params = {} if page_size is not None: extra_params["pageSize"] = page_size path = "/projects/%s/metrics" % (project,) return page_iterator.HTTPIterator( client=self._client, api_request=self._client._connection.api_request, path=path, item_to_value=_item_to_metric, items_key="metrics", page_token=page_token, extra_params=extra_params, )
API call: create a metric resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/create :type project: str :param project: ID of the project in which to create the metric. :type metric_name: str :param metric_name: the name of the metric :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the metric. :type description: str :param description: description of the metric. def metric_create(self, project, metric_name, filter_, description=None): """API call: create a metric resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/create :type project: str :param project: ID of the project in which to create the metric. :type metric_name: str :param metric_name: the name of the metric :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the metric. :type description: str :param description: description of the metric. """ target = "/projects/%s/metrics" % (project,) data = {"name": metric_name, "filter": filter_, "description": description} self.api_request(method="POST", path=target, data=data)
API call: retrieve a metric resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/get :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric :rtype: dict :returns: The JSON metric object returned from the API. def metric_get(self, project, metric_name): """API call: retrieve a metric resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/get :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric :rtype: dict :returns: The JSON metric object returned from the API. """ target = "/projects/%s/metrics/%s" % (project, metric_name) return self.api_request(method="GET", path=target)
API call: delete a metric resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/delete :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric. def metric_delete(self, project, metric_name): """API call: delete a metric resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/delete :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric. """ target = "/projects/%s/metrics/%s" % (project, metric_name) self.api_request(method="DELETE", path=target)
Add row range to row_ranges list from the row keys For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_row_range_from_keys] :end-before: [END bigtable_row_range_from_keys] :type start_key: bytes :param start_key: (Optional) Start key of the row range. If left empty, will be interpreted as the empty string. :type end_key: bytes :param end_key: (Optional) End key of the row range. If left empty, will be interpreted as the empty string and range will be unbounded on the high end. :type start_inclusive: bool :param start_inclusive: (Optional) Whether the ``start_key`` should be considered inclusive. The default is True (inclusive). :type end_inclusive: bool :param end_inclusive: (Optional) Whether the ``end_key`` should be considered inclusive. The default is False (exclusive). def add_row_range_from_keys( self, start_key=None, end_key=None, start_inclusive=True, end_inclusive=False ): """Add row range to row_ranges list from the row keys For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_row_range_from_keys] :end-before: [END bigtable_row_range_from_keys] :type start_key: bytes :param start_key: (Optional) Start key of the row range. If left empty, will be interpreted as the empty string. :type end_key: bytes :param end_key: (Optional) End key of the row range. If left empty, will be interpreted as the empty string and range will be unbounded on the high end. :type start_inclusive: bool :param start_inclusive: (Optional) Whether the ``start_key`` should be considered inclusive. The default is True (inclusive). :type end_inclusive: bool :param end_inclusive: (Optional) Whether the ``end_key`` should be considered inclusive. The default is False (exclusive). """ row_range = RowRange(start_key, end_key, start_inclusive, end_inclusive) self.row_ranges.append(row_range)
Add row keys and row range to given request message :type message: class:`data_messages_v2_pb2.ReadRowsRequest` :param message: The ``ReadRowsRequest`` protobuf def _update_message_request(self, message): """Add row keys and row range to given request message :type message: class:`data_messages_v2_pb2.ReadRowsRequest` :param message: The ``ReadRowsRequest`` protobuf """ for each in self.row_keys: message.rows.row_keys.append(_to_bytes(each)) for each in self.row_ranges: r_kwrags = each.get_range_kwargs() message.rows.row_ranges.add(**r_kwrags)
A tuple key that uniquely describes this field. Used to compute this instance's hashcode and evaluate equality. Returns: Tuple[str]: The contents of this :class:`.RowRange`. def _key(self): """A tuple key that uniquely describes this field. Used to compute this instance's hashcode and evaluate equality. Returns: Tuple[str]: The contents of this :class:`.RowRange`. """ return (self.start_key, self.start_inclusive, self.end_key, self.end_inclusive)
Convert row range object to dict which can be passed to google.bigtable.v2.RowRange add method. def get_range_kwargs(self): """ Convert row range object to dict which can be passed to google.bigtable.v2.RowRange add method. """ range_kwargs = {} if self.start_key is not None: start_key_key = "start_key_open" if self.start_inclusive: start_key_key = "start_key_closed" range_kwargs[start_key_key] = _to_bytes(self.start_key) if self.end_key is not None: end_key_key = "end_key_open" if self.end_inclusive: end_key_key = "end_key_closed" range_kwargs[end_key_key] = _to_bytes(self.end_key) return range_kwargs