text
stringlengths
81
112k
Convert a log entry protobuf to the native object. .. note:: This method does not have the correct signature to be used as the ``item_to_value`` argument to :class:`~google.api_core.page_iterator.Iterator`. It is intended to be patched with a mutable ``loggers`` argument that can be updated on subsequent calls. For an example, see how the method is used above in :meth:`_LoggingAPI.list_entries`. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type entry_pb: :class:`.log_entry_pb2.LogEntry` :param entry_pb: Log entry protobuf returned from the API. :type loggers: dict :param loggers: A mapping of logger fullnames -> loggers. If the logger that owns the entry is not in ``loggers``, the entry will have a newly-created logger. :rtype: :class:`~google.cloud.logging.entries._BaseEntry` :returns: The next log entry in the page. def _item_to_entry(iterator, entry_pb, loggers): """Convert a log entry protobuf to the native object. .. note:: This method does not have the correct signature to be used as the ``item_to_value`` argument to :class:`~google.api_core.page_iterator.Iterator`. It is intended to be patched with a mutable ``loggers`` argument that can be updated on subsequent calls. For an example, see how the method is used above in :meth:`_LoggingAPI.list_entries`. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type entry_pb: :class:`.log_entry_pb2.LogEntry` :param entry_pb: Log entry protobuf returned from the API. :type loggers: dict :param loggers: A mapping of logger fullnames -> loggers. If the logger that owns the entry is not in ``loggers``, the entry will have a newly-created logger. :rtype: :class:`~google.cloud.logging.entries._BaseEntry` :returns: The next log entry in the page. """ resource = _parse_log_entry(entry_pb) return entry_from_resource(resource, iterator.client, loggers)
Convert a sink protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_sink_pb: :class:`.logging_config_pb2.LogSink` :param log_sink_pb: Sink protobuf returned from the API. :rtype: :class:`~google.cloud.logging.sink.Sink` :returns: The next sink in the page. def _item_to_sink(iterator, log_sink_pb): """Convert a sink protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_sink_pb: :class:`.logging_config_pb2.LogSink` :param log_sink_pb: Sink protobuf returned from the API. :rtype: :class:`~google.cloud.logging.sink.Sink` :returns: The next sink in the page. """ # NOTE: LogSink message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. resource = MessageToDict(log_sink_pb) return Sink.from_api_repr(resource, iterator.client)
Convert a metric protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_metric_pb: :class:`.logging_metrics_pb2.LogMetric` :param log_metric_pb: Metric protobuf returned from the API. :rtype: :class:`~google.cloud.logging.metric.Metric` :returns: The next metric in the page. def _item_to_metric(iterator, log_metric_pb): """Convert a metric protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_metric_pb: :class:`.logging_metrics_pb2.LogMetric` :param log_metric_pb: Metric protobuf returned from the API. :rtype: :class:`~google.cloud.logging.metric.Metric` :returns: The next metric in the page. """ # NOTE: LogMetric message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. resource = MessageToDict(log_metric_pb) return Metric.from_api_repr(resource, iterator.client)
Create an instance of the Logging API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_LoggingAPI` :returns: A metrics API instance with the proper credentials. def make_logging_api(client): """Create an instance of the Logging API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_LoggingAPI` :returns: A metrics API instance with the proper credentials. """ generated = LoggingServiceV2Client( credentials=client._credentials, client_info=_CLIENT_INFO ) return _LoggingAPI(generated, client)
Create an instance of the Metrics API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_MetricsAPI` :returns: A metrics API instance with the proper credentials. def make_metrics_api(client): """Create an instance of the Metrics API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_MetricsAPI` :returns: A metrics API instance with the proper credentials. """ generated = MetricsServiceV2Client( credentials=client._credentials, client_info=_CLIENT_INFO ) return _MetricsAPI(generated, client)
Create an instance of the Sinks API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_SinksAPI` :returns: A metrics API instance with the proper credentials. def make_sinks_api(client): """Create an instance of the Sinks API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_SinksAPI` :returns: A metrics API instance with the proper credentials. """ generated = ConfigServiceV2Client( credentials=client._credentials, client_info=_CLIENT_INFO ) return _SinksAPI(generated, client)
Return a page of log entry resources. :type projects: list of strings :param projects: project IDs to include. If not passed, defaults to the project bound to the API's 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_="", order_by="", page_size=0, page_token=None ): """Return a page of log entry resources. :type projects: list of strings :param projects: project IDs to include. If not passed, defaults to the project bound to the API's 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. """ page_iter = self._gapic_api.list_log_entries( [], project_ids=projects, filter_=filter_, order_by=order_by, page_size=page_size, ) page_iter.client = self._client page_iter.next_page_token = page_token # 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 = {} page_iter.item_to_value = functools.partial(_item_to_entry, loggers=loggers) return page_iter
API call: log an entry resource via a POST request :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 :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. """ partial_success = False entry_pbs = [_log_entry_mapping_to_pb(entry) for entry in entries] self._gapic_api.write_log_entries( entry_pbs, log_name=logger_name, resource=resource, labels=labels, partial_success=partial_success, )
API call: delete all entries in a logger via a DELETE request :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 :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._gapic_api.delete_log(path)
List sinks for the project associated with this client. :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: tuple, (list, str) :returns: list of mappings, plus a "next page token" string: if not None, indicates that more sinks can be retrieved with another call (pass that value as ``page_token``). def list_sinks(self, project, page_size=0, page_token=None): """List sinks for the project associated with this client. :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: tuple, (list, str) :returns: list of mappings, plus a "next page token" string: if not None, indicates that more sinks can be retrieved with another call (pass that value as ``page_token``). """ path = "projects/%s" % (project,) page_iter = self._gapic_api.list_sinks(path, page_size=page_size) page_iter.client = self._client page_iter.next_page_token = page_token page_iter.item_to_value = _item_to_sink return page_iter
API call: create a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/create :type project: str :param project: ID of the project in which to create 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 sink resource returned from the API (converted from a protobuf to a dictionary). def sink_create( self, project, sink_name, filter_, destination, unique_writer_identity=False ): """API call: create a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/create :type project: str :param project: ID of the project in which to create 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 sink resource returned from the API (converted from a protobuf to a dictionary). """ parent = "projects/%s" % (project,) sink_pb = LogSink(name=sink_name, filter=filter_, destination=destination) created_pb = self._gapic_api.create_sink( parent, sink_pb, unique_writer_identity=unique_writer_identity ) return MessageToDict(created_pb)
API call: retrieve a sink resource. :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 sink object returned from the API (converted from a protobuf to a dictionary). def sink_get(self, project, sink_name): """API call: retrieve a sink resource. :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 sink object returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/sinks/%s" % (project, sink_name) sink_pb = self._gapic_api.get_sink(path) # NOTE: LogSink message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(sink_pb)
API call: update a sink resource. :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 sink resource returned from the API (converted from a protobuf to a dictionary). def sink_update( self, project, sink_name, filter_, destination, unique_writer_identity=False ): """API call: update a sink resource. :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 sink resource returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/sinks/%s" % (project, sink_name) sink_pb = LogSink(name=path, filter=filter_, destination=destination) sink_pb = self._gapic_api.update_sink( path, sink_pb, unique_writer_identity=unique_writer_identity ) # NOTE: LogSink message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(sink_pb)
API call: delete a sink resource. :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. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink """ path = "projects/%s/sinks/%s" % (project, sink_name) self._gapic_api.delete_sink(path)
List metrics for the project associated with this client. :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=0, page_token=None): """List metrics for the project associated with this client. :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. """ path = "projects/%s" % (project,) page_iter = self._gapic_api.list_log_metrics(path, page_size=page_size) page_iter.client = self._client page_iter.next_page_token = page_token page_iter.item_to_value = _item_to_metric return page_iter
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): """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. """ parent = "projects/%s" % (project,) metric_pb = LogMetric(name=metric_name, filter=filter_, description=description) self._gapic_api.create_log_metric(parent, metric_pb)
API call: retrieve a metric resource. :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 metric object returned from the API (converted from a protobuf to a dictionary). def metric_get(self, project, metric_name): """API call: retrieve a metric resource. :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 metric object returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/metrics/%s" % (project, metric_name) metric_pb = self._gapic_api.get_log_metric(path) # NOTE: LogMetric message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(metric_pb)
API call: update a metric resource. :type project: str :param project: ID of the project containing 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. :rtype: dict :returns: The metric object returned from the API (converted from a protobuf to a dictionary). def metric_update(self, project, metric_name, filter_, description): """API call: update a metric resource. :type project: str :param project: ID of the project containing 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. :rtype: dict :returns: The metric object returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/metrics/%s" % (project, metric_name) metric_pb = LogMetric(name=path, filter=filter_, description=description) metric_pb = self._gapic_api.update_log_metric(path, metric_pb) # NOTE: LogMetric message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(metric_pb)
API call: delete a metric resource. :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. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric """ path = "projects/%s/metrics/%s" % (project, metric_name) self._gapic_api.delete_log_metric(path)
Return a fully-qualified tenant string. def tenant_path(cls, project, tenant): """Return a fully-qualified tenant string.""" return google.api_core.path_template.expand( "projects/{project}/tenants/{tenant}", project=project, tenant=tenant )
Creates a new tenant entity. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `tenant`: >>> tenant = {} >>> >>> response = client.create_tenant(parent, tenant) Args: parent (str): Required. Resource name of the project under which the tenant is created. The format is "projects/{project\_id}", for example, "projects/api-test-project". tenant (Union[dict, ~google.cloud.talent_v4beta1.types.Tenant]): Required. The tenant to be created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Tenant` 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.talent_v4beta1.types.Tenant` 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_tenant( self, parent, tenant, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new tenant entity. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `tenant`: >>> tenant = {} >>> >>> response = client.create_tenant(parent, tenant) Args: parent (str): Required. Resource name of the project under which the tenant is created. The format is "projects/{project\_id}", for example, "projects/api-test-project". tenant (Union[dict, ~google.cloud.talent_v4beta1.types.Tenant]): Required. The tenant to be created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Tenant` 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.talent_v4beta1.types.Tenant` 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_tenant" not in self._inner_api_calls: self._inner_api_calls[ "create_tenant" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_tenant, default_retry=self._method_configs["CreateTenant"].retry, default_timeout=self._method_configs["CreateTenant"].timeout, client_info=self._client_info, ) request = tenant_service_pb2.CreateTenantRequest(parent=parent, tenant=tenant) return self._inner_api_calls["create_tenant"]( request, retry=retry, timeout=timeout, metadata=metadata )
Retrieves specified tenant. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> name = client.tenant_path('[PROJECT]', '[TENANT]') >>> >>> response = client.get_tenant(name) Args: name (str): Required. The resource name of the tenant to be retrieved. The format is "projects/{project\_id}/tenants/{tenant\_id}", for example, "projects/api-test-project/tenants/foo". 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.talent_v4beta1.types.Tenant` 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 get_tenant( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Retrieves specified tenant. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> name = client.tenant_path('[PROJECT]', '[TENANT]') >>> >>> response = client.get_tenant(name) Args: name (str): Required. The resource name of the tenant to be retrieved. The format is "projects/{project\_id}/tenants/{tenant\_id}", for example, "projects/api-test-project/tenants/foo". 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.talent_v4beta1.types.Tenant` 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 "get_tenant" not in self._inner_api_calls: self._inner_api_calls[ "get_tenant" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_tenant, default_retry=self._method_configs["GetTenant"].retry, default_timeout=self._method_configs["GetTenant"].timeout, client_info=self._client_info, ) request = tenant_service_pb2.GetTenantRequest(name=name) return self._inner_api_calls["get_tenant"]( request, retry=retry, timeout=timeout, metadata=metadata )
Updates specified tenant. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> # TODO: Initialize `tenant`: >>> tenant = {} >>> >>> response = client.update_tenant(tenant) Args: tenant (Union[dict, ~google.cloud.talent_v4beta1.types.Tenant]): Required. The tenant resource to replace the current resource in the system. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Tenant` update_mask (Union[dict, ~google.cloud.talent_v4beta1.types.FieldMask]): Optional but strongly recommended for the best service experience. If ``update_mask`` is provided, only the specified fields in ``tenant`` are updated. Otherwise all the fields are updated. A field mask to specify the tenant fields to be updated. Only top level fields of ``Tenant`` are supported. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.FieldMask` 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.talent_v4beta1.types.Tenant` 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_tenant( self, tenant, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates specified tenant. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> # TODO: Initialize `tenant`: >>> tenant = {} >>> >>> response = client.update_tenant(tenant) Args: tenant (Union[dict, ~google.cloud.talent_v4beta1.types.Tenant]): Required. The tenant resource to replace the current resource in the system. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Tenant` update_mask (Union[dict, ~google.cloud.talent_v4beta1.types.FieldMask]): Optional but strongly recommended for the best service experience. If ``update_mask`` is provided, only the specified fields in ``tenant`` are updated. Otherwise all the fields are updated. A field mask to specify the tenant fields to be updated. Only top level fields of ``Tenant`` are supported. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.FieldMask` 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.talent_v4beta1.types.Tenant` 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_tenant" not in self._inner_api_calls: self._inner_api_calls[ "update_tenant" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_tenant, default_retry=self._method_configs["UpdateTenant"].retry, default_timeout=self._method_configs["UpdateTenant"].timeout, client_info=self._client_info, ) request = tenant_service_pb2.UpdateTenantRequest( tenant=tenant, update_mask=update_mask ) return self._inner_api_calls["update_tenant"]( request, retry=retry, timeout=timeout, metadata=metadata )
Apply a list of decorators to a given function. ``decorators`` may contain items that are ``None`` or ``False`` which will be ignored. def _apply_decorators(func, decorators): """Apply a list of decorators to a given function. ``decorators`` may contain items that are ``None`` or ``False`` which will be ignored. """ decorators = filter(_is_not_none_or_false, reversed(decorators)) for decorator in decorators: func = decorator(func) return func
Determines how timeout should be applied to a wrapped method. Args: default_timeout (Optional[Timeout]): The default timeout specified at method creation time. specified_timeout (Optional[Timeout]): The timeout specified at invocation time. If :attr:`DEFAULT`, this will be set to the ``default_timeout``. retry (Optional[Retry]): The retry specified at invocation time. Returns: Optional[Timeout]: The timeout to apply to the method or ``None``. def _determine_timeout(default_timeout, specified_timeout, retry): """Determines how timeout should be applied to a wrapped method. Args: default_timeout (Optional[Timeout]): The default timeout specified at method creation time. specified_timeout (Optional[Timeout]): The timeout specified at invocation time. If :attr:`DEFAULT`, this will be set to the ``default_timeout``. retry (Optional[Retry]): The retry specified at invocation time. Returns: Optional[Timeout]: The timeout to apply to the method or ``None``. """ if specified_timeout is DEFAULT: specified_timeout = default_timeout if specified_timeout is default_timeout: # If timeout is the default and the default timeout is exponential and # a non-default retry is specified, make sure the timeout's deadline # matches the retry's. This handles the case where the user leaves # the timeout default but specifies a lower deadline via the retry. if ( retry and retry is not DEFAULT and isinstance(default_timeout, timeout.ExponentialTimeout) ): return default_timeout.with_deadline(retry._deadline) else: return default_timeout # If timeout is specified as a number instead of a Timeout instance, # convert it to a ConstantTimeout. if isinstance(specified_timeout, (int, float)): return timeout.ConstantTimeout(specified_timeout) else: return specified_timeout
Wrap an RPC method with common behavior. This applies common error wrapping, retry, and timeout behavior a function. The wrapped function will take optional ``retry`` and ``timeout`` arguments. For example:: import google.api_core.gapic_v1.method from google.api_core import retry from google.api_core import timeout # The original RPC method. def get_topic(name, timeout=None): request = publisher_v2.GetTopicRequest(name=name) return publisher_stub.GetTopic(request, timeout=timeout) default_retry = retry.Retry(deadline=60) default_timeout = timeout.Timeout(deadline=60) wrapped_get_topic = google.api_core.gapic_v1.method.wrap_method( get_topic, default_retry) # Execute get_topic with default retry and timeout: response = wrapped_get_topic() # Execute get_topic without doing any retying but with the default # timeout: response = wrapped_get_topic(retry=None) # Execute get_topic but only retry on 5xx errors: my_retry = retry.Retry(retry.if_exception_type( exceptions.InternalServerError)) response = wrapped_get_topic(retry=my_retry) The way this works is by late-wrapping the given function with the retry and timeout decorators. Essentially, when ``wrapped_get_topic()`` is called: * ``get_topic()`` is first wrapped with the ``timeout`` into ``get_topic_with_timeout``. * ``get_topic_with_timeout`` is wrapped with the ``retry`` into ``get_topic_with_timeout_and_retry()``. * The final ``get_topic_with_timeout_and_retry`` is called passing through the ``args`` and ``kwargs``. The callstack is therefore:: method.__call__() -> Retry.__call__() -> Timeout.__call__() -> wrap_errors() -> get_topic() Note that if ``timeout`` or ``retry`` is ``None``, then they are not applied to the function. For example, ``wrapped_get_topic(timeout=None, retry=None)`` is more or less equivalent to just calling ``get_topic`` but with error re-mapping. Args: func (Callable[Any]): The function to wrap. It should accept an optional ``timeout`` argument. If ``metadata`` is not ``None``, it should accept a ``metadata`` argument. default_retry (Optional[google.api_core.Retry]): The default retry strategy. If ``None``, the method will not retry by default. default_timeout (Optional[google.api_core.Timeout]): The default timeout strategy. Can also be specified as an int or float. If ``None``, the method will not have timeout specified by default. client_info (Optional[google.api_core.gapic_v1.client_info.ClientInfo]): Client information used to create a user-agent string that's passed as gRPC metadata to the method. If unspecified, then a sane default will be used. If ``None``, then no user agent metadata will be provided to the RPC method. Returns: Callable: A new callable that takes optional ``retry`` and ``timeout`` arguments and applies the common error mapping, retry, timeout, and metadata behavior to the low-level RPC method. def wrap_method( func, default_retry=None, default_timeout=None, client_info=client_info.DEFAULT_CLIENT_INFO, ): """Wrap an RPC method with common behavior. This applies common error wrapping, retry, and timeout behavior a function. The wrapped function will take optional ``retry`` and ``timeout`` arguments. For example:: import google.api_core.gapic_v1.method from google.api_core import retry from google.api_core import timeout # The original RPC method. def get_topic(name, timeout=None): request = publisher_v2.GetTopicRequest(name=name) return publisher_stub.GetTopic(request, timeout=timeout) default_retry = retry.Retry(deadline=60) default_timeout = timeout.Timeout(deadline=60) wrapped_get_topic = google.api_core.gapic_v1.method.wrap_method( get_topic, default_retry) # Execute get_topic with default retry and timeout: response = wrapped_get_topic() # Execute get_topic without doing any retying but with the default # timeout: response = wrapped_get_topic(retry=None) # Execute get_topic but only retry on 5xx errors: my_retry = retry.Retry(retry.if_exception_type( exceptions.InternalServerError)) response = wrapped_get_topic(retry=my_retry) The way this works is by late-wrapping the given function with the retry and timeout decorators. Essentially, when ``wrapped_get_topic()`` is called: * ``get_topic()`` is first wrapped with the ``timeout`` into ``get_topic_with_timeout``. * ``get_topic_with_timeout`` is wrapped with the ``retry`` into ``get_topic_with_timeout_and_retry()``. * The final ``get_topic_with_timeout_and_retry`` is called passing through the ``args`` and ``kwargs``. The callstack is therefore:: method.__call__() -> Retry.__call__() -> Timeout.__call__() -> wrap_errors() -> get_topic() Note that if ``timeout`` or ``retry`` is ``None``, then they are not applied to the function. For example, ``wrapped_get_topic(timeout=None, retry=None)`` is more or less equivalent to just calling ``get_topic`` but with error re-mapping. Args: func (Callable[Any]): The function to wrap. It should accept an optional ``timeout`` argument. If ``metadata`` is not ``None``, it should accept a ``metadata`` argument. default_retry (Optional[google.api_core.Retry]): The default retry strategy. If ``None``, the method will not retry by default. default_timeout (Optional[google.api_core.Timeout]): The default timeout strategy. Can also be specified as an int or float. If ``None``, the method will not have timeout specified by default. client_info (Optional[google.api_core.gapic_v1.client_info.ClientInfo]): Client information used to create a user-agent string that's passed as gRPC metadata to the method. If unspecified, then a sane default will be used. If ``None``, then no user agent metadata will be provided to the RPC method. Returns: Callable: A new callable that takes optional ``retry`` and ``timeout`` arguments and applies the common error mapping, retry, timeout, and metadata behavior to the low-level RPC method. """ func = grpc_helpers.wrap_errors(func) if client_info is not None: user_agent_metadata = [client_info.to_grpc_metadata()] else: user_agent_metadata = None return general_helpers.wraps(func)( _GapicCallable( func, default_retry, default_timeout, metadata=user_agent_metadata ) )
Pre-flight ``Bucket`` name validation. :type name: str or :data:`NoneType` :param name: Proposed bucket name. :rtype: str or :data:`NoneType` :returns: ``name`` if valid. def _validate_name(name): """Pre-flight ``Bucket`` name validation. :type name: str or :data:`NoneType` :param name: Proposed bucket name. :rtype: str or :data:`NoneType` :returns: ``name`` if valid. """ if name is None: return # The first and las characters must be alphanumeric. if not all([name[0].isalnum(), name[-1].isalnum()]): raise ValueError("Bucket names must start and end with a number or letter.") return name
Create a property descriptor around the :class:`_PropertyMixin` helpers. def _scalar_property(fieldname): """Create a property descriptor around the :class:`_PropertyMixin` helpers. """ def _getter(self): """Scalar property getter.""" return self._properties.get(fieldname) def _setter(self, value): """Scalar property setter.""" self._patch_property(fieldname, value) return property(_getter, _setter)
Read blocks from a buffer and update a hash with them. :type buffer_object: bytes buffer :param buffer_object: Buffer containing bytes used to update a hash object. :type hash_obj: object that implements update :param hash_obj: A hash object (MD5 or CRC32-C). :type digest_block_size: int :param digest_block_size: The block size to write to the hash. Defaults to 8192. def _write_buffer_to_hash(buffer_object, hash_obj, digest_block_size=8192): """Read blocks from a buffer and update a hash with them. :type buffer_object: bytes buffer :param buffer_object: Buffer containing bytes used to update a hash object. :type hash_obj: object that implements update :param hash_obj: A hash object (MD5 or CRC32-C). :type digest_block_size: int :param digest_block_size: The block size to write to the hash. Defaults to 8192. """ block = buffer_object.read(digest_block_size) while len(block) > 0: hash_obj.update(block) # Update the block for the next iteration. block = buffer_object.read(digest_block_size)
Get MD5 hash of bytes (as base64). :type buffer_object: bytes buffer :param buffer_object: Buffer containing bytes used to compute an MD5 hash (as base64). :rtype: str :returns: A base64 encoded digest of the MD5 hash. def _base64_md5hash(buffer_object): """Get MD5 hash of bytes (as base64). :type buffer_object: bytes buffer :param buffer_object: Buffer containing bytes used to compute an MD5 hash (as base64). :rtype: str :returns: A base64 encoded digest of the MD5 hash. """ hash_obj = md5() _write_buffer_to_hash(buffer_object, hash_obj) digest_bytes = hash_obj.digest() return base64.b64encode(digest_bytes)
Reload properties from Cloud Storage. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. def reload(self, client=None): """Reload properties from Cloud Storage. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. """ client = self._require_client(client) query_params = self._query_params # Pass only '?projection=noAcl' here because 'acl' and related # are handled via custom endpoints. query_params["projection"] = "noAcl" api_response = client._connection.api_request( method="GET", path=self.path, query_params=query_params, headers=self._encryption_headers(), _target_object=self, ) self._set_properties(api_response)
Update field of this object's properties. This method will only update the field provided and will not touch the other fields. It **will not** reload the properties from the server. The behavior is local only and syncing occurs via :meth:`patch`. :type name: str :param name: The field name to update. :type value: object :param value: The value being updated. def _patch_property(self, name, value): """Update field of this object's properties. This method will only update the field provided and will not touch the other fields. It **will not** reload the properties from the server. The behavior is local only and syncing occurs via :meth:`patch`. :type name: str :param name: The field name to update. :type value: object :param value: The value being updated. """ self._changes.add(name) self._properties[name] = value
Sends all changed properties in a PATCH request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. def patch(self, client=None): """Sends all changed properties in a PATCH request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. """ client = self._require_client(client) query_params = self._query_params # Pass '?projection=full' here because 'PATCH' documented not # to work properly w/ 'noAcl'. query_params["projection"] = "full" update_properties = {key: self._properties[key] for key in self._changes} # Make the API call. api_response = client._connection.api_request( method="PATCH", path=self.path, data=update_properties, query_params=query_params, _target_object=self, ) self._set_properties(api_response)
Sends all properties in a PUT request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. def update(self, client=None): """Sends all properties in a PUT request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. """ client = self._require_client(client) query_params = self._query_params query_params["projection"] = "full" api_response = client._connection.api_request( method="PUT", path=self.path, data=self._properties, query_params=query_params, _target_object=self, ) self._set_properties(api_response)
Start a thread to dispatch requests queued up by callbacks. Spawns a thread to run :meth:`dispatch_callback`. def start(self): """Start a thread to dispatch requests queued up by callbacks. Spawns a thread to run :meth:`dispatch_callback`. """ with self._operational_lock: if self._thread is not None: raise ValueError("Dispatcher is already running.") flow_control = self._manager.flow_control worker = helper_threads.QueueCallbackWorker( self._queue, self.dispatch_callback, max_items=flow_control.max_request_batch_size, max_latency=flow_control.max_request_batch_latency, ) # Create and start the helper thread. thread = threading.Thread(name=_CALLBACK_WORKER_NAME, target=worker) thread.daemon = True thread.start() _LOGGER.debug("Started helper thread %s", thread.name) self._thread = thread
Map the callback request to the appropriate gRPC request. Args: action (str): The method to be invoked. kwargs (Dict[str, Any]): The keyword arguments for the method specified by ``action``. Raises: ValueError: If ``action`` isn't one of the expected actions "ack", "drop", "lease", "modify_ack_deadline" or "nack". def dispatch_callback(self, items): """Map the callback request to the appropriate gRPC request. Args: action (str): The method to be invoked. kwargs (Dict[str, Any]): The keyword arguments for the method specified by ``action``. Raises: ValueError: If ``action`` isn't one of the expected actions "ack", "drop", "lease", "modify_ack_deadline" or "nack". """ if not self._manager.is_active: return batched_commands = collections.defaultdict(list) for item in items: batched_commands[item.__class__].append(item) _LOGGER.debug("Handling %d batched requests", len(items)) if batched_commands[requests.LeaseRequest]: self.lease(batched_commands.pop(requests.LeaseRequest)) if batched_commands[requests.ModAckRequest]: self.modify_ack_deadline(batched_commands.pop(requests.ModAckRequest)) # Note: Drop and ack *must* be after lease. It's possible to get both # the lease the and ack/drop request in the same batch. if batched_commands[requests.AckRequest]: self.ack(batched_commands.pop(requests.AckRequest)) if batched_commands[requests.NackRequest]: self.nack(batched_commands.pop(requests.NackRequest)) if batched_commands[requests.DropRequest]: self.drop(batched_commands.pop(requests.DropRequest))
Acknowledge the given messages. Args: items(Sequence[AckRequest]): The items to acknowledge. def ack(self, items): """Acknowledge the given messages. Args: items(Sequence[AckRequest]): The items to acknowledge. """ # If we got timing information, add it to the histogram. for item in items: time_to_ack = item.time_to_ack if time_to_ack is not None: self._manager.ack_histogram.add(time_to_ack) ack_ids = [item.ack_id for item in items] request = types.StreamingPullRequest(ack_ids=ack_ids) self._manager.send(request) # Remove the message from lease management. self.drop(items)
Remove the given messages from lease management. Args: items(Sequence[DropRequest]): The items to drop. def drop(self, items): """Remove the given messages from lease management. Args: items(Sequence[DropRequest]): The items to drop. """ self._manager.leaser.remove(items) self._manager.maybe_resume_consumer()
Add the given messages to lease management. Args: items(Sequence[LeaseRequest]): The items to lease. def lease(self, items): """Add the given messages to lease management. Args: items(Sequence[LeaseRequest]): The items to lease. """ self._manager.leaser.add(items) self._manager.maybe_pause_consumer()
Modify the ack deadline for the given messages. Args: items(Sequence[ModAckRequest]): The items to modify. def modify_ack_deadline(self, items): """Modify the ack deadline for the given messages. Args: items(Sequence[ModAckRequest]): The items to modify. """ ack_ids = [item.ack_id for item in items] seconds = [item.seconds for item in items] request = types.StreamingPullRequest( modify_deadline_ack_ids=ack_ids, modify_deadline_seconds=seconds ) self._manager.send(request)
Explicitly deny receipt of messages. Args: items(Sequence[NackRequest]): The items to deny. def nack(self, items): """Explicitly deny receipt of messages. Args: items(Sequence[NackRequest]): The items to deny. """ self.modify_ack_deadline( [requests.ModAckRequest(ack_id=item.ack_id, seconds=0) for item in items] ) self.drop([requests.DropRequest(*item) for item in items])
Submits a job to a cluster. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job`: >>> job = {} >>> >>> response = client.submit_job(project_id, region, job) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job (Union[dict, ~google.cloud.dataproc_v1beta2.types.Job]): Required. The job resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Job` request_id (str): Optional. A unique id used to identify the request. If the server receives two ``SubmitJobRequest`` requests with the same id, then the second request will be ignored and the first ``Job`` created and stored in the backend is returned. It is recommended to always set this value to a `UUID <https://en.wikipedia.org/wiki/Universally_unique_identifier>`__. The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (\_), and hyphens (-). The maximum length is 40 characters. 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.dataproc_v1beta2.types.Job` 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 submit_job( self, project_id, region, job, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Submits a job to a cluster. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job`: >>> job = {} >>> >>> response = client.submit_job(project_id, region, job) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job (Union[dict, ~google.cloud.dataproc_v1beta2.types.Job]): Required. The job resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Job` request_id (str): Optional. A unique id used to identify the request. If the server receives two ``SubmitJobRequest`` requests with the same id, then the second request will be ignored and the first ``Job`` created and stored in the backend is returned. It is recommended to always set this value to a `UUID <https://en.wikipedia.org/wiki/Universally_unique_identifier>`__. The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (\_), and hyphens (-). The maximum length is 40 characters. 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.dataproc_v1beta2.types.Job` 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 "submit_job" not in self._inner_api_calls: self._inner_api_calls[ "submit_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.submit_job, default_retry=self._method_configs["SubmitJob"].retry, default_timeout=self._method_configs["SubmitJob"].timeout, client_info=self._client_info, ) request = jobs_pb2.SubmitJobRequest( project_id=project_id, region=region, job=job, request_id=request_id ) return self._inner_api_calls["submit_job"]( request, retry=retry, timeout=timeout, metadata=metadata )
Updates a job in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job_id`: >>> job_id = '' >>> >>> # TODO: Initialize `job`: >>> job = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_job(project_id, region, job_id, job, update_mask) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job_id (str): Required. The job ID. job (Union[dict, ~google.cloud.dataproc_v1beta2.types.Job]): Required. The changes to the job. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Job` update_mask (Union[dict, ~google.cloud.dataproc_v1beta2.types.FieldMask]): Required. Specifies the path, relative to Job, of the field to update. For example, to update the labels of a Job the update\_mask parameter would be specified as labels, and the ``PATCH`` request body would specify the new value. Note: Currently, labels is the only field that can be updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.FieldMask` 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.dataproc_v1beta2.types.Job` 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_job( self, project_id, region, job_id, job, update_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates a job in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job_id`: >>> job_id = '' >>> >>> # TODO: Initialize `job`: >>> job = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_job(project_id, region, job_id, job, update_mask) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job_id (str): Required. The job ID. job (Union[dict, ~google.cloud.dataproc_v1beta2.types.Job]): Required. The changes to the job. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Job` update_mask (Union[dict, ~google.cloud.dataproc_v1beta2.types.FieldMask]): Required. Specifies the path, relative to Job, of the field to update. For example, to update the labels of a Job the update\_mask parameter would be specified as labels, and the ``PATCH`` request body would specify the new value. Note: Currently, labels is the only field that can be updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.FieldMask` 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.dataproc_v1beta2.types.Job` 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_job" not in self._inner_api_calls: self._inner_api_calls[ "update_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_job, default_retry=self._method_configs["UpdateJob"].retry, default_timeout=self._method_configs["UpdateJob"].timeout, client_info=self._client_info, ) request = jobs_pb2.UpdateJobRequest( project_id=project_id, region=region, job_id=job_id, job=job, update_mask=update_mask, ) return self._inner_api_calls["update_job"]( request, retry=retry, timeout=timeout, metadata=metadata )
Starts a job cancellation request. To access the job resource after cancellation, call `regions/{region}/jobs.list <https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/list>`__ or `regions/{region}/jobs.get <https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/get>`__. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job_id`: >>> job_id = '' >>> >>> response = client.cancel_job(project_id, region, job_id) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job_id (str): Required. The job 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.dataproc_v1beta2.types.Job` 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 cancel_job( self, project_id, region, job_id, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a job cancellation request. To access the job resource after cancellation, call `regions/{region}/jobs.list <https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/list>`__ or `regions/{region}/jobs.get <https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/get>`__. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job_id`: >>> job_id = '' >>> >>> response = client.cancel_job(project_id, region, job_id) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job_id (str): Required. The job 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.dataproc_v1beta2.types.Job` 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 "cancel_job" not in self._inner_api_calls: self._inner_api_calls[ "cancel_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.cancel_job, default_retry=self._method_configs["CancelJob"].retry, default_timeout=self._method_configs["CancelJob"].timeout, client_info=self._client_info, ) request = jobs_pb2.CancelJobRequest( project_id=project_id, region=region, job_id=job_id ) return self._inner_api_calls["cancel_job"]( request, retry=retry, timeout=timeout, metadata=metadata )
Return a fully-qualified instance string. def instance_path(cls, project, instance): """Return a fully-qualified instance string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}", project=project, instance=instance, )
Return a fully-qualified app_profile string. def app_profile_path(cls, project, instance, app_profile): """Return a fully-qualified app_profile string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/appProfiles/{app_profile}", project=project, instance=instance, app_profile=app_profile, )
Return a fully-qualified cluster string. def cluster_path(cls, project, instance, cluster): """Return a fully-qualified cluster string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/clusters/{cluster}", project=project, instance=instance, cluster=cluster, )
Lists information about instances in a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.list_instances(parent) Args: parent (str): The unique name of the project for which a list of instances is requested. Values are of the form ``projects/<project>``. page_token (str): DEPRECATED: This field is unused and ignored. 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.bigtable_admin_v2.types.ListInstancesResponse` 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_instances( self, parent, page_token=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists information about instances in a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.list_instances(parent) Args: parent (str): The unique name of the project for which a list of instances is requested. Values are of the form ``projects/<project>``. page_token (str): DEPRECATED: This field is unused and ignored. 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.bigtable_admin_v2.types.ListInstancesResponse` 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_instances" not in self._inner_api_calls: self._inner_api_calls[ "list_instances" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_instances, default_retry=self._method_configs["ListInstances"].retry, default_timeout=self._method_configs["ListInstances"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.ListInstancesRequest( parent=parent, page_token=page_token ) 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["list_instances"]( request, retry=retry, timeout=timeout, metadata=metadata )
Updates an instance within a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> from google.cloud.bigtable_admin_v2 import enums >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `display_name`: >>> display_name = '' >>> >>> # TODO: Initialize `type_`: >>> type_ = enums.Instance.Type.TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `labels`: >>> labels = {} >>> >>> response = client.update_instance(name, display_name, type_, labels) Args: name (str): (``OutputOnly``) The unique name of the instance. Values are of the form ``projects/<project>/instances/[a-z][a-z0-9\\-]+[a-z0-9]``. display_name (str): The descriptive name for this instance as it appears in UIs. Can be changed at any time, but should be kept globally unique to avoid confusion. type_ (~google.cloud.bigtable_admin_v2.types.Type): The type of the instance. Defaults to ``PRODUCTION``. labels (dict[str -> str]): Labels are a flexible and lightweight mechanism for organizing cloud resources into groups that reflect a customer's organizational needs and deployment strategies. They can be used to filter resources and aggregate metrics. - Label keys must be between 1 and 63 characters long and must conform to the regular expression: ``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}``. - Label values must be between 0 and 63 characters long and must conform to the regular expression: ``[\p{Ll}\p{Lo}\p{N}_-]{0,63}``. - No more than 64 labels can be associated with a given resource. - Keys and values must both be under 128 bytes. state (~google.cloud.bigtable_admin_v2.types.State): (``OutputOnly``) The current state of the instance. 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.bigtable_admin_v2.types.Instance` 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_instance( self, name, display_name, type_, labels, state=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an instance within a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> from google.cloud.bigtable_admin_v2 import enums >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `display_name`: >>> display_name = '' >>> >>> # TODO: Initialize `type_`: >>> type_ = enums.Instance.Type.TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `labels`: >>> labels = {} >>> >>> response = client.update_instance(name, display_name, type_, labels) Args: name (str): (``OutputOnly``) The unique name of the instance. Values are of the form ``projects/<project>/instances/[a-z][a-z0-9\\-]+[a-z0-9]``. display_name (str): The descriptive name for this instance as it appears in UIs. Can be changed at any time, but should be kept globally unique to avoid confusion. type_ (~google.cloud.bigtable_admin_v2.types.Type): The type of the instance. Defaults to ``PRODUCTION``. labels (dict[str -> str]): Labels are a flexible and lightweight mechanism for organizing cloud resources into groups that reflect a customer's organizational needs and deployment strategies. They can be used to filter resources and aggregate metrics. - Label keys must be between 1 and 63 characters long and must conform to the regular expression: ``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}``. - Label values must be between 0 and 63 characters long and must conform to the regular expression: ``[\p{Ll}\p{Lo}\p{N}_-]{0,63}``. - No more than 64 labels can be associated with a given resource. - Keys and values must both be under 128 bytes. state (~google.cloud.bigtable_admin_v2.types.State): (``OutputOnly``) The current state of the instance. 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.bigtable_admin_v2.types.Instance` 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_instance" not in self._inner_api_calls: self._inner_api_calls[ "update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_instance, default_retry=self._method_configs["UpdateInstance"].retry, default_timeout=self._method_configs["UpdateInstance"].timeout, client_info=self._client_info, ) request = instance_pb2.Instance( name=name, display_name=display_name, type=type_, labels=labels, state=state ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", 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_instance"]( request, retry=retry, timeout=timeout, metadata=metadata )
Partially updates an instance within a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.partial_update_instance(instance, update_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.bigtable_admin_v2.types.Instance]): The Instance which will (partially) replace the current value. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Instance` update_mask (Union[dict, ~google.cloud.bigtable_admin_v2.types.FieldMask]): The subset of Instance fields which should be replaced. Must be explicitly set. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.FieldMask` 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.bigtable_admin_v2.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 partial_update_instance( self, instance, update_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Partially updates an instance within a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.partial_update_instance(instance, update_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.bigtable_admin_v2.types.Instance]): The Instance which will (partially) replace the current value. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Instance` update_mask (Union[dict, ~google.cloud.bigtable_admin_v2.types.FieldMask]): The subset of Instance fields which should be replaced. Must be explicitly set. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.FieldMask` 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.bigtable_admin_v2.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 "partial_update_instance" not in self._inner_api_calls: self._inner_api_calls[ "partial_update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.partial_update_instance, default_retry=self._method_configs["PartialUpdateInstance"].retry, default_timeout=self._method_configs["PartialUpdateInstance"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.PartialUpdateInstanceRequest( instance=instance, update_mask=update_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("instance.name", instance.name)] 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["partial_update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instance_pb2.Instance, metadata_type=bigtable_instance_admin_pb2.UpdateInstanceMetadata, )
Creates a cluster within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `cluster_id`: >>> cluster_id = '' >>> >>> # TODO: Initialize `cluster`: >>> cluster = {} >>> >>> response = client.create_cluster(parent, cluster_id, cluster) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): The unique name of the instance in which to create the new cluster. Values are of the form ``projects/<project>/instances/<instance>``. cluster_id (str): The ID to be used when referring to the new cluster within its instance, e.g., just ``mycluster`` rather than ``projects/myproject/instances/myinstance/clusters/mycluster``. cluster (Union[dict, ~google.cloud.bigtable_admin_v2.types.Cluster]): The cluster to be created. Fields marked ``OutputOnly`` must be left blank. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Cluster` 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.bigtable_admin_v2.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 create_cluster( self, parent, cluster_id, cluster, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a cluster within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `cluster_id`: >>> cluster_id = '' >>> >>> # TODO: Initialize `cluster`: >>> cluster = {} >>> >>> response = client.create_cluster(parent, cluster_id, cluster) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): The unique name of the instance in which to create the new cluster. Values are of the form ``projects/<project>/instances/<instance>``. cluster_id (str): The ID to be used when referring to the new cluster within its instance, e.g., just ``mycluster`` rather than ``projects/myproject/instances/myinstance/clusters/mycluster``. cluster (Union[dict, ~google.cloud.bigtable_admin_v2.types.Cluster]): The cluster to be created. Fields marked ``OutputOnly`` must be left blank. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Cluster` 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.bigtable_admin_v2.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 "create_cluster" not in self._inner_api_calls: self._inner_api_calls[ "create_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_cluster, default_retry=self._method_configs["CreateCluster"].retry, default_timeout=self._method_configs["CreateCluster"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.CreateClusterRequest( parent=parent, cluster_id=cluster_id, cluster=cluster ) 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["create_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instance_pb2.Cluster, metadata_type=bigtable_instance_admin_pb2.CreateClusterMetadata, )
Updates a cluster within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> name = client.cluster_path('[PROJECT]', '[INSTANCE]', '[CLUSTER]') >>> >>> # TODO: Initialize `serve_nodes`: >>> serve_nodes = 0 >>> >>> response = client.update_cluster(name, serve_nodes) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): (``OutputOnly``) The unique name of the cluster. Values are of the form ``projects/<project>/instances/<instance>/clusters/[a-z][-a-z0-9]*``. serve_nodes (int): The number of nodes allocated to this cluster. More nodes enable higher throughput and more consistent performance. location (str): (``CreationOnly``) The location where this cluster's nodes and storage reside. For best performance, clients should be located as close as possible to this cluster. Currently only zones are supported, so values should be of the form ``projects/<project>/locations/<zone>``. state (~google.cloud.bigtable_admin_v2.types.State): (``OutputOnly``) The current state of the cluster. default_storage_type (~google.cloud.bigtable_admin_v2.types.StorageType): (``CreationOnly``) The type of storage used by this cluster to serve its parent instance's tables, unless explicitly overridden. 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.bigtable_admin_v2.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 update_cluster( self, name, serve_nodes, location=None, state=None, default_storage_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates a cluster within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> name = client.cluster_path('[PROJECT]', '[INSTANCE]', '[CLUSTER]') >>> >>> # TODO: Initialize `serve_nodes`: >>> serve_nodes = 0 >>> >>> response = client.update_cluster(name, serve_nodes) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): (``OutputOnly``) The unique name of the cluster. Values are of the form ``projects/<project>/instances/<instance>/clusters/[a-z][-a-z0-9]*``. serve_nodes (int): The number of nodes allocated to this cluster. More nodes enable higher throughput and more consistent performance. location (str): (``CreationOnly``) The location where this cluster's nodes and storage reside. For best performance, clients should be located as close as possible to this cluster. Currently only zones are supported, so values should be of the form ``projects/<project>/locations/<zone>``. state (~google.cloud.bigtable_admin_v2.types.State): (``OutputOnly``) The current state of the cluster. default_storage_type (~google.cloud.bigtable_admin_v2.types.StorageType): (``CreationOnly``) The type of storage used by this cluster to serve its parent instance's tables, unless explicitly overridden. 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.bigtable_admin_v2.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 "update_cluster" not in self._inner_api_calls: self._inner_api_calls[ "update_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_cluster, default_retry=self._method_configs["UpdateCluster"].retry, default_timeout=self._method_configs["UpdateCluster"].timeout, client_info=self._client_info, ) request = instance_pb2.Cluster( name=name, serve_nodes=serve_nodes, location=location, state=state, default_storage_type=default_storage_type, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] 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["update_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instance_pb2.Cluster, metadata_type=bigtable_instance_admin_pb2.UpdateClusterMetadata, )
Creates an app profile within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `app_profile_id`: >>> app_profile_id = '' >>> >>> # TODO: Initialize `app_profile`: >>> app_profile = {} >>> >>> response = client.create_app_profile(parent, app_profile_id, app_profile) Args: parent (str): The unique name of the instance in which to create the new app profile. Values are of the form ``projects/<project>/instances/<instance>``. app_profile_id (str): The ID to be used when referring to the new app profile within its instance, e.g., just ``myprofile`` rather than ``projects/myproject/instances/myinstance/appProfiles/myprofile``. app_profile (Union[dict, ~google.cloud.bigtable_admin_v2.types.AppProfile]): The app profile to be created. Fields marked ``OutputOnly`` will be ignored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.AppProfile` ignore_warnings (bool): If true, ignore safety checks when creating the app profile. 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.bigtable_admin_v2.types.AppProfile` 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_app_profile( self, parent, app_profile_id, app_profile, ignore_warnings=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an app profile within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `app_profile_id`: >>> app_profile_id = '' >>> >>> # TODO: Initialize `app_profile`: >>> app_profile = {} >>> >>> response = client.create_app_profile(parent, app_profile_id, app_profile) Args: parent (str): The unique name of the instance in which to create the new app profile. Values are of the form ``projects/<project>/instances/<instance>``. app_profile_id (str): The ID to be used when referring to the new app profile within its instance, e.g., just ``myprofile`` rather than ``projects/myproject/instances/myinstance/appProfiles/myprofile``. app_profile (Union[dict, ~google.cloud.bigtable_admin_v2.types.AppProfile]): The app profile to be created. Fields marked ``OutputOnly`` will be ignored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.AppProfile` ignore_warnings (bool): If true, ignore safety checks when creating the app profile. 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.bigtable_admin_v2.types.AppProfile` 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_app_profile" not in self._inner_api_calls: self._inner_api_calls[ "create_app_profile" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_app_profile, default_retry=self._method_configs["CreateAppProfile"].retry, default_timeout=self._method_configs["CreateAppProfile"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.CreateAppProfileRequest( parent=parent, app_profile_id=app_profile_id, app_profile=app_profile, ignore_warnings=ignore_warnings, ) 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_app_profile"]( request, retry=retry, timeout=timeout, metadata=metadata )
Updates an app profile within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> # TODO: Initialize `app_profile`: >>> app_profile = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_app_profile(app_profile, update_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: app_profile (Union[dict, ~google.cloud.bigtable_admin_v2.types.AppProfile]): The app profile which will (partially) replace the current value. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.AppProfile` update_mask (Union[dict, ~google.cloud.bigtable_admin_v2.types.FieldMask]): The subset of app profile fields which should be replaced. If unset, all fields will be replaced. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.FieldMask` ignore_warnings (bool): If true, ignore safety checks when updating the app profile. 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.bigtable_admin_v2.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 update_app_profile( self, app_profile, update_mask, ignore_warnings=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an app profile within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> # TODO: Initialize `app_profile`: >>> app_profile = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_app_profile(app_profile, update_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: app_profile (Union[dict, ~google.cloud.bigtable_admin_v2.types.AppProfile]): The app profile which will (partially) replace the current value. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.AppProfile` update_mask (Union[dict, ~google.cloud.bigtable_admin_v2.types.FieldMask]): The subset of app profile fields which should be replaced. If unset, all fields will be replaced. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.FieldMask` ignore_warnings (bool): If true, ignore safety checks when updating the app profile. 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.bigtable_admin_v2.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 "update_app_profile" not in self._inner_api_calls: self._inner_api_calls[ "update_app_profile" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_app_profile, default_retry=self._method_configs["UpdateAppProfile"].retry, default_timeout=self._method_configs["UpdateAppProfile"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.UpdateAppProfileRequest( app_profile=app_profile, update_mask=update_mask, ignore_warnings=ignore_warnings, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("app_profile.name", app_profile.name)] 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["update_app_profile"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instance_pb2.AppProfile, metadata_type=bigtable_instance_admin_pb2.UpdateAppProfileMetadata, )
Return a fully-qualified annotation_spec_set string. def annotation_spec_set_path(cls, project, annotation_spec_set): """Return a fully-qualified annotation_spec_set string.""" return google.api_core.path_template.expand( "projects/{project}/annotationSpecSets/{annotation_spec_set}", project=project, annotation_spec_set=annotation_spec_set, )
Return a fully-qualified dataset string. def dataset_path(cls, project, dataset): """Return a fully-qualified dataset string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}", project=project, dataset=dataset )
Return a fully-qualified annotated_dataset string. def annotated_dataset_path(cls, project, dataset, annotated_dataset): """Return a fully-qualified annotated_dataset string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}", project=project, dataset=dataset, annotated_dataset=annotated_dataset, )
Return a fully-qualified example string. def example_path(cls, project, dataset, annotated_dataset, example): """Return a fully-qualified example string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}", project=project, dataset=dataset, annotated_dataset=annotated_dataset, example=example, )
Return a fully-qualified data_item string. def data_item_path(cls, project, dataset, data_item): """Return a fully-qualified data_item string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/dataItems/{data_item}", project=project, dataset=dataset, data_item=data_item, )
Return a fully-qualified instruction string. def instruction_path(cls, project, instruction): """Return a fully-qualified instruction string.""" return google.api_core.path_template.expand( "projects/{project}/instructions/{instruction}", project=project, instruction=instruction, )
Exports data and annotations from dataset. Example: >>> from google.cloud import datalabeling_v1beta1 >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> name = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `annotated_dataset`: >>> annotated_dataset = '' >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.export_data(name, annotated_dataset, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): Required. Dataset resource name, format: projects/{project\_id}/datasets/{dataset\_id} annotated_dataset (str): Required. Annotated dataset resource name. DataItem in Dataset and their annotations in specified annotated dataset will be exported. It's in format of projects/{project\_id}/datasets/{dataset\_id}/annotatedDatasets/ {annotated\_dataset\_id} output_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.OutputConfig]): Required. Specify the output destination. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.OutputConfig` filter_ (str): Optional. Filter is not supported at this moment. 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.datalabeling_v1beta1.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 export_data( self, name, annotated_dataset, output_config, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Exports data and annotations from dataset. Example: >>> from google.cloud import datalabeling_v1beta1 >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> name = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `annotated_dataset`: >>> annotated_dataset = '' >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.export_data(name, annotated_dataset, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): Required. Dataset resource name, format: projects/{project\_id}/datasets/{dataset\_id} annotated_dataset (str): Required. Annotated dataset resource name. DataItem in Dataset and their annotations in specified annotated dataset will be exported. It's in format of projects/{project\_id}/datasets/{dataset\_id}/annotatedDatasets/ {annotated\_dataset\_id} output_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.OutputConfig]): Required. Specify the output destination. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.OutputConfig` filter_ (str): Optional. Filter is not supported at this moment. 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.datalabeling_v1beta1.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 "export_data" not in self._inner_api_calls: self._inner_api_calls[ "export_data" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.export_data, default_retry=self._method_configs["ExportData"].retry, default_timeout=self._method_configs["ExportData"].timeout, client_info=self._client_info, ) request = data_labeling_service_pb2.ExportDataRequest( name=name, annotated_dataset=annotated_dataset, output_config=output_config, filter=filter_, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] 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["export_data"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, proto_operations_pb2.ExportDataOperationResponse, metadata_type=proto_operations_pb2.ExportDataOperationMetadata, )
Starts a labeling task for image. The type of image labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelImageRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_image(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the dataset to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of image labeling task. image_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig]): Configuration for image classification task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig` bounding_poly_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig]): Configuration for bounding box and bounding poly task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig` polyline_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.PolylineConfig]): Configuration for polyline task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.PolylineConfig` segmentation_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.SegmentationConfig]): Configuration for segmentation task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.SegmentationConfig` 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.datalabeling_v1beta1.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 label_image( self, parent, basic_config, feature, image_classification_config=None, bounding_poly_config=None, polyline_config=None, segmentation_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a labeling task for image. The type of image labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelImageRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_image(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the dataset to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of image labeling task. image_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig]): Configuration for image classification task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig` bounding_poly_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig]): Configuration for bounding box and bounding poly task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig` polyline_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.PolylineConfig]): Configuration for polyline task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.PolylineConfig` segmentation_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.SegmentationConfig]): Configuration for segmentation task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.SegmentationConfig` 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.datalabeling_v1beta1.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 "label_image" not in self._inner_api_calls: self._inner_api_calls[ "label_image" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.label_image, default_retry=self._method_configs["LabelImage"].retry, default_timeout=self._method_configs["LabelImage"].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( image_classification_config=image_classification_config, bounding_poly_config=bounding_poly_config, polyline_config=polyline_config, segmentation_config=segmentation_config, ) request = data_labeling_service_pb2.LabelImageRequest( parent=parent, basic_config=basic_config, feature=feature, image_classification_config=image_classification_config, bounding_poly_config=bounding_poly_config, polyline_config=polyline_config, segmentation_config=segmentation_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) operation = self._inner_api_calls["label_image"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, dataset_pb2.AnnotatedDataset, metadata_type=proto_operations_pb2.LabelOperationMetadata, )
Starts a labeling task for video. The type of video labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelVideoRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_video(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the dataset to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of video labeling task. video_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig]): Configuration for video classification task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig` object_detection_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig]): Configuration for video object detection task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig` object_tracking_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig]): Configuration for video object tracking task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig` event_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.EventConfig]): Configuration for video event task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.EventConfig` 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.datalabeling_v1beta1.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 label_video( self, parent, basic_config, feature, video_classification_config=None, object_detection_config=None, object_tracking_config=None, event_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a labeling task for video. The type of video labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelVideoRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_video(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the dataset to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of video labeling task. video_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig]): Configuration for video classification task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig` object_detection_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig]): Configuration for video object detection task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig` object_tracking_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig]): Configuration for video object tracking task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig` event_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.EventConfig]): Configuration for video event task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.EventConfig` 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.datalabeling_v1beta1.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 "label_video" not in self._inner_api_calls: self._inner_api_calls[ "label_video" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.label_video, default_retry=self._method_configs["LabelVideo"].retry, default_timeout=self._method_configs["LabelVideo"].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( video_classification_config=video_classification_config, object_detection_config=object_detection_config, object_tracking_config=object_tracking_config, event_config=event_config, ) request = data_labeling_service_pb2.LabelVideoRequest( parent=parent, basic_config=basic_config, feature=feature, video_classification_config=video_classification_config, object_detection_config=object_detection_config, object_tracking_config=object_tracking_config, event_config=event_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) operation = self._inner_api_calls["label_video"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, dataset_pb2.AnnotatedDataset, metadata_type=proto_operations_pb2.LabelOperationMetadata, )
Starts a labeling task for text. The type of text labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelTextRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_text(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the data set to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of text labeling task. text_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.TextClassificationConfig]): Configuration for text classification task. One of text\_classification\_config and text\_entity\_extraction\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.TextClassificationConfig` text_entity_extraction_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig]): Configuration for entity extraction task. One of text\_classification\_config and text\_entity\_extraction\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig` 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.datalabeling_v1beta1.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 label_text( self, parent, basic_config, feature, text_classification_config=None, text_entity_extraction_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a labeling task for text. The type of text labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelTextRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_text(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the data set to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of text labeling task. text_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.TextClassificationConfig]): Configuration for text classification task. One of text\_classification\_config and text\_entity\_extraction\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.TextClassificationConfig` text_entity_extraction_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig]): Configuration for entity extraction task. One of text\_classification\_config and text\_entity\_extraction\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig` 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.datalabeling_v1beta1.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 "label_text" not in self._inner_api_calls: self._inner_api_calls[ "label_text" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.label_text, default_retry=self._method_configs["LabelText"].retry, default_timeout=self._method_configs["LabelText"].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( text_classification_config=text_classification_config, text_entity_extraction_config=text_entity_extraction_config, ) request = data_labeling_service_pb2.LabelTextRequest( parent=parent, basic_config=basic_config, feature=feature, text_classification_config=text_classification_config, text_entity_extraction_config=text_entity_extraction_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) operation = self._inner_api_calls["label_text"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, dataset_pb2.AnnotatedDataset, metadata_type=proto_operations_pb2.LabelOperationMetadata, )
Creates an instruction for how data should be labeled. Example: >>> from google.cloud import datalabeling_v1beta1 >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instruction`: >>> instruction = {} >>> >>> response = client.create_instruction(parent, instruction) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Instruction resource parent, format: projects/{project\_id} instruction (Union[dict, ~google.cloud.datalabeling_v1beta1.types.Instruction]): Required. Instruction of how to perform the labeling task. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.Instruction` 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.datalabeling_v1beta1.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 create_instruction( self, parent, instruction, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an instruction for how data should be labeled. Example: >>> from google.cloud import datalabeling_v1beta1 >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instruction`: >>> instruction = {} >>> >>> response = client.create_instruction(parent, instruction) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Instruction resource parent, format: projects/{project\_id} instruction (Union[dict, ~google.cloud.datalabeling_v1beta1.types.Instruction]): Required. Instruction of how to perform the labeling task. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.Instruction` 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.datalabeling_v1beta1.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 "create_instruction" not in self._inner_api_calls: self._inner_api_calls[ "create_instruction" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_instruction, default_retry=self._method_configs["CreateInstruction"].retry, default_timeout=self._method_configs["CreateInstruction"].timeout, client_info=self._client_info, ) request = data_labeling_service_pb2.CreateInstructionRequest( parent=parent, instruction=instruction ) 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["create_instruction"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instruction_pb2.Instruction, metadata_type=proto_operations_pb2.CreateInstructionMetadata, )
Factory: construct a Variable given its API representation :type resource: dict :param resource: change set representation returned from the API. :type config: :class:`google.cloud.runtimeconfig.config.Config` :param config: The config to which this variable belongs. :rtype: :class:`google.cloud.runtimeconfig.variable.Variable` :returns: Variable parsed from ``resource``. def from_api_repr(cls, resource, config): """Factory: construct a Variable given its API representation :type resource: dict :param resource: change set representation returned from the API. :type config: :class:`google.cloud.runtimeconfig.config.Config` :param config: The config to which this variable belongs. :rtype: :class:`google.cloud.runtimeconfig.variable.Variable` :returns: Variable parsed from ``resource``. """ name = variable_name_from_full_name(resource.get("name")) variable = cls(name=name, config=config) variable._set_properties(resource=resource) return variable
Fully-qualified name of this variable. Example: ``projects/my-project/configs/my-config/variables/my-var`` :rtype: str :returns: The full name based on config and variable names. :raises: :class:`ValueError` if the variable is missing a name. def full_name(self): """Fully-qualified name of this variable. Example: ``projects/my-project/configs/my-config/variables/my-var`` :rtype: str :returns: The full name based on config and variable names. :raises: :class:`ValueError` if the variable is missing a name. """ if not self.name: raise ValueError("Missing variable name.") return "%s/variables/%s" % (self.config.full_name, self.name)
Value of the variable, as bytes. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables :rtype: bytes or ``NoneType`` :returns: The value of the variable or ``None`` if the property is not set locally. def value(self): """Value of the variable, as bytes. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables :rtype: bytes or ``NoneType`` :returns: The value of the variable or ``None`` if the property is not set locally. """ value = self._properties.get("value") if value is not None: value = base64.b64decode(value) return value
Retrieve the timestamp at which the variable was updated. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables Returns: :class:`~api_core.datetime_helpers.DatetimeWithNanoseconds`, :class:`datetime.datetime` or ``NoneType``: Datetime object parsed from RFC3339 valid timestamp, or ``None`` if the property is not set locally. Raises: ValueError: if value is not a valid RFC3339 timestamp def update_time(self): """Retrieve the timestamp at which the variable was updated. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables Returns: :class:`~api_core.datetime_helpers.DatetimeWithNanoseconds`, :class:`datetime.datetime` or ``NoneType``: Datetime object parsed from RFC3339 valid timestamp, or ``None`` if the property is not set locally. Raises: ValueError: if value is not a valid RFC3339 timestamp """ value = self._properties.get("updateTime") if value is not None: try: value = datetime.datetime.strptime( value, datetime_helpers._RFC3339_MICROS ) except ValueError: DatetimeNS = datetime_helpers.DatetimeWithNanoseconds value = DatetimeNS.from_rfc3339(value) naive = value.tzinfo is None or value.tzinfo.utcoffset(value) is None if naive: value = pytz.utc.localize(value) return value
Update properties from resource in body of ``api_response`` :type resource: dict :param resource: variable representation returned from the API. def _set_properties(self, resource): """Update properties from resource in body of ``api_response`` :type resource: dict :param resource: variable representation returned from the API. """ self._properties.clear() cleaned = resource.copy() if "name" in cleaned: self.name = variable_name_from_full_name(cleaned.pop("name")) self._properties.update(cleaned)
Converts an ``Any`` protobuf to the specified message type. Args: pb_type (type): the type of the message that any_pb stores an instance of. any_pb (google.protobuf.any_pb2.Any): the object to be converted. Returns: pb_type: An instance of the pb_type message. Raises: TypeError: if the message could not be converted. def from_any_pb(pb_type, any_pb): """Converts an ``Any`` protobuf to the specified message type. Args: pb_type (type): the type of the message that any_pb stores an instance of. any_pb (google.protobuf.any_pb2.Any): the object to be converted. Returns: pb_type: An instance of the pb_type message. Raises: TypeError: if the message could not be converted. """ msg = pb_type() # Unwrap proto-plus wrapped messages. if callable(getattr(pb_type, "pb", None)): msg_pb = pb_type.pb(msg) else: msg_pb = msg # Unpack the Any object and populate the protobuf message instance. if not any_pb.Unpack(msg_pb): raise TypeError( "Could not convert {} to {}".format( any_pb.__class__.__name__, pb_type.__name__ ) ) # Done; return the message. return msg
Discovers all protobuf Message classes in a given import module. Args: module (module): A Python module; :func:`dir` will be run against this module to find Message subclasses. Returns: dict[str, google.protobuf.message.Message]: A dictionary with the Message class names as keys, and the Message subclasses themselves as values. def get_messages(module): """Discovers all protobuf Message classes in a given import module. Args: module (module): A Python module; :func:`dir` will be run against this module to find Message subclasses. Returns: dict[str, google.protobuf.message.Message]: A dictionary with the Message class names as keys, and the Message subclasses themselves as values. """ answer = collections.OrderedDict() for name in dir(module): candidate = getattr(module, name) if inspect.isclass(candidate) and issubclass(candidate, message.Message): answer[name] = candidate return answer
Resolve a potentially nested key. If the key contains the ``separator`` (e.g. ``.``) then the key will be split on the first instance of the subkey:: >>> _resolve_subkeys('a.b.c') ('a', 'b.c') >>> _resolve_subkeys('d|e|f', separator='|') ('d', 'e|f') If not, the subkey will be :data:`None`:: >>> _resolve_subkeys('foo') ('foo', None) Args: key (str): A string that may or may not contain the separator. separator (str): The namespace separator. Defaults to `.`. Returns: Tuple[str, str]: The key and subkey(s). def _resolve_subkeys(key, separator="."): """Resolve a potentially nested key. If the key contains the ``separator`` (e.g. ``.``) then the key will be split on the first instance of the subkey:: >>> _resolve_subkeys('a.b.c') ('a', 'b.c') >>> _resolve_subkeys('d|e|f', separator='|') ('d', 'e|f') If not, the subkey will be :data:`None`:: >>> _resolve_subkeys('foo') ('foo', None) Args: key (str): A string that may or may not contain the separator. separator (str): The namespace separator. Defaults to `.`. Returns: Tuple[str, str]: The key and subkey(s). """ parts = key.split(separator, 1) if len(parts) > 1: return parts else: return parts[0], None
Retrieve a key's value from a protobuf Message or dictionary. Args: mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to retrieve from the object. default (Any): If the key is not present on the object, and a default is set, returns that default instead. A type-appropriate falsy default is generally recommended, as protobuf messages almost always have default values for unset values and it is not always possible to tell the difference between a falsy value and an unset one. If no default is set then :class:`KeyError` will be raised if the key is not present in the object. Returns: Any: The return value from the underlying Message or dict. Raises: KeyError: If the key is not found. Note that, for unset values, messages and dictionaries may not have consistent behavior. TypeError: If ``msg_or_dict`` is not a Message or Mapping. def get(msg_or_dict, key, default=_SENTINEL): """Retrieve a key's value from a protobuf Message or dictionary. Args: mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to retrieve from the object. default (Any): If the key is not present on the object, and a default is set, returns that default instead. A type-appropriate falsy default is generally recommended, as protobuf messages almost always have default values for unset values and it is not always possible to tell the difference between a falsy value and an unset one. If no default is set then :class:`KeyError` will be raised if the key is not present in the object. Returns: Any: The return value from the underlying Message or dict. Raises: KeyError: If the key is not found. Note that, for unset values, messages and dictionaries may not have consistent behavior. TypeError: If ``msg_or_dict`` is not a Message or Mapping. """ # We may need to get a nested key. Resolve this. key, subkey = _resolve_subkeys(key) # Attempt to get the value from the two types of objects we know about. # If we get something else, complain. if isinstance(msg_or_dict, message.Message): answer = getattr(msg_or_dict, key, default) elif isinstance(msg_or_dict, collections_abc.Mapping): answer = msg_or_dict.get(key, default) else: raise TypeError( "get() expected a dict or protobuf message, got {!r}.".format( type(msg_or_dict) ) ) # If the object we got back is our sentinel, raise KeyError; this is # a "not found" case. if answer is _SENTINEL: raise KeyError(key) # If a subkey exists, call this method recursively against the answer. if subkey is not None and answer is not default: return get(answer, subkey, default=default) return answer
Set helper for protobuf Messages. def _set_field_on_message(msg, key, value): """Set helper for protobuf Messages.""" # Attempt to set the value on the types of objects we know how to deal # with. if isinstance(value, (collections_abc.MutableSequence, tuple)): # Clear the existing repeated protobuf message of any elements # currently inside it. while getattr(msg, key): getattr(msg, key).pop() # Write our new elements to the repeated field. for item in value: if isinstance(item, collections_abc.Mapping): getattr(msg, key).add(**item) else: # protobuf's RepeatedCompositeContainer doesn't support # append. getattr(msg, key).extend([item]) elif isinstance(value, collections_abc.Mapping): # Assign the dictionary values to the protobuf message. for item_key, item_value in value.items(): set(getattr(msg, key), item_key, item_value) elif isinstance(value, message.Message): getattr(msg, key).CopyFrom(value) else: setattr(msg, key, value)
Set a key's value on a protobuf Message or dictionary. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to set. value (Any): The value to set. Raises: TypeError: If ``msg_or_dict`` is not a Message or dictionary. def set(msg_or_dict, key, value): """Set a key's value on a protobuf Message or dictionary. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to set. value (Any): The value to set. Raises: TypeError: If ``msg_or_dict`` is not a Message or dictionary. """ # Sanity check: Is our target object valid? if not isinstance(msg_or_dict, (collections_abc.MutableMapping, message.Message)): raise TypeError( "set() expected a dict or protobuf message, got {!r}.".format( type(msg_or_dict) ) ) # We may be setting a nested key. Resolve this. basekey, subkey = _resolve_subkeys(key) # If a subkey exists, then get that object and call this method # recursively against it using the subkey. if subkey is not None: if isinstance(msg_or_dict, collections_abc.MutableMapping): msg_or_dict.setdefault(basekey, {}) set(get(msg_or_dict, basekey), subkey, value) return if isinstance(msg_or_dict, collections_abc.MutableMapping): msg_or_dict[key] = value else: _set_field_on_message(msg_or_dict, key, value)
Set the key on a protobuf Message or dictionary to a given value if the current value is falsy. Because protobuf Messages do not distinguish between unset values and falsy ones particularly well (by design), this method treats any falsy value (e.g. 0, empty list) as a target to be overwritten, on both Messages and dictionaries. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key on the object in question. value (Any): The value to set. Raises: TypeError: If ``msg_or_dict`` is not a Message or dictionary. def setdefault(msg_or_dict, key, value): """Set the key on a protobuf Message or dictionary to a given value if the current value is falsy. Because protobuf Messages do not distinguish between unset values and falsy ones particularly well (by design), this method treats any falsy value (e.g. 0, empty list) as a target to be overwritten, on both Messages and dictionaries. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key on the object in question. value (Any): The value to set. Raises: TypeError: If ``msg_or_dict`` is not a Message or dictionary. """ if not get(msg_or_dict, key, default=None): set(msg_or_dict, key, value)
Create a field mask by comparing two messages. Args: original (~google.protobuf.message.Message): the original message. If set to None, this field will be interpretted as an empty message. modified (~google.protobuf.message.Message): the modified message. If set to None, this field will be interpretted as an empty message. Returns: google.protobuf.field_mask_pb2.FieldMask: field mask that contains the list of field names that have different values between the two messages. If the messages are equivalent, then the field mask is empty. Raises: ValueError: If the ``original`` or ``modified`` are not the same type. def field_mask(original, modified): """Create a field mask by comparing two messages. Args: original (~google.protobuf.message.Message): the original message. If set to None, this field will be interpretted as an empty message. modified (~google.protobuf.message.Message): the modified message. If set to None, this field will be interpretted as an empty message. Returns: google.protobuf.field_mask_pb2.FieldMask: field mask that contains the list of field names that have different values between the two messages. If the messages are equivalent, then the field mask is empty. Raises: ValueError: If the ``original`` or ``modified`` are not the same type. """ if original is None and modified is None: return field_mask_pb2.FieldMask() if original is None and modified is not None: original = copy.deepcopy(modified) original.Clear() if modified is None and original is not None: modified = copy.deepcopy(original) modified.Clear() if type(original) != type(modified): raise ValueError( "expected that both original and modified should be of the " 'same type, received "{!r}" and "{!r}".'.format( type(original), type(modified) ) ) return field_mask_pb2.FieldMask(paths=_field_mask_helper(original, modified))
Return a fully-qualified topic string. def topic_path(cls, project, topic): """Return a fully-qualified topic string.""" return google.api_core.path_template.expand( "projects/{project}/topics/{topic}", project=project, topic=topic )
Return a fully-qualified snapshot string. def snapshot_path(cls, project, snapshot): """Return a fully-qualified snapshot string.""" return google.api_core.path_template.expand( "projects/{project}/snapshots/{snapshot}", project=project, snapshot=snapshot, )
Creates a subscription to a given topic. See the resource name rules. If the subscription already exists, returns ``ALREADY_EXISTS``. If the corresponding topic doesn't exist, returns ``NOT_FOUND``. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic, conforming to the `resource name format <https://cloud.google.com/pubsub/docs/admin#resource_names>`__. The generated name is populated in the returned Subscription object. Note that for REST API requests, you must specify a name in the request. Example: >>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> name = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> response = client.create_subscription(name, topic) Args: name (str): The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"` topic (str): The name of the topic from which this subscription is receiving messages. Format is ``projects/{project}/topics/{topic}``. The value of this field will be ``_deleted-topic_`` if the topic has been deleted. push_config (Union[dict, ~google.cloud.pubsub_v1.types.PushConfig]): If push delivery is used with this subscription, this field is used to configure it. An empty ``pushConfig`` signifies that the subscriber will pull and ack messages using API methods. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.PushConfig` ack_deadline_seconds (int): The approximate amount of time (on a best-effort basis) Pub/Sub waits for the subscriber to acknowledge receipt before resending the message. In the interval after the message is delivered and before it is acknowledged, it is considered to be outstanding. During that time period, the message will not be redelivered (on a best-effort basis). For pull subscriptions, this value is used as the initial value for the ack deadline. To override this value for a given message, call ``ModifyAckDeadline`` with the corresponding ``ack_id`` if using non-streaming pull or send the ``ack_id`` in a ``StreamingModifyAckDeadlineRequest`` if using streaming pull. The minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds (10 minutes). If this parameter is 0, a default value of 10 seconds is used. For push delivery, this value is also used to set the request timeout for the call to the push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message. retain_acked_messages (bool): Indicates whether to retain acknowledged messages. If true, then messages are not expunged from the subscription's backlog, even if they are acknowledged, until they fall out of the ``message_retention_duration`` window. This must be true if you would like to Seek to a timestamp. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. message_retention_duration (Union[dict, ~google.cloud.pubsub_v1.types.Duration]): How long to retain unacknowledged messages in the subscription's backlog, from the moment a message is published. If ``retain_acked_messages`` is true, then this also configures the retention of acknowledged messages, and thus configures how far back in time a ``Seek`` can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 minutes. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.Duration` labels (dict[str -> str]): See <a href="https://cloud.google.com/pubsub/docs/labels"> Creating and managing labels</a>. enable_message_ordering (bool): If true, messages published with the same ``ordering_key`` in ``PubsubMessage`` will be delivered to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise, they may be delivered in any order. EXPERIMENTAL: This feature is part of a closed alpha release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. expiration_policy (Union[dict, ~google.cloud.pubsub_v1.types.ExpirationPolicy]): A policy that specifies the conditions for this subscription's expiration. A subscription is considered active as long as any connected subscriber is successfully consuming messages from the subscription or is issuing operations on the subscription. If ``expiration_policy`` is not set, a *default policy* with ``ttl`` of 31 days will be used. The minimum allowed value for ``expiration_policy.ttl`` is 1 day. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.ExpirationPolicy` 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.pubsub_v1.types.Subscription` 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_subscription( self, name, topic, push_config=None, ack_deadline_seconds=None, retain_acked_messages=None, message_retention_duration=None, labels=None, enable_message_ordering=None, expiration_policy=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a subscription to a given topic. See the resource name rules. If the subscription already exists, returns ``ALREADY_EXISTS``. If the corresponding topic doesn't exist, returns ``NOT_FOUND``. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic, conforming to the `resource name format <https://cloud.google.com/pubsub/docs/admin#resource_names>`__. The generated name is populated in the returned Subscription object. Note that for REST API requests, you must specify a name in the request. Example: >>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> name = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> response = client.create_subscription(name, topic) Args: name (str): The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"` topic (str): The name of the topic from which this subscription is receiving messages. Format is ``projects/{project}/topics/{topic}``. The value of this field will be ``_deleted-topic_`` if the topic has been deleted. push_config (Union[dict, ~google.cloud.pubsub_v1.types.PushConfig]): If push delivery is used with this subscription, this field is used to configure it. An empty ``pushConfig`` signifies that the subscriber will pull and ack messages using API methods. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.PushConfig` ack_deadline_seconds (int): The approximate amount of time (on a best-effort basis) Pub/Sub waits for the subscriber to acknowledge receipt before resending the message. In the interval after the message is delivered and before it is acknowledged, it is considered to be outstanding. During that time period, the message will not be redelivered (on a best-effort basis). For pull subscriptions, this value is used as the initial value for the ack deadline. To override this value for a given message, call ``ModifyAckDeadline`` with the corresponding ``ack_id`` if using non-streaming pull or send the ``ack_id`` in a ``StreamingModifyAckDeadlineRequest`` if using streaming pull. The minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds (10 minutes). If this parameter is 0, a default value of 10 seconds is used. For push delivery, this value is also used to set the request timeout for the call to the push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message. retain_acked_messages (bool): Indicates whether to retain acknowledged messages. If true, then messages are not expunged from the subscription's backlog, even if they are acknowledged, until they fall out of the ``message_retention_duration`` window. This must be true if you would like to Seek to a timestamp. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. message_retention_duration (Union[dict, ~google.cloud.pubsub_v1.types.Duration]): How long to retain unacknowledged messages in the subscription's backlog, from the moment a message is published. If ``retain_acked_messages`` is true, then this also configures the retention of acknowledged messages, and thus configures how far back in time a ``Seek`` can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 minutes. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.Duration` labels (dict[str -> str]): See <a href="https://cloud.google.com/pubsub/docs/labels"> Creating and managing labels</a>. enable_message_ordering (bool): If true, messages published with the same ``ordering_key`` in ``PubsubMessage`` will be delivered to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise, they may be delivered in any order. EXPERIMENTAL: This feature is part of a closed alpha release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. expiration_policy (Union[dict, ~google.cloud.pubsub_v1.types.ExpirationPolicy]): A policy that specifies the conditions for this subscription's expiration. A subscription is considered active as long as any connected subscriber is successfully consuming messages from the subscription or is issuing operations on the subscription. If ``expiration_policy`` is not set, a *default policy* with ``ttl`` of 31 days will be used. The minimum allowed value for ``expiration_policy.ttl`` is 1 day. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.ExpirationPolicy` 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.pubsub_v1.types.Subscription` 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_subscription" not in self._inner_api_calls: self._inner_api_calls[ "create_subscription" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_subscription, default_retry=self._method_configs["CreateSubscription"].retry, default_timeout=self._method_configs["CreateSubscription"].timeout, client_info=self._client_info, ) request = pubsub_pb2.Subscription( name=name, topic=topic, push_config=push_config, ack_deadline_seconds=ack_deadline_seconds, retain_acked_messages=retain_acked_messages, message_retention_duration=message_retention_duration, labels=labels, enable_message_ordering=enable_message_ordering, expiration_policy=expiration_policy, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", 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["create_subscription"]( request, retry=retry, timeout=timeout, metadata=metadata )
Seeks an existing subscription to a point in time or to a given snapshot, whichever is provided in the request. Snapshots are used in <a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek</a> operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot. Note that both the subscription and the snapshot must be on the same topic.<br><br> <b>BETA:</b> This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. Example: >>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> response = client.seek(subscription) Args: subscription (str): The subscription to affect. time (Union[dict, ~google.cloud.pubsub_v1.types.Timestamp]): The time to seek to. Messages retained in the subscription that were published before this time are marked as acknowledged, and messages retained in the subscription that were published after this time are marked as unacknowledged. Note that this operation affects only those messages retained in the subscription (configured by the combination of ``message_retention_duration`` and ``retain_acked_messages``). For example, if ``time`` corresponds to a point before the message retention window (or to a point before the system's notion of the subscription creation time), only retained messages will be marked as unacknowledged, and already-expunged messages will not be restored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.Timestamp` snapshot (str): The snapshot to seek to. The snapshot's topic must be the same as that of the provided subscription. Format is ``projects/{project}/snapshots/{snap}``. 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.pubsub_v1.types.SeekResponse` 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 seek( self, subscription, time=None, snapshot=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Seeks an existing subscription to a point in time or to a given snapshot, whichever is provided in the request. Snapshots are used in <a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek</a> operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot. Note that both the subscription and the snapshot must be on the same topic.<br><br> <b>BETA:</b> This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. Example: >>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> response = client.seek(subscription) Args: subscription (str): The subscription to affect. time (Union[dict, ~google.cloud.pubsub_v1.types.Timestamp]): The time to seek to. Messages retained in the subscription that were published before this time are marked as acknowledged, and messages retained in the subscription that were published after this time are marked as unacknowledged. Note that this operation affects only those messages retained in the subscription (configured by the combination of ``message_retention_duration`` and ``retain_acked_messages``). For example, if ``time`` corresponds to a point before the message retention window (or to a point before the system's notion of the subscription creation time), only retained messages will be marked as unacknowledged, and already-expunged messages will not be restored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.Timestamp` snapshot (str): The snapshot to seek to. The snapshot's topic must be the same as that of the provided subscription. Format is ``projects/{project}/snapshots/{snap}``. 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.pubsub_v1.types.SeekResponse` 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 "seek" not in self._inner_api_calls: self._inner_api_calls["seek"] = google.api_core.gapic_v1.method.wrap_method( self.transport.seek, default_retry=self._method_configs["Seek"].retry, default_timeout=self._method_configs["Seek"].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(time=time, snapshot=snapshot) request = pubsub_pb2.SeekRequest( subscription=subscription, time=time, snapshot=snapshot ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("subscription", subscription)] 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["seek"]( request, retry=retry, timeout=timeout, metadata=metadata )
Completes the specified prefix with keyword suggestions. Intended for use by a job search auto-complete search box. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompletionClient() >>> >>> name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `query`: >>> query = '' >>> >>> # TODO: Initialize `page_size`: >>> page_size = 0 >>> >>> response = client.complete_query(name, query, page_size) Args: name (str): Required. Resource name of project the completion is performed within. The format is "projects/{project\_id}", for example, "projects/api-test-project". query (str): Required. The query used to generate suggestions. The maximum number of allowed characters is 255. page_size (int): Required. Completion result count. The maximum allowed page size is 10. language_codes (list[str]): Optional. The list of languages of the query. This is the BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see `Tags for Identifying Languages <https://tools.ietf.org/html/bcp47>`__. For ``CompletionType.JOB_TITLE`` type, only open jobs with the same ``language_codes`` are returned. For ``CompletionType.COMPANY_NAME`` type, only companies having open jobs with the same ``language_codes`` are returned. For ``CompletionType.COMBINED`` type, only open jobs with the same ``language_codes`` or companies having open jobs with the same ``language_codes`` are returned. The maximum number of allowed characters is 255. company_name (str): Optional. If provided, restricts completion to specified company. The format is "projects/{project\_id}/companies/{company\_id}", for example, "projects/api-test-project/companies/foo". scope (~google.cloud.talent_v4beta1.types.CompletionScope): Optional. The scope of the completion. The defaults is ``CompletionScope.PUBLIC``. type_ (~google.cloud.talent_v4beta1.types.CompletionType): Optional. The completion topic. The default is ``CompletionType.COMBINED``. 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.talent_v4beta1.types.CompleteQueryResponse` 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 complete_query( self, name, query, page_size, language_codes=None, company_name=None, scope=None, type_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Completes the specified prefix with keyword suggestions. Intended for use by a job search auto-complete search box. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompletionClient() >>> >>> name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `query`: >>> query = '' >>> >>> # TODO: Initialize `page_size`: >>> page_size = 0 >>> >>> response = client.complete_query(name, query, page_size) Args: name (str): Required. Resource name of project the completion is performed within. The format is "projects/{project\_id}", for example, "projects/api-test-project". query (str): Required. The query used to generate suggestions. The maximum number of allowed characters is 255. page_size (int): Required. Completion result count. The maximum allowed page size is 10. language_codes (list[str]): Optional. The list of languages of the query. This is the BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see `Tags for Identifying Languages <https://tools.ietf.org/html/bcp47>`__. For ``CompletionType.JOB_TITLE`` type, only open jobs with the same ``language_codes`` are returned. For ``CompletionType.COMPANY_NAME`` type, only companies having open jobs with the same ``language_codes`` are returned. For ``CompletionType.COMBINED`` type, only open jobs with the same ``language_codes`` or companies having open jobs with the same ``language_codes`` are returned. The maximum number of allowed characters is 255. company_name (str): Optional. If provided, restricts completion to specified company. The format is "projects/{project\_id}/companies/{company\_id}", for example, "projects/api-test-project/companies/foo". scope (~google.cloud.talent_v4beta1.types.CompletionScope): Optional. The scope of the completion. The defaults is ``CompletionScope.PUBLIC``. type_ (~google.cloud.talent_v4beta1.types.CompletionType): Optional. The completion topic. The default is ``CompletionType.COMBINED``. 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.talent_v4beta1.types.CompleteQueryResponse` 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 "complete_query" not in self._inner_api_calls: self._inner_api_calls[ "complete_query" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.complete_query, default_retry=self._method_configs["CompleteQuery"].retry, default_timeout=self._method_configs["CompleteQuery"].timeout, client_info=self._client_info, ) request = completion_service_pb2.CompleteQueryRequest( name=name, query=query, page_size=page_size, language_codes=language_codes, company_name=company_name, scope=scope, type=type_, ) return self._inner_api_calls["complete_query"]( request, retry=retry, timeout=timeout, metadata=metadata )
Helper for concrete methods creating session instances. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: new session instance. def _new_session(self): """Helper for concrete methods creating session instances. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: new session instance. """ if self.labels: return self._database.session(labels=self.labels) return self._database.session()
Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. def bind(self, database): """Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ self._database = database while not self._sessions.full(): session = self._new_session() session.create() self._sessions.put(session)
Check a session out from the pool. :type timeout: int :param timeout: seconds to block waiting for an available session :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty. def get(self, timeout=None): # pylint: disable=arguments-differ """Check a session out from the pool. :type timeout: int :param timeout: seconds to block waiting for an available session :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty. """ if timeout is None: timeout = self.default_timeout session = self._sessions.get(block=True, timeout=timeout) if not session.exists(): session = self._database.session() session.create() return session
Delete all sessions in the pool. def clear(self): """Delete all sessions in the pool.""" while True: try: session = self._sessions.get(block=False) except queue.Empty: break else: session.delete()
Check a session out from the pool. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. def get(self): """Check a session out from the pool. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. """ try: session = self._sessions.get_nowait() except queue.Empty: session = self._new_session() session.create() else: if not session.exists(): session = self._new_session() session.create() return session
Return a session to the pool. Never blocks: if the pool is full, the returned session is discarded. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. def put(self, session): """Return a session to the pool. Never blocks: if the pool is full, the returned session is discarded. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. """ try: self._sessions.put_nowait(session) except queue.Full: try: session.delete() except NotFound: pass
Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. def bind(self, database): """Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ self._database = database for _ in xrange(self.size): session = self._new_session() session.create() self.put(session)
Check a session out from the pool. :type timeout: int :param timeout: seconds to block waiting for an available session :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty. def get(self, timeout=None): # pylint: disable=arguments-differ """Check a session out from the pool. :type timeout: int :param timeout: seconds to block waiting for an available session :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty. """ if timeout is None: timeout = self.default_timeout ping_after, session = self._sessions.get(block=True, timeout=timeout) if _NOW() > ping_after: if not session.exists(): session = self._new_session() session.create() return session
Return a session to the pool. Never blocks: if the pool is full, raises. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full. def put(self, session): """Return a session to the pool. Never blocks: if the pool is full, raises. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full. """ self._sessions.put_nowait((_NOW() + self._delta, session))
Refresh maybe-expired sessions in the pool. This method is designed to be called from a background thread, or during the "idle" phase of an event loop. def ping(self): """Refresh maybe-expired sessions in the pool. This method is designed to be called from a background thread, or during the "idle" phase of an event loop. """ while True: try: ping_after, session = self._sessions.get(block=False) except queue.Empty: # all sessions in use break if ping_after > _NOW(): # oldest session is fresh # Re-add to queue with existing expiration self._sessions.put((ping_after, session)) break if not session.exists(): # stale session = self._new_session() session.create() # Re-add to queue with new expiration self.put(session)
Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. def bind(self, database): """Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ super(TransactionPingingPool, self).bind(database) self.begin_pending_transactions()
Return a session to the pool. Never blocks: if the pool is full, raises. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full. def put(self, session): """Return a session to the pool. Never blocks: if the pool is full, raises. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full. """ if self._sessions.full(): raise queue.Full txn = session._transaction if txn is None or txn.committed() or txn._rolled_back: session.transaction() self._pending_sessions.put(session) else: super(TransactionPingingPool, self).put(session)
Begin all transactions for sessions added to the pool. def begin_pending_transactions(self): """Begin all transactions for sessions added to the pool.""" while not self._pending_sessions.empty(): session = self._pending_sessions.get() session._transaction.begin() super(TransactionPingingPool, self).put(session)
Attach a logging handler to the Python root logger Excludes loggers that this library itself uses to avoid infinite recursion. :type handler: :class:`logging.handler` :param handler: the handler to attach to the global handler :type excluded_loggers: tuple :param excluded_loggers: (Optional) The loggers to not attach the handler to. This will always include the loggers in the path of the logging client itself. :type log_level: int :param log_level: (Optional) Python logging log level. Defaults to :const:`logging.INFO`. Example: .. code-block:: python import logging import google.cloud.logging from google.cloud.logging.handlers import CloudLoggingHandler client = google.cloud.logging.Client() handler = CloudLoggingHandler(client) google.cloud.logging.handlers.setup_logging(handler) logging.getLogger().setLevel(logging.DEBUG) logging.error('bad news') # API call def setup_logging( handler, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, log_level=logging.INFO ): """Attach a logging handler to the Python root logger Excludes loggers that this library itself uses to avoid infinite recursion. :type handler: :class:`logging.handler` :param handler: the handler to attach to the global handler :type excluded_loggers: tuple :param excluded_loggers: (Optional) The loggers to not attach the handler to. This will always include the loggers in the path of the logging client itself. :type log_level: int :param log_level: (Optional) Python logging log level. Defaults to :const:`logging.INFO`. Example: .. code-block:: python import logging import google.cloud.logging from google.cloud.logging.handlers import CloudLoggingHandler client = google.cloud.logging.Client() handler = CloudLoggingHandler(client) google.cloud.logging.handlers.setup_logging(handler) logging.getLogger().setLevel(logging.DEBUG) logging.error('bad news') # API call """ all_excluded_loggers = set(excluded_loggers + EXCLUDED_LOGGER_DEFAULTS) logger = logging.getLogger() logger.setLevel(log_level) logger.addHandler(handler) logger.addHandler(logging.StreamHandler()) for logger_name in all_excluded_loggers: logger = logging.getLogger(logger_name) logger.propagate = False logger.addHandler(logging.StreamHandler())
Actually log the specified logging record. Overrides the default emit behavior of ``StreamHandler``. See https://docs.python.org/2/library/logging.html#handler-objects :type record: :class:`logging.LogRecord` :param record: The record to be logged. def emit(self, record): """Actually log the specified logging record. Overrides the default emit behavior of ``StreamHandler``. See https://docs.python.org/2/library/logging.html#handler-objects :type record: :class:`logging.LogRecord` :param record: The record to be logged. """ message = super(CloudLoggingHandler, self).format(record) self.transport.send(record, message, resource=self.resource, labels=self.labels)
Helper: construct concrete query parameter from JSON resource. def _query_param_from_api_repr(resource): """Helper: construct concrete query parameter from JSON resource.""" qp_type = resource["parameterType"] if "arrayType" in qp_type: klass = ArrayQueryParameter elif "structTypes" in qp_type: klass = StructQueryParameter else: klass = ScalarQueryParameter return klass.from_api_repr(resource)
Factory: construct parameter from JSON resource. :type resource: dict :param resource: JSON mapping of parameter :rtype: :class:`~google.cloud.bigquery.query.ScalarQueryParameter` :returns: instance def from_api_repr(cls, resource): """Factory: construct parameter from JSON resource. :type resource: dict :param resource: JSON mapping of parameter :rtype: :class:`~google.cloud.bigquery.query.ScalarQueryParameter` :returns: instance """ name = resource.get("name") type_ = resource["parameterType"]["type"] value = resource["parameterValue"]["value"] converted = _QUERY_PARAMS_FROM_JSON[type_](value, None) return cls(name, type_, converted)