text
stringlengths
81
112k
Start the background thread and begin consuming the thread. def start(self): """Start the background thread and begin consuming the thread.""" with self._operational_lock: ready = threading.Event() thread = threading.Thread( name=_BIDIRECTIONAL_CONSUMER_NAME, ...
Stop consuming the stream and shutdown the background thread. def stop(self): """Stop consuming the stream and shutdown the background thread.""" with self._operational_lock: self._bidi_rpc.close() if self._thread is not None: # Resume the thread to wake it up i...
Resumes the response stream. def resume(self): """Resumes the response stream.""" with self._wake: self._paused = False self._wake.notifyAll()
Return a fully-qualified project string. def project_path(cls, user, project): """Return a fully-qualified project string.""" return google.api_core.path_template.expand( "users/{user}/projects/{project}", user=user, project=project )
Return a fully-qualified fingerprint string. def fingerprint_path(cls, user, fingerprint): """Return a fully-qualified fingerprint string.""" return google.api_core.path_template.expand( "users/{user}/sshPublicKeys/{fingerprint}", user=user, fingerprint=fingerprint, ...
Deletes a POSIX account. Example: >>> from google.cloud import oslogin_v1 >>> >>> client = oslogin_v1.OsLoginServiceClient() >>> >>> name = client.project_path('[USER]', '[PROJECT]') >>> >>> client.delete_posix_account(name) ...
Adds an SSH public key and returns the profile information. Default POSIX account information is set when no username and UID exist as part of the login profile. Example: >>> from google.cloud import oslogin_v1 >>> >>> client = oslogin_v1.OsLoginServiceClient...
Updates an SSH public key and returns the profile information. This method supports patch semantics. Example: >>> from google.cloud import oslogin_v1 >>> >>> client = oslogin_v1.OsLoginServiceClient() >>> >>> name = client.fingerprint_path('[U...
Convert a protobuf GC rule to a native object. :type gc_rule_pb: :class:`.table_v2_pb2.GcRule` :param gc_rule_pb: The GC rule to convert. :rtype: :class:`GarbageCollectionRule` or :data:`NoneType <types.NoneType>` :returns: An instance of one of the native rules defined in :module:`colum...
Converts the garbage collection rule to a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted current object. def to_pb(self): """Converts the garbage collection rule to a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted current objec...
Converts the union into a single GC rule as a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted current object. def to_pb(self): """Converts the union into a single GC rule as a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted curre...
Converts the intersection into a single GC rule as a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted current object. def to_pb(self): """Converts the intersection into a single GC rule as a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The c...
Converts the column family to a protobuf. :rtype: :class:`.table_v2_pb2.ColumnFamily` :returns: The converted current object. def to_pb(self): """Converts the column family to a protobuf. :rtype: :class:`.table_v2_pb2.ColumnFamily` :returns: The converted current object. ...
Create this column family. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_create_column_family] :end-before: [END bigtable_create_column_family] def create(self): """Create this column family. For example: .. literali...
Delete this column family. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_delete_column_family] :end-before: [END bigtable_delete_column_family] def delete(self): """Delete this column family. For example: .. literali...
Wraps a gRPC exception class, if needed. def _maybe_wrap_exception(exception): """Wraps a gRPC exception class, if needed.""" if isinstance(exception, grpc.RpcError): return exceptions.from_grpc_error(exception) return exception
Stop consuming messages and shutdown all helper threads. This method is idempotent. Additional calls will have no effect. Args: reason (Any): The reason to close this. If None, this is considered an "intentional" shutdown. def close(self, reason=None): """Stop cons...
Triggered whenever the underlying RPC terminates without recovery. This is typically triggered from one of two threads: the background consumer thread (when calling ``recv()`` produces a non-recoverable error) or the grpc management thread (when cancelling the RPC). This method is *non...
Creates a watch snapshot listener for a document. snapshot_callback receives a DocumentChange object, but may also start to get targetChange and such soon Args: document_ref: Reference to Document snapshot_callback: callback to be called on snapshot snapshot_...
Called everytime there is a response from listen. Collect changes and 'push' the changes in a batch to the customer when we receive 'current' from the listen response. Args: listen_response(`google.cloud.firestore_v1beta1.types.ListenResponse`): Callback method that ...
Assembles a new snapshot from the current set of changes and invokes the user's callback. Clears the current changes on completion. def push(self, read_time, next_resume_token): """ Assembles a new snapshot from the current set of changes and invokes the user's callback. Clears the curr...
Returns the current count of all documents, including the changes from the current changeMap. def _current_size(self): """ Returns the current count of all documents, including the changes from the current changeMap. """ deletes, adds, _ = Watch._extract_changes(self.doc...
Helper to clear the docs on RESET or filter mismatch. def _reset_docs(self): """ Helper to clear the docs on RESET or filter mismatch. """ _LOGGER.debug("resetting documents") self.change_map.clear() self.resume_token = None # Mark each document as deleted. If d...
Construct an API url given a few components, some optional. Typically, you shouldn't need to use this method. :type path: str :param path: The path to the resource (ie, ``'/b/bucket-name'``). :type query_params: dict or list :param query_params: A dictionary of keys and values...
A low level method to send a request to the API. Typically, you shouldn't need to use this method. :type method: str :param method: The HTTP method to use in the request. :type url: str :param url: The URL to send the request to. :type data: str :param data: T...
Low-level helper: perform the actual API request over HTTP. Allows batch context managers to override and defer a request. :type method: str :param method: The HTTP method to use in the request. :type url: str :param url: The URL to send the request to. :type headers...
Make a request over the HTTP transport to the API. You shouldn't need to use this method, but if you plan to interact with the API using these primitives, this is the correct one to use. :type method: str :param method: The HTTP method name (ie, ``GET``, ``POST``, etc). ...
Construct a filter string to filter on metric or resource labels. def _build_label_filter(category, *args, **kwargs): """Construct a filter string to filter on metric or resource labels.""" terms = list(args) for key, value in six.iteritems(kwargs): if value is None: continue s...
Copy the query and set the query time interval. Example:: import datetime now = datetime.datetime.utcnow() query = query.select_interval( end_time=now, start_time=now - datetime.timedelta(minutes=5)) As a convenience, you can altern...
Copy the query and add filtering by group. Example:: query = query.select_group('1234567') :type group_id: str :param group_id: The ID of a group to filter by. :rtype: :class:`Query` :returns: The new query object. def select_group(self, group_id): """Cop...
Copy the query and add filtering by monitored projects. This is only useful if the target project represents a Stackdriver account containing the specified monitored projects. Examples:: query = query.select_projects('project-1') query = query.select_projects('project-...
Copy the query and add filtering by resource labels. Examples:: query = query.select_resources(zone='us-central1-a') query = query.select_resources(zone_prefix='europe-') query = query.select_resources(resource_type='gce_instance') A keyword argument ``<label>=<val...
Copy the query and add filtering by metric labels. Examples:: query = query.select_metrics(instance_name='myinstance') query = query.select_metrics(instance_name_prefix='mycluster-') A keyword argument ``<label>=<value>`` ordinarily generates a filter expression of the...
Copy the query and add temporal alignment. If ``per_series_aligner`` is not :data:`Aligner.ALIGN_NONE`, each time series will contain data points only on the period boundaries. Example:: from google.cloud.monitoring import enums query = query.align( enu...
Copy the query and add cross-series reduction. Cross-series reduction combines time series by aggregating their data points. For example, you could request an aggregated time series for each combination of project and zone as follows:: from google.cloud.monitoring import e...
Yield all time series objects selected by the query. The generator returned iterates over :class:`~google.cloud.monitoring_v3.types.TimeSeries` objects containing points ordered from oldest to newest. Note that the :class:`Query` object itself is an iterable, such that the foll...
Return key-value pairs for the list_time_series API call. :type headers_only: bool :param headers_only: Whether to omit the point data from the :class:`~google.cloud.monitoring_v3.types.TimeSeries` objects. :type page_size: int :param page_size: (O...
Factory: construct a project given its API representation. :type resource: dict :param resource: project resource representation returned from the API :type client: :class:`google.cloud.resource_manager.client.Client` :param client: The Client used with this project. :rtype: ...
Update specific properties from its API representation. def set_properties_from_api_repr(self, resource): """Update specific properties from its API representation.""" self.name = resource.get("name") self.number = resource["projectNumber"] self.labels = resource.get("labels", {}) ...
API call: create the project via a ``POST`` request. See https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/create :type client: :class:`google.cloud.resource_manager.client.Client` or :data:`NoneType <types.NoneType>` :param client: the cl...
API call: update the project via a ``PUT`` request. See https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/update :type client: :class:`google.cloud.resource_manager.client.Client` or :data:`NoneType <types.NoneType>` :param client: the cli...
API call: delete the project via a ``DELETE`` request. See https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/delete This actually changes the status (``lifecycleState``) from ``ACTIVE`` to ``DELETE_REQUESTED``. Later (it's not specified when), the proje...
Get the meaning from a protobuf value. :type value_pb: :class:`.entity_pb2.Value` :param value_pb: The protobuf value to be checked for an associated meaning. :type is_list: bool :param is_list: Boolean indicating if the ``value_pb`` contains a list value. ...
Factory method for creating an entity based on a protobuf. The protobuf should be one returned from the Cloud Datastore Protobuf API. :type pb: :class:`.entity_pb2.Entity` :param pb: The Protobuf representing the entity. :rtype: :class:`google.cloud.datastore.entity.Entity` :returns: The enti...
Add meaning information (from an entity) to a protobuf. :type entity: :class:`google.cloud.datastore.entity.Entity` :param entity: The entity to be turned into a protobuf. :type name: str :param name: The name of the property. :type value: object :param value: The current value stored as prop...
Converts an entity into a protobuf. :type entity: :class:`google.cloud.datastore.entity.Entity` :param entity: The entity to be turned into a protobuf. :rtype: :class:`.entity_pb2.Entity` :returns: The protobuf representing the entity. def entity_to_protobuf(entity): """Converts an entity into a ...
Validate rules for read options, and assign to the request. Helper method for ``lookup()`` and ``run_query``. :type eventual: bool :param eventual: Flag indicating if ``EVENTUAL`` or ``STRONG`` consistency should be used. :type transaction_id: bytes :param transaction_id: A t...
Factory method for creating a key based on a protobuf. The protobuf should be one returned from the Cloud Datastore Protobuf API. :type pb: :class:`.entity_pb2.Key` :param pb: The Protobuf representing the key. :rtype: :class:`google.cloud.datastore.key.Key` :returns: a new `Key` instance de...
Given a value, return the protobuf attribute name and proper value. The Protobuf API uses different attribute names based on value types rather than inferring the type. This function simply determines the proper attribute name based on the type of the value provided and returns the attribute name as w...
Given a protobuf for a Value, get the correct value. The Cloud Datastore Protobuf API returns a Property Protobuf which has one value set and the rest blank. This function retrieves the the one value provided. Some work is done to coerce the return value into a more useful type (particularly in t...
Assign 'val' to the correct subfield of 'value_pb'. The Protobuf API uses different attribute names based on value types rather than inferring the type. Some value types (entities, keys, lists) cannot be directly assigned; this function handles them correctly. :type value_pb: :class:`.entity_pb2....
Convert the current object to protobuf. :rtype: :class:`google.type.latlng_pb2.LatLng`. :returns: The current point as a protobuf. def to_protobuf(self): """Convert the current object to protobuf. :rtype: :class:`google.type.latlng_pb2.LatLng`. :returns: The current point as a...
Factory: construct an entry given its API representation :type resource: dict :param resource: text entry resource representation returned from the API :type client: :class:`google.cloud.logging.client.Client` :param client: Client which holds credentials and ...
API repr (JSON format) for entry. def to_api_repr(self): """API repr (JSON format) for entry. """ info = {} if self.log_name is not None: info["logName"] = self.log_name if self.resource is not None: info["resource"] = self.resource._to_dict() if ...
API repr (JSON format) for entry. def to_api_repr(self): """API repr (JSON format) for entry. """ info = super(TextEntry, self).to_api_repr() info["textPayload"] = self.payload return info
API repr (JSON format) for entry. def to_api_repr(self): """API repr (JSON format) for entry. """ info = super(StructEntry, self).to_api_repr() info["jsonPayload"] = self.payload return info
API repr (JSON format) for entry. def to_api_repr(self): """API repr (JSON format) for entry. """ info = super(ProtobufEntry, self).to_api_repr() info["protoPayload"] = MessageToDict(self.payload) return info
Construct a DB-API time value from the given ticks value. :type ticks: float :param ticks: a number of seconds since the epoch; see the documentation of the standard Python time module for details. :type tz: :class:`datetime.tzinfo` :param tz: (Optional) time zone to use for conversion...
Return a fully-qualified registry string. def registry_path(cls, project, location, registry): """Return a fully-qualified registry string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/registries/{registry}", project=project, ...
Return a fully-qualified device string. def device_path(cls, project, location, registry, device): """Return a fully-qualified device string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/registries/{registry}/devices/{device}", project...
Creates a device in a device registry. Example: >>> from google.cloud import iot_v1 >>> >>> client = iot_v1.DeviceManagerClient() >>> >>> parent = client.registry_path('[PROJECT]', '[LOCATION]', '[REGISTRY]') >>> >>> # TODO: In...
Sets the access control policy on the specified resource. Replaces any existing policy. Example: >>> from google.cloud import iot_v1 >>> >>> client = iot_v1.DeviceManagerClient() >>> >>> resource = client.registry_path('[PROJECT]', '[LOCATION]...
Associates the device with the gateway. Example: >>> from google.cloud import iot_v1 >>> >>> client = iot_v1.DeviceManagerClient() >>> >>> parent = client.registry_path('[PROJECT]', '[LOCATION]', '[REGISTRY]') >>> >>> # TODO: I...
Return a fully-qualified queue string. def queue_path(cls, project, location, queue): """Return a fully-qualified queue string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/queues/{queue}", project=project, location=locatio...
Return a fully-qualified task string. def task_path(cls, project, location, queue, task): """Return a fully-qualified task string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}", project=project, ...
Creates a queue. Queues created with this method allow tasks to live for a maximum of 31 days. After a task is 31 days old, the task will be deleted regardless of whether it was dispatched or not. WARNING: Using this method may have unintended side effects if you are using an A...
Creates a task and adds it to a queue. Tasks cannot be updated after creation; there is no UpdateTask command. - For ``App Engine queues``, the maximum task size is 100KB. Example: >>> from google.cloud import tasks_v2 >>> >>> client = tasks_v2.CloudTasksC...
A generator that yields exponential timeout values. Args: initial (float): The initial timeout. maximum (float): The maximum timeout. multiplier (float): The multiplier applied to the timeout. deadline (float): The overall deadline across all invocations. Yields: float:...
Formats parameters in operation in the way BigQuery expects. The input operation will be a query like ``SELECT %s`` and the output will be a query like ``SELECT ?``. :type operation: str :param operation: A Google BigQuery query string. :type parameters: Sequence[Any] :param parameters: Seque...
Formats parameters in operation in the way BigQuery expects. The input operation will be a query like ``SELECT %(namedparam)s`` and the output will be a query like ``SELECT @namedparam``. :type operation: str :param operation: A Google BigQuery query string. :type parameters: Mapping[str, Any] ...
Formats parameters in operation in way BigQuery expects. :type: str :param operation: A Google BigQuery query string. :type: Mapping[str, Any] or Sequence[Any] :param parameters: Optional parameter values. :rtype: str :returns: A formatted query string. :raises: :class:`~google.cloud.bigq...
Set description from schema. :type schema: Sequence[google.cloud.bigquery.schema.SchemaField] :param schema: A description of fields in the schema. def _set_description(self, schema): """Set description from schema. :type schema: Sequence[google.cloud.bigquery.schema.SchemaField] ...
Set the rowcount from query results. Normally, this sets rowcount to the number of rows returned by the query, but if it was a DML statement, it sets rowcount to the number of modified rows. :type query_results: :class:`~google.cloud.bigquery.query._QueryResults` :p...
Prepare and execute a database operation. .. note:: When setting query parameters, values which are "text" (``unicode`` in Python2, ``str`` in Python3) will use the 'STRING' BigQuery type. Values which are "bytes" (``str`` in Python2, ``bytes`` in Python3), will ...
Try to start fetching data, if not yet started. Mutates self to indicate that iteration has started. def _try_fetch(self, size=None): """Try to start fetching data, if not yet started. Mutates self to indicate that iteration has started. """ if self._query_job is None: ...
Fetch multiple results from the last ``execute*()`` call. .. note:: The size parameter is not used for the request/response size. Set the ``arraysize`` attribute before calling ``execute()`` to set the batch size. :type size: int :param size: (Op...
Create and return a gRPC channel object. Args: address (str): The host for the channel to use. credentials (~.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If ...
Helper for API methods returning sink resources. def _update_from_api_repr(self, resource): """Helper for API methods returning sink resources.""" self.destination = resource["destination"] self.filter_ = resource.get("filter") self._writer_identity = resource.get("writerIdentity")
Factory: construct a sink given its API representation :type resource: dict :param resource: sink resource representation returned from the API :type client: :class:`google.cloud.logging.client.Client` :param client: Client which holds credentials and project co...
API call: create the sink via a PUT request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/create :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls bac...
API call: test for the existence of the sink via a GET request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/get :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param client: the client to use. If not p...
API call: sync local sink configuration via a GET request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/get :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param client: the client to use. If not passed...
API call: update sink configuration via a PUT request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param client: the client to use. If not passed,...
API call: delete a sink via a DELETE request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/delete :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls ba...
Helper for '_merge_by_type'. def _merge_float64(lhs, rhs, type_): # pylint: disable=unused-argument """Helper for '_merge_by_type'.""" lhs_kind = lhs.WhichOneof("kind") if lhs_kind == "string_value": return Value(string_value=lhs.string_value + rhs.string_value) rhs_kind = rhs.WhichOneof("kind...
Helper for '_merge_by_type'. def _merge_string(lhs, rhs, type_): # pylint: disable=unused-argument """Helper for '_merge_by_type'.""" return Value(string_value=lhs.string_value + rhs.string_value)
Helper for '_merge_by_type'. def _merge_array(lhs, rhs, type_): """Helper for '_merge_by_type'.""" element_type = type_.array_element_type if element_type.code in _UNMERGEABLE_TYPES: # Individual values cannot be merged, just concatenate lhs.list_value.values.extend(rhs.list_value.values) ...
Helper for '_merge_by_type'. def _merge_struct(lhs, rhs, type_): """Helper for '_merge_by_type'.""" fields = type_.struct_type.fields lhs, rhs = list(lhs.list_value.values), list(rhs.list_value.values) candidate_type = fields[len(lhs) - 1].type first = rhs.pop(0) if first.HasField("null_value")...
Helper for '_merge_chunk'. def _merge_by_type(lhs, rhs, type_): """Helper for '_merge_chunk'.""" merger = _MERGE_BY_TYPE[type_.code] return merger(lhs, rhs, type_)
Merge pending chunk with next value. :type value: :class:`~google.protobuf.struct_pb2.Value` :param value: continuation of chunked value from previous partial result set. :rtype: :class:`~google.protobuf.struct_pb2.Value` :returns: the merged value def _merge_chu...
Merge values into rows. :type values: list of :class:`~google.protobuf.struct_pb2.Value` :param values: non-chunked values from partial result set. def _merge_values(self, values): """Merge values into rows. :type values: list of :class:`~google.protobuf.struct_pb2.Value` :par...
Consume the next partial result set from the stream. Parse the result set into new/existing rows in :attr:`_rows` def _consume_next(self): """Consume the next partial result set from the stream. Parse the result set into new/existing rows in :attr:`_rows` """ response = six.ne...
Return exactly one result, or None if there are no results. :raises: :exc:`ValueError`: If there are multiple results. :raises: :exc:`RuntimeError`: If consumption has already occurred, in whole or in part. def one_or_none(self): """Return exactly one result, or None if there are n...
Return a fully-qualified product_set string. def product_set_path(cls, project, location, product_set): """Return a fully-qualified product_set string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/productSets/{product_set}", project=pr...
Return a fully-qualified product string. def product_path(cls, project, location, product): """Return a fully-qualified product string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/products/{product}", project=project, loca...
Return a fully-qualified reference_image string. def reference_image_path(cls, project, location, product, reference_image): """Return a fully-qualified reference_image string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/products/{product}/refere...
Creates and returns a new ProductSet resource. Possible errors: - Returns INVALID\_ARGUMENT if display\_name is missing, or is longer than 4096 characters. Example: >>> from google.cloud import vision_v1p3beta1 >>> >>> client = vision_v1p3beta1....
Creates and returns a new ReferenceImage resource. The ``bounding_poly`` field is optional. If ``bounding_poly`` is not specified, the system will try to detect regions of interest in the image that are compatible with the product\_category on the parent product. If it is specified, det...
Asynchronous API that imports a list of reference images to specified product sets based on a list of image information. The ``google.longrunning.Operation`` API can be used to keep track of the progress and results of the request. ``Operation.metadata`` contains ``BatchOperationMetadat...
Special helper to parse ``LogEntry`` protobuf into a dictionary. The ``proto_payload`` field in ``LogEntry`` is of type ``Any``. This can be problematic if the type URL in the payload isn't in the ``google.protobuf`` registry. To help with parsing unregistered types, this function will remove ``proto_p...