INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Delete the current document in the Firestore database.
Args:
option (Optional[~.firestore_v1beta1.client.WriteOption]): A
write option to make assertions / preconditions on the server
state of the document before applying changes.
Returns:
google.p... | def delete(self, option=None):
"""Delete the current document in the Firestore database.
Args:
option (Optional[~.firestore_v1beta1.client.WriteOption]): A
write option to make assertions / preconditions on the server
state of the document before applying chang... |
Retrieve a snapshot of the current document.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
If a ``transaction`` is used and it already has write operations
added, this method cannot be used (i.e. read-after-write is not
allowe... | def get(self, field_paths=None, transaction=None):
"""Retrieve a snapshot of the current document.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
If a ``transaction`` is used and it already has write operations
added, this meth... |
List subcollections of the current document.
Args:
page_size (Optional[int]]): The maximum number of collections
in each page of results from this request. Non-positive values
are ignored. Defaults to a sensible value set by the API.
Returns:
Sequence[~.... | def collections(self, page_size=None):
"""List subcollections of the current document.
Args:
page_size (Optional[int]]): The maximum number of collections
in each page of results from this request. Non-positive values
are ignored. Defaults to a sensible value set by ... |
Get a value from the snapshot data.
If the data is nested, for example:
.. code-block:: python
>>> snapshot.to_dict()
{
'top1': {
'middle2': {
'bottom3': 20,
'bottom4': 22,
},
... | def get(self, field_path):
"""Get a value from the snapshot data.
If the data is nested, for example:
.. code-block:: python
>>> snapshot.to_dict()
{
'top1': {
'middle2': {
'bottom3': 20,
'bo... |
Helper for :meth:`Session.run_in_transaction`.
Detect retryable abort, and impose server-supplied delay.
:type exc: :class:`google.api_core.exceptions.Aborted`
:param exc: exception for aborted transaction
:type deadline: float
:param deadline: maximum timestamp to continue retrying the transacti... | def _delay_until_retry(exc, deadline):
"""Helper for :meth:`Session.run_in_transaction`.
Detect retryable abort, and impose server-supplied delay.
:type exc: :class:`google.api_core.exceptions.Aborted`
:param exc: exception for aborted transaction
:type deadline: float
:param deadline: maximu... |
Helper for :func:`_delay_until_retry`.
:type exc: :class:`grpc.Call`
:param exc: exception for aborted transaction
:rtype: float
:returns: seconds to wait before retrying the transaction. | def _get_retry_delay(cause):
"""Helper for :func:`_delay_until_retry`.
:type exc: :class:`grpc.Call`
:param exc: exception for aborted transaction
:rtype: float
:returns: seconds to wait before retrying the transaction.
"""
metadata = dict(cause.trailing_metadata())
retry_info_pb = met... |
Return a fully-qualified database string. | def database_path(cls, project, instance, database):
"""Return a fully-qualified database string."""
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/databases/{database}",
project=project,
instance=instance,
database=d... |
Creates a new Cloud Spanner database and starts to prepare it for
serving. The returned ``long-running operation`` will have a name of the
format ``<database_name>/operations/<operation_id>`` and can be used to
track preparation of the database. The ``metadata`` field type is
``CreateDat... | def create_database(
self,
parent,
create_statement,
extra_statements=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a new Cloud Spanner database and starts to... |
Updates the schema of a Cloud Spanner database by
creating/altering/dropping tables, columns, indexes, etc. The returned
``long-running operation`` will have a name of the format
``<database_name>/operations/<operation_id>`` and can be used to track
execution of the schema change(s). The... | def update_database_ddl(
self,
database,
statements,
operation_id=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates the schema of a Cloud Spanner database by
... |
Get the scopes corresponding to admin / read-only state.
Returns:
Tuple[str, ...]: The tuple of scopes. | def _get_scopes(self):
"""Get the scopes corresponding to admin / read-only state.
Returns:
Tuple[str, ...]: The tuple of scopes.
"""
if self._read_only:
scopes = (READ_ONLY_SCOPE,)
else:
scopes = (DATA_SCOPE,)
if self._admin:
... |
Getter for the gRPC stub used for the Table Admin API.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_table_data_client]
:end-before: [END bigtable_table_data_client]
:rtype: :class:`.bigtable_v2.BigtableClient`
:returns: A BigtableC... | def table_data_client(self):
"""Getter for the gRPC stub used for the Table Admin API.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_table_data_client]
:end-before: [END bigtable_table_data_client]
:rtype: :class:`.bigtable_v2.Bigta... |
Getter for the gRPC stub used for the Table Admin API.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_table_admin_client]
:end-before: [END bigtable_table_admin_client]
:rtype: :class:`.bigtable_admin_pb2.BigtableTableAdmin`
:returns... | def table_admin_client(self):
"""Getter for the gRPC stub used for the Table Admin API.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_table_admin_client]
:end-before: [END bigtable_table_admin_client]
:rtype: :class:`.bigtable_admin... |
Getter for the gRPC stub used for the Table Admin API.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_instance_admin_client]
:end-before: [END bigtable_instance_admin_client]
:rtype: :class:`.bigtable_admin_pb2.BigtableInstanceAdmin`
... | def instance_admin_client(self):
"""Getter for the gRPC stub used for the Table Admin API.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_instance_admin_client]
:end-before: [END bigtable_instance_admin_client]
:rtype: :class:`.bigta... |
Factory to create a instance associated with this client.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_create_prod_instance]
:end-before: [END bigtable_create_prod_instance]
:type instance_id: str
:param instance_id: The ID of the ... | def instance(self, instance_id, display_name=None, instance_type=None, labels=None):
"""Factory to create a instance associated with this client.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_create_prod_instance]
:end-before: [END bigtable_... |
List instances owned by the project.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_list_instances]
:end-before: [END bigtable_list_instances]
:rtype: tuple
:returns:
(instances, failed_locations), where 'instances' is li... | def list_instances(self):
"""List instances owned by the project.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_list_instances]
:end-before: [END bigtable_list_instances]
:rtype: tuple
:returns:
(instances, faile... |
Deletes a metric descriptor. Only user-created
[custom metrics](/monitoring/custom-metrics) can be deleted. | def DeleteMetricDescriptor(self, request, context):
"""Deletes a metric descriptor. Only user-created
[custom metrics](/monitoring/custom-metrics) can be deleted.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplement... |
List the clusters in the project.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_list_clusters_in_project]
:end-before: [END bigtable_list_clusters_in_project]
:rtype: tuple
:returns:
(clusters, failed_locations), where '... | def list_clusters(self):
"""List the clusters in the project.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_list_clusters_in_project]
:end-before: [END bigtable_list_clusters_in_project]
:rtype: tuple
:returns:
(... |
Lists all clusters owned by a project in either the specified zone or all
zones.
Example:
>>> from google.cloud import container_v1
>>>
>>> client = container_v1.ClusterManagerClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> p... | def list_clusters(
self,
project_id,
zone,
parent=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Lists all clusters owned by a project in either the specified zone or ... |
Gets the details of a specific cluster.
Example:
>>> from google.cloud import container_v1
>>>
>>> client = container_v1.ClusterManagerClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> project_id = ''
>>>
>>> # ... | def get_cluster(
self,
project_id,
zone,
cluster_id,
name=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets the details of a specific cluster.
Examp... |
Sets labels on a cluster.
Example:
>>> from google.cloud import container_v1
>>>
>>> client = container_v1.ClusterManagerClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> project_id = ''
>>>
>>> # TODO: Initiali... | def set_labels(
self,
project_id,
zone,
cluster_id,
resource_labels,
label_fingerprint,
name=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Set... |
Return a fully-qualified metric string. | def metric_path(cls, project, metric):
"""Return a fully-qualified metric string."""
return google.api_core.path_template.expand(
"projects/{project}/metrics/{metric}", project=project, metric=metric
) |
Gets a logs-based metric.
Example:
>>> from google.cloud import logging_v2
>>>
>>> client = logging_v2.MetricsServiceV2Client()
>>>
>>> metric_name = client.metric_path('[PROJECT]', '[METRIC]')
>>>
>>> response = client.get_log... | def get_log_metric(
self,
metric_name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets a logs-based metric.
Example:
>>> from google.cloud import logging_v2
... |
Return a fully-qualified metric_descriptor string. | def metric_descriptor_path(cls, project, metric_descriptor):
"""Return a fully-qualified metric_descriptor string."""
return google.api_core.path_template.expand(
"projects/{project}/metricDescriptors/{metric_descriptor=**}",
project=project,
metric_descriptor=metric_... |
Return a fully-qualified monitored_resource_descriptor string. | def monitored_resource_descriptor_path(cls, project, monitored_resource_descriptor):
"""Return a fully-qualified monitored_resource_descriptor string."""
return google.api_core.path_template.expand(
"projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}",
... |
Construct a KeyRange protobuf.
:rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeyRange`
:returns: protobuf corresponding to this instance. | def _to_pb(self):
"""Construct a KeyRange protobuf.
:rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeyRange`
:returns: protobuf corresponding to this instance.
"""
kwargs = {}
if self.start_open is not None:
kwargs["start_open"] = _make_list_value_p... |
Return keyrange's state as a dict.
:rtype: dict
:returns: state of this instance. | def _to_dict(self):
"""Return keyrange's state as a dict.
:rtype: dict
:returns: state of this instance.
"""
mapping = {}
if self.start_open:
mapping["start_open"] = self.start_open
if self.start_closed:
mapping["start_closed"] = self.st... |
Construct a KeySet protobuf.
:rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeySet`
:returns: protobuf corresponding to this instance. | def _to_pb(self):
"""Construct a KeySet protobuf.
:rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeySet`
:returns: protobuf corresponding to this instance.
"""
if self.all_:
return KeySetPB(all=True)
kwargs = {}
if self.keys:
kwa... |
Return keyset's state as a dict.
The result can be used to serialize the instance and reconstitute
it later using :meth:`_from_dict`.
:rtype: dict
:returns: state of this instance. | def _to_dict(self):
"""Return keyset's state as a dict.
The result can be used to serialize the instance and reconstitute
it later using :meth:`_from_dict`.
:rtype: dict
:returns: state of this instance.
"""
if self.all_:
return {"all": True}
... |
Create an instance from the corresponding state mapping.
:type mapping: dict
:param mapping: the instance state. | def _from_dict(cls, mapping):
"""Create an instance from the corresponding state mapping.
:type mapping: dict
:param mapping: the instance state.
"""
if mapping.get("all"):
return cls(all_=True)
r_mappings = mapping.get("ranges", ())
ranges = [KeyRan... |
Map errors for Unary-Unary and Stream-Unary gRPC callables. | def _wrap_unary_errors(callable_):
"""Map errors for Unary-Unary and Stream-Unary gRPC callables."""
_patch_callable_name(callable_)
@six.wraps(callable_)
def error_remapped_callable(*args, **kwargs):
try:
return callable_(*args, **kwargs)
except grpc.RpcError as exc:
... |
Wrap errors for Unary-Stream and Stream-Stream gRPC callables.
The callables that return iterators require a bit more logic to re-map
errors when iterating. This wraps both the initial invocation and the
iterator of the return value to re-map errors. | def _wrap_stream_errors(callable_):
"""Wrap errors for Unary-Stream and Stream-Stream gRPC callables.
The callables that return iterators require a bit more logic to re-map
errors when iterating. This wraps both the initial invocation and the
iterator of the return value to re-map errors.
"""
_... |
Create a secure channel with credentials.
Args:
target (str): The target service address in the format 'hostname:port'.
credentials (google.auth.credentials.Credentials): The credentials. If
not specified, then this function will attempt to ascertain the
credentials from the... | def create_channel(
target, credentials=None, scopes=None, ssl_credentials=None, **kwargs
):
"""Create a secure channel with credentials.
Args:
target (str): The target service address in the format 'hostname:port'.
credentials (google.auth.credentials.Credentials): The credentials. If
... |
Get the next response from the stream.
Returns:
protobuf.Message: A single response from the stream. | def next(self):
"""Get the next response from the stream.
Returns:
protobuf.Message: A single response from the stream.
"""
try:
return six.next(self._wrapped)
except grpc.RpcError as exc:
six.raise_from(exceptions.from_grpc_error(exc), exc) |
Determine default project explicitly or implicitly as fall-back.
In implicit case, supports four environments. In order of precedence, the
implicit environments are:
* DATASTORE_DATASET environment variable (for ``gcd`` / emulator testing)
* GOOGLE_CLOUD_PROJECT environment variable
* Google App E... | def _determine_default_project(project=None):
"""Determine default project explicitly or implicitly as fall-back.
In implicit case, supports four environments. In order of precedence, the
implicit environments are:
* DATASTORE_DATASET environment variable (for ``gcd`` / emulator testing)
* GOOGLE_... |
A functools.wraps helper that handles partial objects on Python 2. | def wraps(wrapped):
"""A functools.wraps helper that handles partial objects on Python 2."""
if isinstance(wrapped, functools.partial):
return six.wraps(wrapped, assigned=_PARTIAL_VALID_ASSIGNMENTS)
else:
return six.wraps(wrapped) |
Repeat lookup until all keys found (unless stop requested).
Helper function for :meth:`Client.get_multi`.
:type datastore_api:
:class:`google.cloud.datastore._http.HTTPDatastoreAPI`
or :class:`google.cloud.datastore_v1.gapic.DatastoreClient`
:param datastore_api: The datastore API object u... | def _extended_lookup(
datastore_api,
project,
key_pbs,
missing=None,
deferred=None,
eventual=False,
transaction_id=None,
):
"""Repeat lookup until all keys found (unless stop requested).
Helper function for :meth:`Client.get_multi`.
:type datastore_api:
:class:`google.c... |
Getter for a wrapped API object. | def _datastore_api(self):
"""Getter for a wrapped API object."""
if self._datastore_api_internal is None:
if self._use_grpc:
self._datastore_api_internal = make_datastore_api(self)
else:
self._datastore_api_internal = HTTPDatastoreAPI(self)
... |
Retrieve an entity from a single key (if it exists).
.. note::
This is just a thin wrapper over :meth:`get_multi`.
The backend API does not make a distinction between a single key or
multiple keys in a lookup request.
:type key: :class:`google.cloud.datastore.key.Key`... | def get(self, key, missing=None, deferred=None, transaction=None, eventual=False):
"""Retrieve an entity from a single key (if it exists).
.. note::
This is just a thin wrapper over :meth:`get_multi`.
The backend API does not make a distinction between a single key or
... |
Retrieve entities, along with their attributes.
:type keys: list of :class:`google.cloud.datastore.key.Key`
:param keys: The keys to be retrieved from the datastore.
:type missing: list
:param missing: (Optional) If a list is passed, the key-only entities
return... | def get_multi(
self, keys, missing=None, deferred=None, transaction=None, eventual=False
):
"""Retrieve entities, along with their attributes.
:type keys: list of :class:`google.cloud.datastore.key.Key`
:param keys: The keys to be retrieved from the datastore.
:type missing... |
Save entities in the Cloud Datastore.
:type entities: list of :class:`google.cloud.datastore.entity.Entity`
:param entities: The entities to be saved to the datastore.
:raises: :class:`ValueError` if ``entities`` is a single entity. | def put_multi(self, entities):
"""Save entities in the Cloud Datastore.
:type entities: list of :class:`google.cloud.datastore.entity.Entity`
:param entities: The entities to be saved to the datastore.
:raises: :class:`ValueError` if ``entities`` is a single entity.
"""
... |
Delete keys from the Cloud Datastore.
:type keys: list of :class:`google.cloud.datastore.key.Key`
:param keys: The keys to be deleted from the Datastore. | def delete_multi(self, keys):
"""Delete keys from the Cloud Datastore.
:type keys: list of :class:`google.cloud.datastore.key.Key`
:param keys: The keys to be deleted from the Datastore.
"""
if not keys:
return
# We allow partial keys to attempt a delete, th... |
Allocate a list of IDs from a partial key.
:type incomplete_key: :class:`google.cloud.datastore.key.Key`
:param incomplete_key: Partial key to use as base for allocated IDs.
:type num_ids: int
:param num_ids: The number of IDs to allocate.
:rtype: list of :class:`google.cloud.... | def allocate_ids(self, incomplete_key, num_ids):
"""Allocate a list of IDs from a partial key.
:type incomplete_key: :class:`google.cloud.datastore.key.Key`
:param incomplete_key: Partial key to use as base for allocated IDs.
:type num_ids: int
:param num_ids: The number of IDs... |
Proxy to :class:`google.cloud.datastore.key.Key`.
Passes our ``project``. | def key(self, *path_args, **kwargs):
"""Proxy to :class:`google.cloud.datastore.key.Key`.
Passes our ``project``.
"""
if "project" in kwargs:
raise TypeError("Cannot pass project")
kwargs["project"] = self.project
if "namespace" not in kwargs:
kwa... |
Proxy to :class:`google.cloud.datastore.query.Query`.
Passes our ``project``.
Using query to search a datastore:
.. testsetup:: query
import os
import uuid
from google.cloud import datastore
unique = os.getenv('CIRCLE_BUILD_NUM', str(uuid.uui... | def query(self, **kwargs):
"""Proxy to :class:`google.cloud.datastore.query.Query`.
Passes our ``project``.
Using query to search a datastore:
.. testsetup:: query
import os
import uuid
from google.cloud import datastore
unique = os.g... |
Add a row to the batch. If the current batch meets one of the size
limits, the batch is sent synchronously.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_batcher_mutate]
:end-before: [END bigtable_batcher_mutate]
:type row: class
... | def mutate(self, row):
""" Add a row to the batch. If the current batch meets one of the size
limits, the batch is sent synchronously.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_batcher_mutate]
:end-before: [END bigtable_batcher_m... |
Sends the current. batch to Cloud Bigtable.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_batcher_flush]
:end-before: [END bigtable_batcher_flush] | def flush(self):
""" Sends the current. batch to Cloud Bigtable.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_batcher_flush]
:end-before: [END bigtable_batcher_flush]
"""
if len(self.rows) != 0:
self.table.mutate... |
Verify that a topic path is in the correct format.
.. _resource manager docs: https://cloud.google.com/resource-manager/\
reference/rest/v1beta1/projects#\
Project.FIELDS.project_id
.. _topic spec: https://cloud.google.com/storage/docs/json_api/v1/\... | def _parse_topic_path(topic_path):
"""Verify that a topic path is in the correct format.
.. _resource manager docs: https://cloud.google.com/resource-manager/\
reference/rest/v1beta1/projects#\
Project.FIELDS.project_id
.. _topic spec: https://c... |
Construct an instance from the JSON repr returned by the server.
See: https://cloud.google.com/storage/docs/json_api/v1/notifications
:type resource: dict
:param resource: JSON repr of the notification
:type bucket: :class:`google.cloud.storage.bucket.Bucket`
:param bucket: Bu... | def from_api_repr(cls, resource, bucket):
"""Construct an instance from the JSON repr returned by the server.
See: https://cloud.google.com/storage/docs/json_api/v1/notifications
:type resource: dict
:param resource: JSON repr of the notification
:type bucket: :class:`google.c... |
Helper for :meth:`reload`.
:type response: dict
:param response: resource mapping from server | def _set_properties(self, response):
"""Helper for :meth:`reload`.
:type response: dict
:param response: resource mapping from server
"""
self._properties.clear()
self._properties.update(response) |
API wrapper: create the notification.
See:
https://cloud.google.com/storage/docs/json_api/v1/notifications/insert
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client`
:param clie... | def create(self, client=None):
"""API wrapper: create the notification.
See:
https://cloud.google.com/storage/docs/json_api/v1/notifications/insert
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.... |
Test whether this notification exists.
See:
https://cloud.google.com/storage/docs/json_api/v1/notifications/get
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
... | def exists(self, client=None):
"""Test whether this notification exists.
See:
https://cloud.google.com/storage/docs/json_api/v1/notifications/get
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.st... |
Update this notification from the server configuration.
See:
https://cloud.google.com/storage/docs/json_api/v1/notifications/get
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
... | def reload(self, client=None):
"""Update this notification from the server configuration.
See:
https://cloud.google.com/storage/docs/json_api/v1/notifications/get
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:... |
Delete this notification.
See:
https://cloud.google.com/storage/docs/json_api/v1/notifications/delete
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``None... | def delete(self, client=None):
"""Delete this notification.
See:
https://cloud.google.com/storage/docs/json_api/v1/notifications/delete
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.clie... |
Creates a Redis instance based on the specified tier and memory size.
By default, the instance is accessible from the project's `default
network <https://cloud.google.com/compute/docs/networks-and-firewalls#networks>`__.
The creation is executed asynchronously and callers may check the
... | def create_instance(
self,
parent,
instance_id,
instance,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a Redis instance based on the specified tier and memory size... |
Import a Redis RDB snapshot file from GCS into a Redis instance.
Redis may stop serving during this operation. Instance state will be
IMPORTING for entire operation. When complete, the instance will contain
only data from the imported file.
The returned operation is automatically delet... | def import_instance(
self,
name,
input_config,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Import a Redis RDB snapshot file from GCS into a Redis instance.
Redis may sto... |
Return a fully-qualified notification_channel string. | def notification_channel_path(cls, project, notification_channel):
"""Return a fully-qualified notification_channel string."""
return google.api_core.path_template.expand(
"projects/{project}/notificationChannels/{notification_channel}",
project=project,
notification_... |
Return a fully-qualified notification_channel_descriptor string. | def notification_channel_descriptor_path(cls, project, channel_descriptor):
"""Return a fully-qualified notification_channel_descriptor string."""
return google.api_core.path_template.expand(
"projects/{project}/notificationChannelDescriptors/{channel_descriptor}",
project=projec... |
Return a batch to use as a context manager.
:type client: :class:`~google.cloud.logging.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current topic.
:rtype: :class:`Batch`... | def batch(self, client=None):
"""Return a batch to use as a context manager.
:type client: :class:`~google.cloud.logging.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the curre... |
Helper for :meth:`log_empty`, :meth:`log_text`, etc. | def _do_log(self, client, _entry_class, payload=None, **kw):
"""Helper for :meth:`log_empty`, :meth:`log_text`, etc.
"""
client = self._require_client(client)
# Apply defaults
kw["log_name"] = kw.pop("log_name", self.full_name)
kw["labels"] = kw.pop("labels", self.labels... |
API call: log a text message via a POST request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write
:type text: str
:param text: the log message.
:type client: :class:`~google.cloud.logging.client.Client` or
``NoneType``
... | def log_text(self, text, client=None, **kw):
"""API call: log a text message via a POST request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write
:type text: str
:param text: the log message.
:type client: :class:`~google.cloud.logging.clien... |
API call: log a structured message via a POST request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write
:type info: dict
:param info: the log entry information
:type client: :class:`~google.cloud.logging.client.Client` or
``Non... | def log_struct(self, info, client=None, **kw):
"""API call: log a structured message via a POST request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write
:type info: dict
:param info: the log entry information
:type client: :class:`~google.c... |
API call: log a protobuf message via a POST request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list
:type message: :class:`~google.protobuf.message.Message`
:param message: The protobuf message to be logged.
:type client: :class:`~google.cloud.logg... | def log_proto(self, message, client=None, **kw):
"""API call: log a protobuf message via a POST request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list
:type message: :class:`~google.protobuf.message.Message`
:param message: The protobuf message to ... |
API call: delete all entries in a logger via a DELETE request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete
:type client: :class:`~google.cloud.logging.client.Client` or
``NoneType``
:param client: the client to use. If not ... | def delete(self, client=None):
"""API call: delete all entries in a logger via a DELETE request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete
:type client: :class:`~google.cloud.logging.client.Client` or
``NoneType``
... |
Return a page of log entries.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list
:type projects: list of strings
:param projects: project IDs to include. If not passed,
defaults to the project bound to the client.
:type filt... | def list_entries(
self,
projects=None,
filter_=None,
order_by=None,
page_size=None,
page_token=None,
):
"""Return a page of log entries.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list
:type projects: list ... |
Add a text entry to be logged during :meth:`commit`.
:type text: str
:param text: the text entry
:type kw: dict
:param kw: (optional) additional keyword arguments for the entry.
See :class:`~google.cloud.logging.entries.LogEntry`. | def log_text(self, text, **kw):
"""Add a text entry to be logged during :meth:`commit`.
:type text: str
:param text: the text entry
:type kw: dict
:param kw: (optional) additional keyword arguments for the entry.
See :class:`~google.cloud.logging.entries.LogE... |
Add a struct entry to be logged during :meth:`commit`.
:type info: dict
:param info: the struct entry
:type kw: dict
:param kw: (optional) additional keyword arguments for the entry.
See :class:`~google.cloud.logging.entries.LogEntry`. | def log_struct(self, info, **kw):
"""Add a struct entry to be logged during :meth:`commit`.
:type info: dict
:param info: the struct entry
:type kw: dict
:param kw: (optional) additional keyword arguments for the entry.
See :class:`~google.cloud.logging.entri... |
Add a protobuf entry to be logged during :meth:`commit`.
:type message: protobuf message
:param message: the protobuf entry
:type kw: dict
:param kw: (optional) additional keyword arguments for the entry.
See :class:`~google.cloud.logging.entries.LogEntry`. | def log_proto(self, message, **kw):
"""Add a protobuf entry to be logged during :meth:`commit`.
:type message: protobuf message
:param message: the protobuf entry
:type kw: dict
:param kw: (optional) additional keyword arguments for the entry.
See :class:`~go... |
Send saved log entries as a single API call.
:type client: :class:`~google.cloud.logging.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current batch. | def commit(self, client=None):
"""Send saved log entries as a single API call.
:type client: :class:`~google.cloud.logging.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the cur... |
Fully-qualified name of this variable.
Example:
``projects/my-project/configs/my-config``
:rtype: str
:returns: The full name based on project and config names.
:raises: :class:`ValueError` if the config is missing a name. | def full_name(self):
"""Fully-qualified name of this variable.
Example:
``projects/my-project/configs/my-config``
:rtype: str
:returns: The full name based on project and config names.
:raises: :class:`ValueError` if the config is missing a name.
"""
if... |
Update properties from resource in body of ``api_response``
:type api_response: dict
:param api_response: response returned from an API call | def _set_properties(self, api_response):
"""Update properties from resource in body of ``api_response``
:type api_response: dict
:param api_response: response returned from an API call
"""
self._properties.clear()
cleaned = api_response.copy()
if "name" in cleane... |
API call: reload the config via a ``GET`` request.
This method will reload the newest data for the config.
See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs/get
:type client: :class:`google.cloud.runtimeconfig.client.Client`
... | def reload(self, client=None):
"""API call: reload the config via a ``GET`` request.
This method will reload the newest data for the config.
See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs/get
:type client: :class:`... |
API call: get a variable via a ``GET`` request.
This will return None if the variable doesn't exist::
>>> from google.cloud import runtimeconfig
>>> client = runtimeconfig.Client()
>>> config = client.config('my-config')
>>> print(config.get_variable('variable-name'))
... | def get_variable(self, variable_name, client=None):
"""API call: get a variable via a ``GET`` request.
This will return None if the variable doesn't exist::
>>> from google.cloud import runtimeconfig
>>> client = runtimeconfig.Client()
>>> config = client.config('my-conf... |
API call: list variables for this config.
This only lists variable names, not the values.
See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables/list
:type page_size: int
:param page_size:
Optional. T... | def list_variables(self, page_size=None, page_token=None, client=None):
"""API call: list variables for this config.
This only lists variable names, not the values.
See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables/l... |
Base64-decode value | def _bytes_from_json(value, field):
"""Base64-decode value"""
if _not_null(value, field):
return base64.standard_b64decode(_to_bytes(value)) |
Coerce 'value' to a datetime, if set or not nullable.
Args:
value (str): The timestamp.
field (.SchemaField): The field corresponding to the value.
Returns:
Optional[datetime.datetime]: The parsed datetime object from
``value`` if the ``field`` is not null (otherwise it is
... | def _timestamp_query_param_from_json(value, field):
"""Coerce 'value' to a datetime, if set or not nullable.
Args:
value (str): The timestamp.
field (.SchemaField): The field corresponding to the value.
Returns:
Optional[datetime.datetime]: The parsed datetime object from
`... |
Coerce 'value' to a datetime, if set or not nullable.
Args:
value (str): The timestamp.
field (.SchemaField): The field corresponding to the value.
Returns:
Optional[datetime.datetime]: The parsed datetime object from
``value`` if the ``field`` is not null (otherwise it is
... | def _datetime_from_json(value, field):
"""Coerce 'value' to a datetime, if set or not nullable.
Args:
value (str): The timestamp.
field (.SchemaField): The field corresponding to the value.
Returns:
Optional[datetime.datetime]: The parsed datetime object from
``value`` if t... |
Coerce 'value' to a datetime date, if set or not nullable | def _time_from_json(value, field):
"""Coerce 'value' to a datetime date, if set or not nullable"""
if _not_null(value, field):
if len(value) == 8: # HH:MM:SS
fmt = _TIMEONLY_WO_MICROS
elif len(value) == 15: # HH:MM:SS.micros
fmt = _TIMEONLY_W_MICROS
else:
... |
Coerce 'value' to a mapping, if set or not nullable. | def _record_from_json(value, field):
"""Coerce 'value' to a mapping, if set or not nullable."""
if _not_null(value, field):
record = {}
record_iter = zip(field.fields, value["f"])
for subfield, cell in record_iter:
converter = _CELLDATA_FROM_JSON[subfield.field_type]
... |
Convert JSON row data to row with appropriate types.
Note: ``row['f']`` and ``schema`` are presumed to be of the same length.
:type row: dict
:param row: A JSON response row to be converted.
:type schema: tuple
:param schema: A tuple of
:class:`~google.cloud.bigquery.schema.Sc... | def _row_tuple_from_json(row, schema):
"""Convert JSON row data to row with appropriate types.
Note: ``row['f']`` and ``schema`` are presumed to be of the same length.
:type row: dict
:param row: A JSON response row to be converted.
:type schema: tuple
:param schema: A tuple of
... |
Convert JSON row data to rows with appropriate types. | def _rows_from_json(values, schema):
"""Convert JSON row data to rows with appropriate types."""
from google.cloud.bigquery import Row
field_to_index = _field_to_index_mapping(schema)
return [Row(_row_tuple_from_json(r, schema), field_to_index) for r in values] |
Coerce 'value' to a JSON-compatible representation. | def _decimal_to_json(value):
"""Coerce 'value' to a JSON-compatible representation."""
if isinstance(value, decimal.Decimal):
value = str(value)
return value |
Coerce 'value' to an JSON-compatible representation. | def _bytes_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, bytes):
value = base64.standard_b64encode(value).decode("ascii")
return value |
Coerce 'value' to an JSON-compatible representation.
This version returns the string representation used in query parameters. | def _timestamp_to_json_parameter(value):
"""Coerce 'value' to an JSON-compatible representation.
This version returns the string representation used in query parameters.
"""
if isinstance(value, datetime.datetime):
if value.tzinfo not in (None, UTC):
# Convert to UTC and remove the ... |
Coerce 'value' to an JSON-compatible representation.
This version returns floating-point seconds value used in row data. | def _timestamp_to_json_row(value):
"""Coerce 'value' to an JSON-compatible representation.
This version returns floating-point seconds value used in row data.
"""
if isinstance(value, datetime.datetime):
value = _microseconds_from_datetime(value) * 1e-6
return value |
Coerce 'value' to an JSON-compatible representation. | def _datetime_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, datetime.datetime):
value = value.strftime(_RFC3339_MICROS_NO_ZULU)
return value |
Coerce 'value' to an JSON-compatible representation. | def _date_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, datetime.date):
value = value.isoformat()
return value |
Coerce 'value' to an JSON-compatible representation. | def _time_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, datetime.time):
value = value.isoformat()
return value |
Maps a field and value to a JSON-safe value.
Args:
field ( \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
):
The SchemaField to use for type conversion and field name.
row_value (any):
Value to be converted, based on the field's type.
Return... | def _scalar_field_to_json(field, row_value):
"""Maps a field and value to a JSON-safe value.
Args:
field ( \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
):
The SchemaField to use for type conversion and field name.
row_value (any):
Value to ... |
Convert a repeated/array field to its JSON representation.
Args:
field ( \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
):
The SchemaField to use for type conversion and field name. The
field mode must equal ``REPEATED``.
row_value (Sequence[any]... | def _repeated_field_to_json(field, row_value):
"""Convert a repeated/array field to its JSON representation.
Args:
field ( \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
):
The SchemaField to use for type conversion and field name. The
field mode mus... |
Convert a record/struct field to its JSON representation.
Args:
fields ( \
Sequence[:class:`~google.cloud.bigquery.schema.SchemaField`], \
):
The :class:`~google.cloud.bigquery.schema.SchemaField`s of the
record's subfields to use for type conversion and field na... | def _record_field_to_json(fields, row_value):
"""Convert a record/struct field to its JSON representation.
Args:
fields ( \
Sequence[:class:`~google.cloud.bigquery.schema.SchemaField`], \
):
The :class:`~google.cloud.bigquery.schema.SchemaField`s of the
recor... |
Convert a field into JSON-serializable values.
Args:
field ( \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
):
The SchemaField to use for type conversion and field name.
row_value (Union[ \
Sequence[list], \
any, \
]):
... | def _field_to_json(field, row_value):
"""Convert a field into JSON-serializable values.
Args:
field ( \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
):
The SchemaField to use for type conversion and field name.
row_value (Union[ \
Sequence[l... |
Convert snake case string to camel case. | def _snake_to_camel_case(value):
"""Convert snake case string to camel case."""
words = value.split("_")
return words[0] + "".join(map(str.capitalize, words[1:])) |
Get a nested value from a dictionary.
This method works like ``dict.get(key)``, but for nested values.
Arguments:
container (dict):
A dictionary which may contain other dictionaries as values.
keys (iterable):
A sequence of keys to attempt to get the value for. Each ite... | def _get_sub_prop(container, keys, default=None):
"""Get a nested value from a dictionary.
This method works like ``dict.get(key)``, but for nested values.
Arguments:
container (dict):
A dictionary which may contain other dictionaries as values.
keys (iterable):
A s... |
Set a nested value in a dictionary.
Arguments:
container (dict):
A dictionary which may contain other dictionaries as values.
keys (iterable):
A sequence of keys to attempt to set the value for. Each item in
the sequence represents a deeper nesting. The first key... | def _set_sub_prop(container, keys, value):
"""Set a nested value in a dictionary.
Arguments:
container (dict):
A dictionary which may contain other dictionaries as values.
keys (iterable):
A sequence of keys to attempt to set the value for. Each item in
the s... |
Remove a nested key fro a dictionary.
Arguments:
container (dict):
A dictionary which may contain other dictionaries as values.
keys (iterable):
A sequence of keys to attempt to clear the value for. Each item in
the sequence represents a deeper nesting. The first... | def _del_sub_prop(container, keys):
"""Remove a nested key fro a dictionary.
Arguments:
container (dict):
A dictionary which may contain other dictionaries as values.
keys (iterable):
A sequence of keys to attempt to clear the value for. Each item in
the sequ... |
Sample ID: go/samples-tracker/1510 | def get_model(client, model_id):
"""Sample ID: go/samples-tracker/1510"""
# [START bigquery_get_model]
from google.cloud import bigquery
# TODO(developer): Construct a BigQuery client object.
# client = bigquery.Client()
# TODO(developer): Set model_id to the ID of the model to fetch.
# m... |
Build a resource based on a ``_properties`` dictionary, filtered by
``filter_fields``, which follow the name of the Python object. | def _build_resource_from_properties(obj, filter_fields):
"""Build a resource based on a ``_properties`` dictionary, filtered by
``filter_fields``, which follow the name of the Python object.
"""
partial = {}
for filter_field in filter_fields:
api_field = obj._PROPERTY_TO_API_FIELD.get(filter... |
Make sure a "Reference" database ID is empty.
:type database_id: unicode
:param database_id: The ``database_id`` field from a "Reference" protobuf.
:raises: :exc:`ValueError` if the ``database_id`` is not empty. | def _check_database_id(database_id):
"""Make sure a "Reference" database ID is empty.
:type database_id: unicode
:param database_id: The ``database_id`` field from a "Reference" protobuf.
:raises: :exc:`ValueError` if the ``database_id`` is not empty.
"""
if database_id != u"":
msg = _... |
Add the ID or name from an element to a list.
:type flat_path: list
:param flat_path: List of accumulated path parts.
:type element_pb: :class:`._app_engine_key_pb2.Path.Element`
:param element_pb: The element containing ID or name.
:type empty_allowed: bool
:param empty_allowed: Indicates if... | def _add_id_or_name(flat_path, element_pb, empty_allowed):
"""Add the ID or name from an element to a list.
:type flat_path: list
:param flat_path: List of accumulated path parts.
:type element_pb: :class:`._app_engine_key_pb2.Path.Element`
:param element_pb: The element containing ID or name.
... |
Convert a legacy "Path" protobuf to a flat path.
For example
Element {
type: "parent"
id: 59
}
Element {
type: "child"
name: "naem"
}
would convert to ``('parent', 59, 'child', 'naem')``.
:type path_pb: :class:`._app_engine_key_pb2.... | def _get_flat_path(path_pb):
"""Convert a legacy "Path" protobuf to a flat path.
For example
Element {
type: "parent"
id: 59
}
Element {
type: "child"
name: "naem"
}
would convert to ``('parent', 59, 'child', 'naem')``.
:type pa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.