id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
28,300 | googleapis/google-cloud-python | redis/google/cloud/redis_v1/gapic/cloud_redis_client.py | CloudRedisClient.import_instance | 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 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 deleted after a few hours, so
there is no need to call DeleteOperation.
Example:
>>> from google.cloud import redis_v1
>>>
>>> client = redis_v1.CloudRedisClient()
>>>
>>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]')
>>>
>>> # TODO: Initialize `input_config`:
>>> input_config = {}
>>>
>>> response = client.import_instance(name, input_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. Redis instance resource name using the form:
``projects/{project_id}/locations/{location_id}/instances/{instance_id}``
where ``location_id`` refers to a GCP region
input_config (Union[dict, ~google.cloud.redis_v1.types.InputConfig]): Required. Specify data to be imported.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.redis_v1.types.InputConfig`
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.redis_v1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "import_instance" not in self._inner_api_calls:
self._inner_api_calls[
"import_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.import_instance,
default_retry=self._method_configs["ImportInstance"].retry,
default_timeout=self._method_configs["ImportInstance"].timeout,
client_info=self._client_info,
)
request = cloud_redis_pb2.ImportInstanceRequest(
name=name, input_config=input_config
)
operation = self._inner_api_calls["import_instance"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
cloud_redis_pb2.Instance,
metadata_type=cloud_redis_pb2.OperationMetadata,
) | python | 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 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 deleted after a few hours, so
there is no need to call DeleteOperation.
Example:
>>> from google.cloud import redis_v1
>>>
>>> client = redis_v1.CloudRedisClient()
>>>
>>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]')
>>>
>>> # TODO: Initialize `input_config`:
>>> input_config = {}
>>>
>>> response = client.import_instance(name, input_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. Redis instance resource name using the form:
``projects/{project_id}/locations/{location_id}/instances/{instance_id}``
where ``location_id`` refers to a GCP region
input_config (Union[dict, ~google.cloud.redis_v1.types.InputConfig]): Required. Specify data to be imported.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.redis_v1.types.InputConfig`
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.redis_v1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "import_instance" not in self._inner_api_calls:
self._inner_api_calls[
"import_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.import_instance,
default_retry=self._method_configs["ImportInstance"].retry,
default_timeout=self._method_configs["ImportInstance"].timeout,
client_info=self._client_info,
)
request = cloud_redis_pb2.ImportInstanceRequest(
name=name, input_config=input_config
)
operation = self._inner_api_calls["import_instance"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
cloud_redis_pb2.Instance,
metadata_type=cloud_redis_pb2.OperationMetadata,
) | [
"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",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"import_instance\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"import_instance\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"import_instance",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"ImportInstance\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"ImportInstance\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"cloud_redis_pb2",
".",
"ImportInstanceRequest",
"(",
"name",
"=",
"name",
",",
"input_config",
"=",
"input_config",
")",
"operation",
"=",
"self",
".",
"_inner_api_calls",
"[",
"\"import_instance\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")",
"return",
"google",
".",
"api_core",
".",
"operation",
".",
"from_gapic",
"(",
"operation",
",",
"self",
".",
"transport",
".",
"_operations_client",
",",
"cloud_redis_pb2",
".",
"Instance",
",",
"metadata_type",
"=",
"cloud_redis_pb2",
".",
"OperationMetadata",
",",
")"
] | 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 deleted after a few hours, so
there is no need to call DeleteOperation.
Example:
>>> from google.cloud import redis_v1
>>>
>>> client = redis_v1.CloudRedisClient()
>>>
>>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]')
>>>
>>> # TODO: Initialize `input_config`:
>>> input_config = {}
>>>
>>> response = client.import_instance(name, input_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. Redis instance resource name using the form:
``projects/{project_id}/locations/{location_id}/instances/{instance_id}``
where ``location_id`` refers to a GCP region
input_config (Union[dict, ~google.cloud.redis_v1.types.InputConfig]): Required. Specify data to be imported.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.redis_v1.types.InputConfig`
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.redis_v1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Import",
"a",
"Redis",
"RDB",
"snapshot",
"file",
"from",
"GCS",
"into",
"a",
"Redis",
"instance",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/redis/google/cloud/redis_v1/gapic/cloud_redis_client.py#L646-L734 |
28,301 | googleapis/google-cloud-python | monitoring/google/cloud/monitoring_v3/gapic/notification_channel_service_client.py | NotificationChannelServiceClient.notification_channel_path | 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_channel=notification_channel,
) | python | 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_channel=notification_channel,
) | [
"def",
"notification_channel_path",
"(",
"cls",
",",
"project",
",",
"notification_channel",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/notificationChannels/{notification_channel}\"",
",",
"project",
"=",
"project",
",",
"notification_channel",
"=",
"notification_channel",
",",
")"
] | Return a fully-qualified notification_channel string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"notification_channel",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/gapic/notification_channel_service_client.py#L101-L107 |
28,302 | googleapis/google-cloud-python | monitoring/google/cloud/monitoring_v3/gapic/notification_channel_service_client.py | NotificationChannelServiceClient.notification_channel_descriptor_path | 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=project,
channel_descriptor=channel_descriptor,
) | python | 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=project,
channel_descriptor=channel_descriptor,
) | [
"def",
"notification_channel_descriptor_path",
"(",
"cls",
",",
"project",
",",
"channel_descriptor",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/notificationChannelDescriptors/{channel_descriptor}\"",
",",
"project",
"=",
"project",
",",
"channel_descriptor",
"=",
"channel_descriptor",
",",
")"
] | Return a fully-qualified notification_channel_descriptor string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"notification_channel_descriptor",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/gapic/notification_channel_service_client.py#L110-L116 |
28,303 | googleapis/google-cloud-python | logging/google/cloud/logging/logger.py | Logger.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 current topic.
:rtype: :class:`Batch`
:returns: A batch to use as a context manager.
"""
client = self._require_client(client)
return Batch(self, client) | python | 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 current topic.
:rtype: :class:`Batch`
:returns: A batch to use as a context manager.
"""
client = self._require_client(client)
return Batch(self, client) | [
"def",
"batch",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"return",
"Batch",
"(",
"self",
",",
"client",
")"
] | 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`
:returns: A batch to use as a context manager. | [
"Return",
"a",
"batch",
"to",
"use",
"as",
"a",
"context",
"manager",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/logger.py#L102-L114 |
28,304 | googleapis/google-cloud-python | logging/google/cloud/logging/logger.py | Batch.commit | 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 current batch.
"""
if client is None:
client = self.client
kwargs = {"logger_name": self.logger.full_name}
if self.resource is not None:
kwargs["resource"] = self.resource._to_dict()
if self.logger.labels is not None:
kwargs["labels"] = self.logger.labels
entries = [entry.to_api_repr() for entry in self.entries]
client.logging_api.write_entries(entries, **kwargs)
del self.entries[:] | python | 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 current batch.
"""
if client is None:
client = self.client
kwargs = {"logger_name": self.logger.full_name}
if self.resource is not None:
kwargs["resource"] = self.resource._to_dict()
if self.logger.labels is not None:
kwargs["labels"] = self.logger.labels
entries = [entry.to_api_repr() for entry in self.entries]
client.logging_api.write_entries(entries, **kwargs)
del self.entries[:] | [
"def",
"commit",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"if",
"client",
"is",
"None",
":",
"client",
"=",
"self",
".",
"client",
"kwargs",
"=",
"{",
"\"logger_name\"",
":",
"self",
".",
"logger",
".",
"full_name",
"}",
"if",
"self",
".",
"resource",
"is",
"not",
"None",
":",
"kwargs",
"[",
"\"resource\"",
"]",
"=",
"self",
".",
"resource",
".",
"_to_dict",
"(",
")",
"if",
"self",
".",
"logger",
".",
"labels",
"is",
"not",
"None",
":",
"kwargs",
"[",
"\"labels\"",
"]",
"=",
"self",
".",
"logger",
".",
"labels",
"entries",
"=",
"[",
"entry",
".",
"to_api_repr",
"(",
")",
"for",
"entry",
"in",
"self",
".",
"entries",
"]",
"client",
".",
"logging_api",
".",
"write_entries",
"(",
"entries",
",",
"*",
"*",
"kwargs",
")",
"del",
"self",
".",
"entries",
"[",
":",
"]"
] | 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. | [
"Send",
"saved",
"log",
"entries",
"as",
"a",
"single",
"API",
"call",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/logger.py#L362-L384 |
28,305 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _bytes_from_json | def _bytes_from_json(value, field):
"""Base64-decode value"""
if _not_null(value, field):
return base64.standard_b64decode(_to_bytes(value)) | python | def _bytes_from_json(value, field):
"""Base64-decode value"""
if _not_null(value, field):
return base64.standard_b64decode(_to_bytes(value)) | [
"def",
"_bytes_from_json",
"(",
"value",
",",
"field",
")",
":",
"if",
"_not_null",
"(",
"value",
",",
"field",
")",
":",
"return",
"base64",
".",
"standard_b64decode",
"(",
"_to_bytes",
"(",
"value",
")",
")"
] | Base64-decode value | [
"Base64",
"-",
"decode",
"value"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L68-L71 |
28,306 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _time_from_json | 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:
raise ValueError("Unknown time format: {}".format(value))
return datetime.datetime.strptime(value, fmt).time() | python | 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:
raise ValueError("Unknown time format: {}".format(value))
return datetime.datetime.strptime(value, fmt).time() | [
"def",
"_time_from_json",
"(",
"value",
",",
"field",
")",
":",
"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",
":",
"raise",
"ValueError",
"(",
"\"Unknown time format: {}\"",
".",
"format",
"(",
"value",
")",
")",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"value",
",",
"fmt",
")",
".",
"time",
"(",
")"
] | Coerce 'value' to a datetime date, if set or not nullable | [
"Coerce",
"value",
"to",
"a",
"datetime",
"date",
"if",
"set",
"or",
"not",
"nullable"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L146-L155 |
28,307 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _record_from_json | 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]
if subfield.mode == "REPEATED":
value = [converter(item["v"], subfield) for item in cell["v"]]
else:
value = converter(cell["v"], subfield)
record[subfield.name] = value
return record | python | 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]
if subfield.mode == "REPEATED":
value = [converter(item["v"], subfield) for item in cell["v"]]
else:
value = converter(cell["v"], subfield)
record[subfield.name] = value
return record | [
"def",
"_record_from_json",
"(",
"value",
",",
"field",
")",
":",
"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",
"]",
"if",
"subfield",
".",
"mode",
"==",
"\"REPEATED\"",
":",
"value",
"=",
"[",
"converter",
"(",
"item",
"[",
"\"v\"",
"]",
",",
"subfield",
")",
"for",
"item",
"in",
"cell",
"[",
"\"v\"",
"]",
"]",
"else",
":",
"value",
"=",
"converter",
"(",
"cell",
"[",
"\"v\"",
"]",
",",
"subfield",
")",
"record",
"[",
"subfield",
".",
"name",
"]",
"=",
"value",
"return",
"record"
] | Coerce 'value' to a mapping, if set or not nullable. | [
"Coerce",
"value",
"to",
"a",
"mapping",
"if",
"set",
"or",
"not",
"nullable",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L158-L170 |
28,308 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _row_tuple_from_json | 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
:class:`~google.cloud.bigquery.schema.SchemaField`.
:rtype: tuple
:returns: A tuple of data converted to native types.
"""
row_data = []
for field, cell in zip(schema, row["f"]):
converter = _CELLDATA_FROM_JSON[field.field_type]
if field.mode == "REPEATED":
row_data.append([converter(item["v"], field) for item in cell["v"]])
else:
row_data.append(converter(cell["v"], field))
return tuple(row_data) | python | 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
:class:`~google.cloud.bigquery.schema.SchemaField`.
:rtype: tuple
:returns: A tuple of data converted to native types.
"""
row_data = []
for field, cell in zip(schema, row["f"]):
converter = _CELLDATA_FROM_JSON[field.field_type]
if field.mode == "REPEATED":
row_data.append([converter(item["v"], field) for item in cell["v"]])
else:
row_data.append(converter(cell["v"], field))
return tuple(row_data) | [
"def",
"_row_tuple_from_json",
"(",
"row",
",",
"schema",
")",
":",
"row_data",
"=",
"[",
"]",
"for",
"field",
",",
"cell",
"in",
"zip",
"(",
"schema",
",",
"row",
"[",
"\"f\"",
"]",
")",
":",
"converter",
"=",
"_CELLDATA_FROM_JSON",
"[",
"field",
".",
"field_type",
"]",
"if",
"field",
".",
"mode",
"==",
"\"REPEATED\"",
":",
"row_data",
".",
"append",
"(",
"[",
"converter",
"(",
"item",
"[",
"\"v\"",
"]",
",",
"field",
")",
"for",
"item",
"in",
"cell",
"[",
"\"v\"",
"]",
"]",
")",
"else",
":",
"row_data",
".",
"append",
"(",
"converter",
"(",
"cell",
"[",
"\"v\"",
"]",
",",
"field",
")",
")",
"return",
"tuple",
"(",
"row_data",
")"
] | 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.SchemaField`.
:rtype: tuple
:returns: A tuple of data converted to native types. | [
"Convert",
"JSON",
"row",
"data",
"to",
"row",
"with",
"appropriate",
"types",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L200-L223 |
28,309 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _rows_from_json | 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] | python | 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] | [
"def",
"_rows_from_json",
"(",
"values",
",",
"schema",
")",
":",
"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",
"]"
] | Convert JSON row data to rows with appropriate types. | [
"Convert",
"JSON",
"row",
"data",
"to",
"rows",
"with",
"appropriate",
"types",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L226-L231 |
28,310 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _decimal_to_json | def _decimal_to_json(value):
"""Coerce 'value' to a JSON-compatible representation."""
if isinstance(value, decimal.Decimal):
value = str(value)
return value | python | def _decimal_to_json(value):
"""Coerce 'value' to a JSON-compatible representation."""
if isinstance(value, decimal.Decimal):
value = str(value)
return value | [
"def",
"_decimal_to_json",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"decimal",
".",
"Decimal",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"return",
"value"
] | Coerce 'value' to a JSON-compatible representation. | [
"Coerce",
"value",
"to",
"a",
"JSON",
"-",
"compatible",
"representation",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L246-L250 |
28,311 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _scalar_field_to_json | 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 be converted, based on the field's type.
Returns:
any:
A JSON-serializable object.
"""
converter = _SCALAR_VALUE_TO_JSON_ROW.get(field.field_type)
if converter is None: # STRING doesn't need converting
return row_value
return converter(row_value) | python | 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 be converted, based on the field's type.
Returns:
any:
A JSON-serializable object.
"""
converter = _SCALAR_VALUE_TO_JSON_ROW.get(field.field_type)
if converter is None: # STRING doesn't need converting
return row_value
return converter(row_value) | [
"def",
"_scalar_field_to_json",
"(",
"field",
",",
"row_value",
")",
":",
"converter",
"=",
"_SCALAR_VALUE_TO_JSON_ROW",
".",
"get",
"(",
"field",
".",
"field_type",
")",
"if",
"converter",
"is",
"None",
":",
"# STRING doesn't need converting",
"return",
"row_value",
"return",
"converter",
"(",
"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 be converted, based on the field's type.
Returns:
any:
A JSON-serializable object. | [
"Maps",
"a",
"field",
"and",
"value",
"to",
"a",
"JSON",
"-",
"safe",
"value",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L333-L351 |
28,312 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _field_to_json | 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[list], \
any, \
]):
Row data to be inserted. If the SchemaField's mode is
REPEATED, assume this is a list. If not, the type
is inferred from the SchemaField's field_type.
Returns:
any:
A JSON-serializable object.
"""
if row_value is None:
return None
if field.mode == "REPEATED":
return _repeated_field_to_json(field, row_value)
if field.field_type == "RECORD":
return _record_field_to_json(field.fields, row_value)
return _scalar_field_to_json(field, row_value) | python | 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[list], \
any, \
]):
Row data to be inserted. If the SchemaField's mode is
REPEATED, assume this is a list. If not, the type
is inferred from the SchemaField's field_type.
Returns:
any:
A JSON-serializable object.
"""
if row_value is None:
return None
if field.mode == "REPEATED":
return _repeated_field_to_json(field, row_value)
if field.field_type == "RECORD":
return _record_field_to_json(field.fields, row_value)
return _scalar_field_to_json(field, row_value) | [
"def",
"_field_to_json",
"(",
"field",
",",
"row_value",
")",
":",
"if",
"row_value",
"is",
"None",
":",
"return",
"None",
"if",
"field",
".",
"mode",
"==",
"\"REPEATED\"",
":",
"return",
"_repeated_field_to_json",
"(",
"field",
",",
"row_value",
")",
"if",
"field",
".",
"field_type",
"==",
"\"RECORD\"",
":",
"return",
"_record_field_to_json",
"(",
"field",
".",
"fields",
",",
"row_value",
")",
"return",
"_scalar_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[list], \
any, \
]):
Row data to be inserted. If the SchemaField's mode is
REPEATED, assume this is a list. If not, the type
is inferred from the SchemaField's field_type.
Returns:
any:
A JSON-serializable object. | [
"Convert",
"a",
"field",
"into",
"JSON",
"-",
"serializable",
"values",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L409-L439 |
28,313 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _snake_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:])) | python | 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:])) | [
"def",
"_snake_to_camel_case",
"(",
"value",
")",
":",
"words",
"=",
"value",
".",
"split",
"(",
"\"_\"",
")",
"return",
"words",
"[",
"0",
"]",
"+",
"\"\"",
".",
"join",
"(",
"map",
"(",
"str",
".",
"capitalize",
",",
"words",
"[",
"1",
":",
"]",
")",
")"
] | Convert snake case string to camel case. | [
"Convert",
"snake",
"case",
"string",
"to",
"camel",
"case",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L442-L445 |
28,314 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _get_sub_prop | 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 sequence of keys to attempt to get the value for. Each item in
the sequence represents a deeper nesting. The first key is for
the top level. If there is a dictionary there, the second key
attempts to get the value within that, and so on.
default (object):
(Optional) Value to returned if any of the keys are not found.
Defaults to ``None``.
Examples:
Get a top-level value (equivalent to ``container.get('key')``).
>>> _get_sub_prop({'key': 'value'}, ['key'])
'value'
Get a top-level value, providing a default (equivalent to
``container.get('key', default='default')``).
>>> _get_sub_prop({'nothere': 123}, ['key'], default='not found')
'not found'
Get a nested value.
>>> _get_sub_prop({'key': {'subkey': 'value'}}, ['key', 'subkey'])
'value'
Returns:
object: The value if present or the default.
"""
sub_val = container
for key in keys:
if key not in sub_val:
return default
sub_val = sub_val[key]
return sub_val | python | 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 sequence of keys to attempt to get the value for. Each item in
the sequence represents a deeper nesting. The first key is for
the top level. If there is a dictionary there, the second key
attempts to get the value within that, and so on.
default (object):
(Optional) Value to returned if any of the keys are not found.
Defaults to ``None``.
Examples:
Get a top-level value (equivalent to ``container.get('key')``).
>>> _get_sub_prop({'key': 'value'}, ['key'])
'value'
Get a top-level value, providing a default (equivalent to
``container.get('key', default='default')``).
>>> _get_sub_prop({'nothere': 123}, ['key'], default='not found')
'not found'
Get a nested value.
>>> _get_sub_prop({'key': {'subkey': 'value'}}, ['key', 'subkey'])
'value'
Returns:
object: The value if present or the default.
"""
sub_val = container
for key in keys:
if key not in sub_val:
return default
sub_val = sub_val[key]
return sub_val | [
"def",
"_get_sub_prop",
"(",
"container",
",",
"keys",
",",
"default",
"=",
"None",
")",
":",
"sub_val",
"=",
"container",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"not",
"in",
"sub_val",
":",
"return",
"default",
"sub_val",
"=",
"sub_val",
"[",
"key",
"]",
"return",
"sub_val"
] | 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 item in
the sequence represents a deeper nesting. The first key is for
the top level. If there is a dictionary there, the second key
attempts to get the value within that, and so on.
default (object):
(Optional) Value to returned if any of the keys are not found.
Defaults to ``None``.
Examples:
Get a top-level value (equivalent to ``container.get('key')``).
>>> _get_sub_prop({'key': 'value'}, ['key'])
'value'
Get a top-level value, providing a default (equivalent to
``container.get('key', default='default')``).
>>> _get_sub_prop({'nothere': 123}, ['key'], default='not found')
'not found'
Get a nested value.
>>> _get_sub_prop({'key': {'subkey': 'value'}}, ['key', 'subkey'])
'value'
Returns:
object: The value if present or the default. | [
"Get",
"a",
"nested",
"value",
"from",
"a",
"dictionary",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L448-L490 |
28,315 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _set_sub_prop | 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 sequence represents a deeper nesting. The first key is for
the top level. If there is a dictionary there, the second key
attempts to get the value within that, and so on.
value (object): Value to set within the container.
Examples:
Set a top-level value (equivalent to ``container['key'] = 'value'``).
>>> container = {}
>>> _set_sub_prop(container, ['key'], 'value')
>>> container
{'key': 'value'}
Set a nested value.
>>> container = {}
>>> _set_sub_prop(container, ['key', 'subkey'], 'value')
>>> container
{'key': {'subkey': 'value'}}
Replace a nested value.
>>> container = {'key': {'subkey': 'prev'}}
>>> _set_sub_prop(container, ['key', 'subkey'], 'new')
>>> container
{'key': {'subkey': 'new'}}
"""
sub_val = container
for key in keys[:-1]:
if key not in sub_val:
sub_val[key] = {}
sub_val = sub_val[key]
sub_val[keys[-1]] = value | python | 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 sequence represents a deeper nesting. The first key is for
the top level. If there is a dictionary there, the second key
attempts to get the value within that, and so on.
value (object): Value to set within the container.
Examples:
Set a top-level value (equivalent to ``container['key'] = 'value'``).
>>> container = {}
>>> _set_sub_prop(container, ['key'], 'value')
>>> container
{'key': 'value'}
Set a nested value.
>>> container = {}
>>> _set_sub_prop(container, ['key', 'subkey'], 'value')
>>> container
{'key': {'subkey': 'value'}}
Replace a nested value.
>>> container = {'key': {'subkey': 'prev'}}
>>> _set_sub_prop(container, ['key', 'subkey'], 'new')
>>> container
{'key': {'subkey': 'new'}}
"""
sub_val = container
for key in keys[:-1]:
if key not in sub_val:
sub_val[key] = {}
sub_val = sub_val[key]
sub_val[keys[-1]] = value | [
"def",
"_set_sub_prop",
"(",
"container",
",",
"keys",
",",
"value",
")",
":",
"sub_val",
"=",
"container",
"for",
"key",
"in",
"keys",
"[",
":",
"-",
"1",
"]",
":",
"if",
"key",
"not",
"in",
"sub_val",
":",
"sub_val",
"[",
"key",
"]",
"=",
"{",
"}",
"sub_val",
"=",
"sub_val",
"[",
"key",
"]",
"sub_val",
"[",
"keys",
"[",
"-",
"1",
"]",
"]",
"=",
"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 sequence represents a deeper nesting. The first key is for
the top level. If there is a dictionary there, the second key
attempts to get the value within that, and so on.
value (object): Value to set within the container.
Examples:
Set a top-level value (equivalent to ``container['key'] = 'value'``).
>>> container = {}
>>> _set_sub_prop(container, ['key'], 'value')
>>> container
{'key': 'value'}
Set a nested value.
>>> container = {}
>>> _set_sub_prop(container, ['key', 'subkey'], 'value')
>>> container
{'key': {'subkey': 'value'}}
Replace a nested value.
>>> container = {'key': {'subkey': 'prev'}}
>>> _set_sub_prop(container, ['key', 'subkey'], 'new')
>>> container
{'key': {'subkey': 'new'}} | [
"Set",
"a",
"nested",
"value",
"in",
"a",
"dictionary",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L493-L533 |
28,316 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _del_sub_prop | 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 sequence represents a deeper nesting. The first key is for
the top level. If there is a dictionary there, the second key
attempts to get the value within that, and so on.
Examples:
Remove a top-level value (equivalent to ``del container['key']``).
>>> container = {'key': 'value'}
>>> _del_sub_prop(container, ['key'])
>>> container
{}
Remove a nested value.
>>> container = {'key': {'subkey': 'value'}}
>>> _del_sub_prop(container, ['key', 'subkey'])
>>> container
{'key': {}}
"""
sub_val = container
for key in keys[:-1]:
if key not in sub_val:
sub_val[key] = {}
sub_val = sub_val[key]
if keys[-1] in sub_val:
del sub_val[keys[-1]] | python | 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 sequence represents a deeper nesting. The first key is for
the top level. If there is a dictionary there, the second key
attempts to get the value within that, and so on.
Examples:
Remove a top-level value (equivalent to ``del container['key']``).
>>> container = {'key': 'value'}
>>> _del_sub_prop(container, ['key'])
>>> container
{}
Remove a nested value.
>>> container = {'key': {'subkey': 'value'}}
>>> _del_sub_prop(container, ['key', 'subkey'])
>>> container
{'key': {}}
"""
sub_val = container
for key in keys[:-1]:
if key not in sub_val:
sub_val[key] = {}
sub_val = sub_val[key]
if keys[-1] in sub_val:
del sub_val[keys[-1]] | [
"def",
"_del_sub_prop",
"(",
"container",
",",
"keys",
")",
":",
"sub_val",
"=",
"container",
"for",
"key",
"in",
"keys",
"[",
":",
"-",
"1",
"]",
":",
"if",
"key",
"not",
"in",
"sub_val",
":",
"sub_val",
"[",
"key",
"]",
"=",
"{",
"}",
"sub_val",
"=",
"sub_val",
"[",
"key",
"]",
"if",
"keys",
"[",
"-",
"1",
"]",
"in",
"sub_val",
":",
"del",
"sub_val",
"[",
"keys",
"[",
"-",
"1",
"]",
"]"
] | 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 key is for
the top level. If there is a dictionary there, the second key
attempts to get the value within that, and so on.
Examples:
Remove a top-level value (equivalent to ``del container['key']``).
>>> container = {'key': 'value'}
>>> _del_sub_prop(container, ['key'])
>>> container
{}
Remove a nested value.
>>> container = {'key': {'subkey': 'value'}}
>>> _del_sub_prop(container, ['key', 'subkey'])
>>> container
{'key': {}} | [
"Remove",
"a",
"nested",
"key",
"fro",
"a",
"dictionary",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L536-L569 |
28,317 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/_helpers.py | _build_resource_from_properties | 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_field)
if api_field is None and filter_field not in obj._properties:
raise ValueError("No property %s" % filter_field)
elif api_field is not None:
partial[api_field] = obj._properties.get(api_field)
else:
# allows properties that are not defined in the library
# and properties that have the same name as API resource key
partial[filter_field] = obj._properties[filter_field]
return partial | python | 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_field)
if api_field is None and filter_field not in obj._properties:
raise ValueError("No property %s" % filter_field)
elif api_field is not None:
partial[api_field] = obj._properties.get(api_field)
else:
# allows properties that are not defined in the library
# and properties that have the same name as API resource key
partial[filter_field] = obj._properties[filter_field]
return partial | [
"def",
"_build_resource_from_properties",
"(",
"obj",
",",
"filter_fields",
")",
":",
"partial",
"=",
"{",
"}",
"for",
"filter_field",
"in",
"filter_fields",
":",
"api_field",
"=",
"obj",
".",
"_PROPERTY_TO_API_FIELD",
".",
"get",
"(",
"filter_field",
")",
"if",
"api_field",
"is",
"None",
"and",
"filter_field",
"not",
"in",
"obj",
".",
"_properties",
":",
"raise",
"ValueError",
"(",
"\"No property %s\"",
"%",
"filter_field",
")",
"elif",
"api_field",
"is",
"not",
"None",
":",
"partial",
"[",
"api_field",
"]",
"=",
"obj",
".",
"_properties",
".",
"get",
"(",
"api_field",
")",
"else",
":",
"# allows properties that are not defined in the library",
"# and properties that have the same name as API resource key",
"partial",
"[",
"filter_field",
"]",
"=",
"obj",
".",
"_properties",
"[",
"filter_field",
"]",
"return",
"partial"
] | Build a resource based on a ``_properties`` dictionary, filtered by
``filter_fields``, which follow the name of the Python object. | [
"Build",
"a",
"resource",
"based",
"on",
"a",
"_properties",
"dictionary",
"filtered",
"by",
"filter_fields",
"which",
"follow",
"the",
"name",
"of",
"the",
"Python",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/_helpers.py#L616-L632 |
28,318 | googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | _check_database_id | 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 = _DATABASE_ID_TEMPLATE.format(database_id)
raise ValueError(msg) | python | 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 = _DATABASE_ID_TEMPLATE.format(database_id)
raise ValueError(msg) | [
"def",
"_check_database_id",
"(",
"database_id",
")",
":",
"if",
"database_id",
"!=",
"u\"\"",
":",
"msg",
"=",
"_DATABASE_ID_TEMPLATE",
".",
"format",
"(",
"database_id",
")",
"raise",
"ValueError",
"(",
"msg",
")"
] | 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. | [
"Make",
"sure",
"a",
"Reference",
"database",
"ID",
"is",
"empty",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L549-L559 |
28,319 | googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | _add_id_or_name | 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.
:type empty_allowed: bool
:param empty_allowed: Indicates if neither ID or name need be set. If
:data:`False`, then **exactly** one of them must be.
:raises: :exc:`ValueError` if 0 or 2 of ID/name are set (unless
``empty_allowed=True`` and 0 are set).
"""
id_ = element_pb.id
name = element_pb.name
# NOTE: Below 0 and the empty string are the "null" values for their
# respective types, indicating that the value is unset.
if id_ == 0:
if name == u"":
if not empty_allowed:
raise ValueError(_EMPTY_ELEMENT)
else:
flat_path.append(name)
else:
if name == u"":
flat_path.append(id_)
else:
msg = _BAD_ELEMENT_TEMPLATE.format(id_, name)
raise ValueError(msg) | python | 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.
:type empty_allowed: bool
:param empty_allowed: Indicates if neither ID or name need be set. If
:data:`False`, then **exactly** one of them must be.
:raises: :exc:`ValueError` if 0 or 2 of ID/name are set (unless
``empty_allowed=True`` and 0 are set).
"""
id_ = element_pb.id
name = element_pb.name
# NOTE: Below 0 and the empty string are the "null" values for their
# respective types, indicating that the value is unset.
if id_ == 0:
if name == u"":
if not empty_allowed:
raise ValueError(_EMPTY_ELEMENT)
else:
flat_path.append(name)
else:
if name == u"":
flat_path.append(id_)
else:
msg = _BAD_ELEMENT_TEMPLATE.format(id_, name)
raise ValueError(msg) | [
"def",
"_add_id_or_name",
"(",
"flat_path",
",",
"element_pb",
",",
"empty_allowed",
")",
":",
"id_",
"=",
"element_pb",
".",
"id",
"name",
"=",
"element_pb",
".",
"name",
"# NOTE: Below 0 and the empty string are the \"null\" values for their",
"# respective types, indicating that the value is unset.",
"if",
"id_",
"==",
"0",
":",
"if",
"name",
"==",
"u\"\"",
":",
"if",
"not",
"empty_allowed",
":",
"raise",
"ValueError",
"(",
"_EMPTY_ELEMENT",
")",
"else",
":",
"flat_path",
".",
"append",
"(",
"name",
")",
"else",
":",
"if",
"name",
"==",
"u\"\"",
":",
"flat_path",
".",
"append",
"(",
"id_",
")",
"else",
":",
"msg",
"=",
"_BAD_ELEMENT_TEMPLATE",
".",
"format",
"(",
"id_",
",",
"name",
")",
"raise",
"ValueError",
"(",
"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 neither ID or name need be set. If
:data:`False`, then **exactly** one of them must be.
:raises: :exc:`ValueError` if 0 or 2 of ID/name are set (unless
``empty_allowed=True`` and 0 are set). | [
"Add",
"the",
"ID",
"or",
"name",
"from",
"an",
"element",
"to",
"a",
"list",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L562-L593 |
28,320 | googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | _get_flat_path | 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 path_pb: :class:`._app_engine_key_pb2.Path`
:param path_pb: Legacy protobuf "Path" object (from a "Reference").
:rtype: tuple
:returns: The path parts from ``path_pb``.
"""
num_elts = len(path_pb.element)
last_index = num_elts - 1
result = []
for index, element in enumerate(path_pb.element):
result.append(element.type)
_add_id_or_name(result, element, index == last_index)
return tuple(result) | python | 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 path_pb: :class:`._app_engine_key_pb2.Path`
:param path_pb: Legacy protobuf "Path" object (from a "Reference").
:rtype: tuple
:returns: The path parts from ``path_pb``.
"""
num_elts = len(path_pb.element)
last_index = num_elts - 1
result = []
for index, element in enumerate(path_pb.element):
result.append(element.type)
_add_id_or_name(result, element, index == last_index)
return tuple(result) | [
"def",
"_get_flat_path",
"(",
"path_pb",
")",
":",
"num_elts",
"=",
"len",
"(",
"path_pb",
".",
"element",
")",
"last_index",
"=",
"num_elts",
"-",
"1",
"result",
"=",
"[",
"]",
"for",
"index",
",",
"element",
"in",
"enumerate",
"(",
"path_pb",
".",
"element",
")",
":",
"result",
".",
"append",
"(",
"element",
".",
"type",
")",
"_add_id_or_name",
"(",
"result",
",",
"element",
",",
"index",
"==",
"last_index",
")",
"return",
"tuple",
"(",
"result",
")"
] | 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.Path`
:param path_pb: Legacy protobuf "Path" object (from a "Reference").
:rtype: tuple
:returns: The path parts from ``path_pb``. | [
"Convert",
"a",
"legacy",
"Path",
"protobuf",
"to",
"a",
"flat",
"path",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L596-L626 |
28,321 | googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | _to_legacy_path | def _to_legacy_path(dict_path):
"""Convert a tuple of ints and strings in a legacy "Path".
.. note:
This assumes, but does not verify, that each entry in
``dict_path`` is valid (i.e. doesn't have more than one
key out of "name" / "id").
:type dict_path: lsit
:param dict_path: The "structured" path for a key, i.e. it
is a list of dictionaries, each of which has
"kind" and one of "name" / "id" as keys.
:rtype: :class:`._app_engine_key_pb2.Path`
:returns: The legacy path corresponding to ``dict_path``.
"""
elements = []
for part in dict_path:
element_kwargs = {"type": part["kind"]}
if "id" in part:
element_kwargs["id"] = part["id"]
elif "name" in part:
element_kwargs["name"] = part["name"]
element = _app_engine_key_pb2.Path.Element(**element_kwargs)
elements.append(element)
return _app_engine_key_pb2.Path(element=elements) | python | def _to_legacy_path(dict_path):
"""Convert a tuple of ints and strings in a legacy "Path".
.. note:
This assumes, but does not verify, that each entry in
``dict_path`` is valid (i.e. doesn't have more than one
key out of "name" / "id").
:type dict_path: lsit
:param dict_path: The "structured" path for a key, i.e. it
is a list of dictionaries, each of which has
"kind" and one of "name" / "id" as keys.
:rtype: :class:`._app_engine_key_pb2.Path`
:returns: The legacy path corresponding to ``dict_path``.
"""
elements = []
for part in dict_path:
element_kwargs = {"type": part["kind"]}
if "id" in part:
element_kwargs["id"] = part["id"]
elif "name" in part:
element_kwargs["name"] = part["name"]
element = _app_engine_key_pb2.Path.Element(**element_kwargs)
elements.append(element)
return _app_engine_key_pb2.Path(element=elements) | [
"def",
"_to_legacy_path",
"(",
"dict_path",
")",
":",
"elements",
"=",
"[",
"]",
"for",
"part",
"in",
"dict_path",
":",
"element_kwargs",
"=",
"{",
"\"type\"",
":",
"part",
"[",
"\"kind\"",
"]",
"}",
"if",
"\"id\"",
"in",
"part",
":",
"element_kwargs",
"[",
"\"id\"",
"]",
"=",
"part",
"[",
"\"id\"",
"]",
"elif",
"\"name\"",
"in",
"part",
":",
"element_kwargs",
"[",
"\"name\"",
"]",
"=",
"part",
"[",
"\"name\"",
"]",
"element",
"=",
"_app_engine_key_pb2",
".",
"Path",
".",
"Element",
"(",
"*",
"*",
"element_kwargs",
")",
"elements",
".",
"append",
"(",
"element",
")",
"return",
"_app_engine_key_pb2",
".",
"Path",
"(",
"element",
"=",
"elements",
")"
] | Convert a tuple of ints and strings in a legacy "Path".
.. note:
This assumes, but does not verify, that each entry in
``dict_path`` is valid (i.e. doesn't have more than one
key out of "name" / "id").
:type dict_path: lsit
:param dict_path: The "structured" path for a key, i.e. it
is a list of dictionaries, each of which has
"kind" and one of "name" / "id" as keys.
:rtype: :class:`._app_engine_key_pb2.Path`
:returns: The legacy path corresponding to ``dict_path``. | [
"Convert",
"a",
"tuple",
"of",
"ints",
"and",
"strings",
"in",
"a",
"legacy",
"Path",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L629-L656 |
28,322 | googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | Key._parse_path | def _parse_path(path_args):
"""Parses positional arguments into key path with kinds and IDs.
:type path_args: tuple
:param path_args: A tuple from positional arguments. Should be
alternating list of kinds (string) and ID/name
parts (int or string).
:rtype: :class:`list` of :class:`dict`
:returns: A list of key parts with kind and ID or name set.
:raises: :class:`ValueError` if there are no ``path_args``, if one of
the kinds is not a string or if one of the IDs/names is not
a string or an integer.
"""
if len(path_args) == 0:
raise ValueError("Key path must not be empty.")
kind_list = path_args[::2]
id_or_name_list = path_args[1::2]
# Dummy sentinel value to pad incomplete key to even length path.
partial_ending = object()
if len(path_args) % 2 == 1:
id_or_name_list += (partial_ending,)
result = []
for kind, id_or_name in zip(kind_list, id_or_name_list):
curr_key_part = {}
if isinstance(kind, six.string_types):
curr_key_part["kind"] = kind
else:
raise ValueError(kind, "Kind was not a string.")
if isinstance(id_or_name, six.string_types):
curr_key_part["name"] = id_or_name
elif isinstance(id_or_name, six.integer_types):
curr_key_part["id"] = id_or_name
elif id_or_name is not partial_ending:
raise ValueError(id_or_name, "ID/name was not a string or integer.")
result.append(curr_key_part)
return result | python | def _parse_path(path_args):
"""Parses positional arguments into key path with kinds and IDs.
:type path_args: tuple
:param path_args: A tuple from positional arguments. Should be
alternating list of kinds (string) and ID/name
parts (int or string).
:rtype: :class:`list` of :class:`dict`
:returns: A list of key parts with kind and ID or name set.
:raises: :class:`ValueError` if there are no ``path_args``, if one of
the kinds is not a string or if one of the IDs/names is not
a string or an integer.
"""
if len(path_args) == 0:
raise ValueError("Key path must not be empty.")
kind_list = path_args[::2]
id_or_name_list = path_args[1::2]
# Dummy sentinel value to pad incomplete key to even length path.
partial_ending = object()
if len(path_args) % 2 == 1:
id_or_name_list += (partial_ending,)
result = []
for kind, id_or_name in zip(kind_list, id_or_name_list):
curr_key_part = {}
if isinstance(kind, six.string_types):
curr_key_part["kind"] = kind
else:
raise ValueError(kind, "Kind was not a string.")
if isinstance(id_or_name, six.string_types):
curr_key_part["name"] = id_or_name
elif isinstance(id_or_name, six.integer_types):
curr_key_part["id"] = id_or_name
elif id_or_name is not partial_ending:
raise ValueError(id_or_name, "ID/name was not a string or integer.")
result.append(curr_key_part)
return result | [
"def",
"_parse_path",
"(",
"path_args",
")",
":",
"if",
"len",
"(",
"path_args",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Key path must not be empty.\"",
")",
"kind_list",
"=",
"path_args",
"[",
":",
":",
"2",
"]",
"id_or_name_list",
"=",
"path_args",
"[",
"1",
":",
":",
"2",
"]",
"# Dummy sentinel value to pad incomplete key to even length path.",
"partial_ending",
"=",
"object",
"(",
")",
"if",
"len",
"(",
"path_args",
")",
"%",
"2",
"==",
"1",
":",
"id_or_name_list",
"+=",
"(",
"partial_ending",
",",
")",
"result",
"=",
"[",
"]",
"for",
"kind",
",",
"id_or_name",
"in",
"zip",
"(",
"kind_list",
",",
"id_or_name_list",
")",
":",
"curr_key_part",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"kind",
",",
"six",
".",
"string_types",
")",
":",
"curr_key_part",
"[",
"\"kind\"",
"]",
"=",
"kind",
"else",
":",
"raise",
"ValueError",
"(",
"kind",
",",
"\"Kind was not a string.\"",
")",
"if",
"isinstance",
"(",
"id_or_name",
",",
"six",
".",
"string_types",
")",
":",
"curr_key_part",
"[",
"\"name\"",
"]",
"=",
"id_or_name",
"elif",
"isinstance",
"(",
"id_or_name",
",",
"six",
".",
"integer_types",
")",
":",
"curr_key_part",
"[",
"\"id\"",
"]",
"=",
"id_or_name",
"elif",
"id_or_name",
"is",
"not",
"partial_ending",
":",
"raise",
"ValueError",
"(",
"id_or_name",
",",
"\"ID/name was not a string or integer.\"",
")",
"result",
".",
"append",
"(",
"curr_key_part",
")",
"return",
"result"
] | Parses positional arguments into key path with kinds and IDs.
:type path_args: tuple
:param path_args: A tuple from positional arguments. Should be
alternating list of kinds (string) and ID/name
parts (int or string).
:rtype: :class:`list` of :class:`dict`
:returns: A list of key parts with kind and ID or name set.
:raises: :class:`ValueError` if there are no ``path_args``, if one of
the kinds is not a string or if one of the IDs/names is not
a string or an integer. | [
"Parses",
"positional",
"arguments",
"into",
"key",
"path",
"with",
"kinds",
"and",
"IDs",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L162-L203 |
28,323 | googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | Key._combine_args | def _combine_args(self):
"""Sets protected data by combining raw data set from the constructor.
If a ``_parent`` is set, updates the ``_flat_path`` and sets the
``_namespace`` and ``_project`` if not already set.
:rtype: :class:`list` of :class:`dict`
:returns: A list of key parts with kind and ID or name set.
:raises: :class:`ValueError` if the parent key is not complete.
"""
child_path = self._parse_path(self._flat_path)
if self._parent is not None:
if self._parent.is_partial:
raise ValueError("Parent key must be complete.")
# We know that _parent.path() will return a copy.
child_path = self._parent.path + child_path
self._flat_path = self._parent.flat_path + self._flat_path
if (
self._namespace is not None
and self._namespace != self._parent.namespace
):
raise ValueError("Child namespace must agree with parent's.")
self._namespace = self._parent.namespace
if self._project is not None and self._project != self._parent.project:
raise ValueError("Child project must agree with parent's.")
self._project = self._parent.project
return child_path | python | def _combine_args(self):
"""Sets protected data by combining raw data set from the constructor.
If a ``_parent`` is set, updates the ``_flat_path`` and sets the
``_namespace`` and ``_project`` if not already set.
:rtype: :class:`list` of :class:`dict`
:returns: A list of key parts with kind and ID or name set.
:raises: :class:`ValueError` if the parent key is not complete.
"""
child_path = self._parse_path(self._flat_path)
if self._parent is not None:
if self._parent.is_partial:
raise ValueError("Parent key must be complete.")
# We know that _parent.path() will return a copy.
child_path = self._parent.path + child_path
self._flat_path = self._parent.flat_path + self._flat_path
if (
self._namespace is not None
and self._namespace != self._parent.namespace
):
raise ValueError("Child namespace must agree with parent's.")
self._namespace = self._parent.namespace
if self._project is not None and self._project != self._parent.project:
raise ValueError("Child project must agree with parent's.")
self._project = self._parent.project
return child_path | [
"def",
"_combine_args",
"(",
"self",
")",
":",
"child_path",
"=",
"self",
".",
"_parse_path",
"(",
"self",
".",
"_flat_path",
")",
"if",
"self",
".",
"_parent",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_parent",
".",
"is_partial",
":",
"raise",
"ValueError",
"(",
"\"Parent key must be complete.\"",
")",
"# We know that _parent.path() will return a copy.",
"child_path",
"=",
"self",
".",
"_parent",
".",
"path",
"+",
"child_path",
"self",
".",
"_flat_path",
"=",
"self",
".",
"_parent",
".",
"flat_path",
"+",
"self",
".",
"_flat_path",
"if",
"(",
"self",
".",
"_namespace",
"is",
"not",
"None",
"and",
"self",
".",
"_namespace",
"!=",
"self",
".",
"_parent",
".",
"namespace",
")",
":",
"raise",
"ValueError",
"(",
"\"Child namespace must agree with parent's.\"",
")",
"self",
".",
"_namespace",
"=",
"self",
".",
"_parent",
".",
"namespace",
"if",
"self",
".",
"_project",
"is",
"not",
"None",
"and",
"self",
".",
"_project",
"!=",
"self",
".",
"_parent",
".",
"project",
":",
"raise",
"ValueError",
"(",
"\"Child project must agree with parent's.\"",
")",
"self",
".",
"_project",
"=",
"self",
".",
"_parent",
".",
"project",
"return",
"child_path"
] | Sets protected data by combining raw data set from the constructor.
If a ``_parent`` is set, updates the ``_flat_path`` and sets the
``_namespace`` and ``_project`` if not already set.
:rtype: :class:`list` of :class:`dict`
:returns: A list of key parts with kind and ID or name set.
:raises: :class:`ValueError` if the parent key is not complete. | [
"Sets",
"protected",
"data",
"by",
"combining",
"raw",
"data",
"set",
"from",
"the",
"constructor",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L205-L234 |
28,324 | googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | Key._clone | def _clone(self):
"""Duplicates the Key.
Most attributes are simple types, so don't require copying. Other
attributes like ``parent`` are long-lived and so we re-use them.
:rtype: :class:`google.cloud.datastore.key.Key`
:returns: A new ``Key`` instance with the same data as the current one.
"""
cloned_self = self.__class__(
*self.flat_path, project=self.project, namespace=self.namespace
)
# If the current parent has already been set, we re-use
# the same instance
cloned_self._parent = self._parent
return cloned_self | python | def _clone(self):
"""Duplicates the Key.
Most attributes are simple types, so don't require copying. Other
attributes like ``parent`` are long-lived and so we re-use them.
:rtype: :class:`google.cloud.datastore.key.Key`
:returns: A new ``Key`` instance with the same data as the current one.
"""
cloned_self = self.__class__(
*self.flat_path, project=self.project, namespace=self.namespace
)
# If the current parent has already been set, we re-use
# the same instance
cloned_self._parent = self._parent
return cloned_self | [
"def",
"_clone",
"(",
"self",
")",
":",
"cloned_self",
"=",
"self",
".",
"__class__",
"(",
"*",
"self",
".",
"flat_path",
",",
"project",
"=",
"self",
".",
"project",
",",
"namespace",
"=",
"self",
".",
"namespace",
")",
"# If the current parent has already been set, we re-use",
"# the same instance",
"cloned_self",
".",
"_parent",
"=",
"self",
".",
"_parent",
"return",
"cloned_self"
] | Duplicates the Key.
Most attributes are simple types, so don't require copying. Other
attributes like ``parent`` are long-lived and so we re-use them.
:rtype: :class:`google.cloud.datastore.key.Key`
:returns: A new ``Key`` instance with the same data as the current one. | [
"Duplicates",
"the",
"Key",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L236-L251 |
28,325 | googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | Key.to_protobuf | def to_protobuf(self):
"""Return a protobuf corresponding to the key.
:rtype: :class:`.entity_pb2.Key`
:returns: The protobuf representing the key.
"""
key = _entity_pb2.Key()
key.partition_id.project_id = self.project
if self.namespace:
key.partition_id.namespace_id = self.namespace
for item in self.path:
element = key.path.add()
if "kind" in item:
element.kind = item["kind"]
if "id" in item:
element.id = item["id"]
if "name" in item:
element.name = item["name"]
return key | python | def to_protobuf(self):
"""Return a protobuf corresponding to the key.
:rtype: :class:`.entity_pb2.Key`
:returns: The protobuf representing the key.
"""
key = _entity_pb2.Key()
key.partition_id.project_id = self.project
if self.namespace:
key.partition_id.namespace_id = self.namespace
for item in self.path:
element = key.path.add()
if "kind" in item:
element.kind = item["kind"]
if "id" in item:
element.id = item["id"]
if "name" in item:
element.name = item["name"]
return key | [
"def",
"to_protobuf",
"(",
"self",
")",
":",
"key",
"=",
"_entity_pb2",
".",
"Key",
"(",
")",
"key",
".",
"partition_id",
".",
"project_id",
"=",
"self",
".",
"project",
"if",
"self",
".",
"namespace",
":",
"key",
".",
"partition_id",
".",
"namespace_id",
"=",
"self",
".",
"namespace",
"for",
"item",
"in",
"self",
".",
"path",
":",
"element",
"=",
"key",
".",
"path",
".",
"add",
"(",
")",
"if",
"\"kind\"",
"in",
"item",
":",
"element",
".",
"kind",
"=",
"item",
"[",
"\"kind\"",
"]",
"if",
"\"id\"",
"in",
"item",
":",
"element",
".",
"id",
"=",
"item",
"[",
"\"id\"",
"]",
"if",
"\"name\"",
"in",
"item",
":",
"element",
".",
"name",
"=",
"item",
"[",
"\"name\"",
"]",
"return",
"key"
] | Return a protobuf corresponding to the key.
:rtype: :class:`.entity_pb2.Key`
:returns: The protobuf representing the key. | [
"Return",
"a",
"protobuf",
"corresponding",
"to",
"the",
"key",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L280-L301 |
28,326 | googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | Key.to_legacy_urlsafe | def to_legacy_urlsafe(self, location_prefix=None):
"""Convert to a base64 encode urlsafe string for App Engine.
This is intended to work with the "legacy" representation of a
datastore "Key" used within Google App Engine (a so-called
"Reference"). The returned string can be used as the ``urlsafe``
argument to ``ndb.Key(urlsafe=...)``. The base64 encoded values
will have padding removed.
.. note::
The string returned by ``to_legacy_urlsafe`` is equivalent, but
not identical, to the string returned by ``ndb``. The location
prefix may need to be specified to obtain identical urlsafe
keys.
:type location_prefix: str
:param location_prefix: The location prefix of an App Engine project
ID. Often this value is 's~', but may also be
'e~', or other location prefixes currently
unknown.
:rtype: bytes
:returns: A bytestring containing the key encoded as URL-safe base64.
"""
if location_prefix is None:
project_id = self.project
else:
project_id = location_prefix + self.project
reference = _app_engine_key_pb2.Reference(
app=project_id,
path=_to_legacy_path(self._path), # Avoid the copy.
name_space=self.namespace,
)
raw_bytes = reference.SerializeToString()
return base64.urlsafe_b64encode(raw_bytes).strip(b"=") | python | def to_legacy_urlsafe(self, location_prefix=None):
"""Convert to a base64 encode urlsafe string for App Engine.
This is intended to work with the "legacy" representation of a
datastore "Key" used within Google App Engine (a so-called
"Reference"). The returned string can be used as the ``urlsafe``
argument to ``ndb.Key(urlsafe=...)``. The base64 encoded values
will have padding removed.
.. note::
The string returned by ``to_legacy_urlsafe`` is equivalent, but
not identical, to the string returned by ``ndb``. The location
prefix may need to be specified to obtain identical urlsafe
keys.
:type location_prefix: str
:param location_prefix: The location prefix of an App Engine project
ID. Often this value is 's~', but may also be
'e~', or other location prefixes currently
unknown.
:rtype: bytes
:returns: A bytestring containing the key encoded as URL-safe base64.
"""
if location_prefix is None:
project_id = self.project
else:
project_id = location_prefix + self.project
reference = _app_engine_key_pb2.Reference(
app=project_id,
path=_to_legacy_path(self._path), # Avoid the copy.
name_space=self.namespace,
)
raw_bytes = reference.SerializeToString()
return base64.urlsafe_b64encode(raw_bytes).strip(b"=") | [
"def",
"to_legacy_urlsafe",
"(",
"self",
",",
"location_prefix",
"=",
"None",
")",
":",
"if",
"location_prefix",
"is",
"None",
":",
"project_id",
"=",
"self",
".",
"project",
"else",
":",
"project_id",
"=",
"location_prefix",
"+",
"self",
".",
"project",
"reference",
"=",
"_app_engine_key_pb2",
".",
"Reference",
"(",
"app",
"=",
"project_id",
",",
"path",
"=",
"_to_legacy_path",
"(",
"self",
".",
"_path",
")",
",",
"# Avoid the copy.",
"name_space",
"=",
"self",
".",
"namespace",
",",
")",
"raw_bytes",
"=",
"reference",
".",
"SerializeToString",
"(",
")",
"return",
"base64",
".",
"urlsafe_b64encode",
"(",
"raw_bytes",
")",
".",
"strip",
"(",
"b\"=\"",
")"
] | Convert to a base64 encode urlsafe string for App Engine.
This is intended to work with the "legacy" representation of a
datastore "Key" used within Google App Engine (a so-called
"Reference"). The returned string can be used as the ``urlsafe``
argument to ``ndb.Key(urlsafe=...)``. The base64 encoded values
will have padding removed.
.. note::
The string returned by ``to_legacy_urlsafe`` is equivalent, but
not identical, to the string returned by ``ndb``. The location
prefix may need to be specified to obtain identical urlsafe
keys.
:type location_prefix: str
:param location_prefix: The location prefix of an App Engine project
ID. Often this value is 's~', but may also be
'e~', or other location prefixes currently
unknown.
:rtype: bytes
:returns: A bytestring containing the key encoded as URL-safe base64. | [
"Convert",
"to",
"a",
"base64",
"encode",
"urlsafe",
"string",
"for",
"App",
"Engine",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L303-L339 |
28,327 | googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | Key._make_parent | def _make_parent(self):
"""Creates a parent key for the current path.
Extracts all but the last element in the key path and creates a new
key, while still matching the namespace and the project.
:rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`
:returns: A new ``Key`` instance, whose path consists of all but the
last element of current path. If the current key has only
one path element, returns ``None``.
"""
if self.is_partial:
parent_args = self.flat_path[:-1]
else:
parent_args = self.flat_path[:-2]
if parent_args:
return self.__class__(
*parent_args, project=self.project, namespace=self.namespace
) | python | def _make_parent(self):
"""Creates a parent key for the current path.
Extracts all but the last element in the key path and creates a new
key, while still matching the namespace and the project.
:rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`
:returns: A new ``Key`` instance, whose path consists of all but the
last element of current path. If the current key has only
one path element, returns ``None``.
"""
if self.is_partial:
parent_args = self.flat_path[:-1]
else:
parent_args = self.flat_path[:-2]
if parent_args:
return self.__class__(
*parent_args, project=self.project, namespace=self.namespace
) | [
"def",
"_make_parent",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_partial",
":",
"parent_args",
"=",
"self",
".",
"flat_path",
"[",
":",
"-",
"1",
"]",
"else",
":",
"parent_args",
"=",
"self",
".",
"flat_path",
"[",
":",
"-",
"2",
"]",
"if",
"parent_args",
":",
"return",
"self",
".",
"__class__",
"(",
"*",
"parent_args",
",",
"project",
"=",
"self",
".",
"project",
",",
"namespace",
"=",
"self",
".",
"namespace",
")"
] | Creates a parent key for the current path.
Extracts all but the last element in the key path and creates a new
key, while still matching the namespace and the project.
:rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`
:returns: A new ``Key`` instance, whose path consists of all but the
last element of current path. If the current key has only
one path element, returns ``None``. | [
"Creates",
"a",
"parent",
"key",
"for",
"the",
"current",
"path",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L456-L474 |
28,328 | googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | Key.parent | def parent(self):
"""The parent of the current key.
:rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`
:returns: A new ``Key`` instance, whose path consists of all but the
last element of current path. If the current key has only
one path element, returns ``None``.
"""
if self._parent is None:
self._parent = self._make_parent()
return self._parent | python | def parent(self):
"""The parent of the current key.
:rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`
:returns: A new ``Key`` instance, whose path consists of all but the
last element of current path. If the current key has only
one path element, returns ``None``.
"""
if self._parent is None:
self._parent = self._make_parent()
return self._parent | [
"def",
"parent",
"(",
"self",
")",
":",
"if",
"self",
".",
"_parent",
"is",
"None",
":",
"self",
".",
"_parent",
"=",
"self",
".",
"_make_parent",
"(",
")",
"return",
"self",
".",
"_parent"
] | The parent of the current key.
:rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`
:returns: A new ``Key`` instance, whose path consists of all but the
last element of current path. If the current key has only
one path element, returns ``None``. | [
"The",
"parent",
"of",
"the",
"current",
"key",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L477-L488 |
28,329 | googleapis/google-cloud-python | logging/google/cloud/logging/handlers/transports/background_thread.py | _Worker._main_thread_terminated | def _main_thread_terminated(self):
"""Callback that attempts to send pending logs before termination."""
if not self.is_alive:
return
if not self._queue.empty():
print(
"Program shutting down, attempting to send %d queued log "
"entries to Stackdriver Logging..." % (self._queue.qsize(),),
file=sys.stderr,
)
if self.stop(self._grace_period):
print("Sent all pending logs.", file=sys.stderr)
else:
print(
"Failed to send %d pending logs." % (self._queue.qsize(),),
file=sys.stderr,
) | python | def _main_thread_terminated(self):
"""Callback that attempts to send pending logs before termination."""
if not self.is_alive:
return
if not self._queue.empty():
print(
"Program shutting down, attempting to send %d queued log "
"entries to Stackdriver Logging..." % (self._queue.qsize(),),
file=sys.stderr,
)
if self.stop(self._grace_period):
print("Sent all pending logs.", file=sys.stderr)
else:
print(
"Failed to send %d pending logs." % (self._queue.qsize(),),
file=sys.stderr,
) | [
"def",
"_main_thread_terminated",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_alive",
":",
"return",
"if",
"not",
"self",
".",
"_queue",
".",
"empty",
"(",
")",
":",
"print",
"(",
"\"Program shutting down, attempting to send %d queued log \"",
"\"entries to Stackdriver Logging...\"",
"%",
"(",
"self",
".",
"_queue",
".",
"qsize",
"(",
")",
",",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
",",
")",
"if",
"self",
".",
"stop",
"(",
"self",
".",
"_grace_period",
")",
":",
"print",
"(",
"\"Sent all pending logs.\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"else",
":",
"print",
"(",
"\"Failed to send %d pending logs.\"",
"%",
"(",
"self",
".",
"_queue",
".",
"qsize",
"(",
")",
",",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
",",
")"
] | Callback that attempts to send pending logs before termination. | [
"Callback",
"that",
"attempts",
"to",
"send",
"pending",
"logs",
"before",
"termination",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/transports/background_thread.py#L217-L235 |
28,330 | googleapis/google-cloud-python | logging/google/cloud/logging/handlers/transports/background_thread.py | _Worker.enqueue | def enqueue(
self, record, message, resource=None, labels=None, trace=None, span_id=None
):
"""Queues a log entry to be written by the background thread.
:type record: :class:`logging.LogRecord`
:param record: Python log record that the handler was called with.
:type message: str
:param message: The message from the ``LogRecord`` after being
formatted by the associated log formatters.
:type resource: :class:`~google.cloud.logging.resource.Resource`
:param resource: (Optional) Monitored resource of the entry
:type labels: dict
:param labels: (Optional) Mapping of labels for the entry.
:type trace: str
:param trace: (optional) traceid to apply to the logging entry.
:type span_id: str
:param span_id: (optional) span_id within the trace for the log entry.
Specify the trace parameter if span_id is set.
"""
self._queue.put_nowait(
{
"info": {"message": message, "python_logger": record.name},
"severity": record.levelname,
"resource": resource,
"labels": labels,
"trace": trace,
"span_id": span_id,
}
) | python | def enqueue(
self, record, message, resource=None, labels=None, trace=None, span_id=None
):
"""Queues a log entry to be written by the background thread.
:type record: :class:`logging.LogRecord`
:param record: Python log record that the handler was called with.
:type message: str
:param message: The message from the ``LogRecord`` after being
formatted by the associated log formatters.
:type resource: :class:`~google.cloud.logging.resource.Resource`
:param resource: (Optional) Monitored resource of the entry
:type labels: dict
:param labels: (Optional) Mapping of labels for the entry.
:type trace: str
:param trace: (optional) traceid to apply to the logging entry.
:type span_id: str
:param span_id: (optional) span_id within the trace for the log entry.
Specify the trace parameter if span_id is set.
"""
self._queue.put_nowait(
{
"info": {"message": message, "python_logger": record.name},
"severity": record.levelname,
"resource": resource,
"labels": labels,
"trace": trace,
"span_id": span_id,
}
) | [
"def",
"enqueue",
"(",
"self",
",",
"record",
",",
"message",
",",
"resource",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"trace",
"=",
"None",
",",
"span_id",
"=",
"None",
")",
":",
"self",
".",
"_queue",
".",
"put_nowait",
"(",
"{",
"\"info\"",
":",
"{",
"\"message\"",
":",
"message",
",",
"\"python_logger\"",
":",
"record",
".",
"name",
"}",
",",
"\"severity\"",
":",
"record",
".",
"levelname",
",",
"\"resource\"",
":",
"resource",
",",
"\"labels\"",
":",
"labels",
",",
"\"trace\"",
":",
"trace",
",",
"\"span_id\"",
":",
"span_id",
",",
"}",
")"
] | Queues a log entry to be written by the background thread.
:type record: :class:`logging.LogRecord`
:param record: Python log record that the handler was called with.
:type message: str
:param message: The message from the ``LogRecord`` after being
formatted by the associated log formatters.
:type resource: :class:`~google.cloud.logging.resource.Resource`
:param resource: (Optional) Monitored resource of the entry
:type labels: dict
:param labels: (Optional) Mapping of labels for the entry.
:type trace: str
:param trace: (optional) traceid to apply to the logging entry.
:type span_id: str
:param span_id: (optional) span_id within the trace for the log entry.
Specify the trace parameter if span_id is set. | [
"Queues",
"a",
"log",
"entry",
"to",
"be",
"written",
"by",
"the",
"background",
"thread",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/transports/background_thread.py#L237-L271 |
28,331 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/field_path.py | FieldPath.eq_or_parent | def eq_or_parent(self, other):
"""Check whether ``other`` is an ancestor.
Returns:
(bool) True IFF ``other`` is an ancestor or equal to ``self``,
else False.
"""
return self.parts[: len(other.parts)] == other.parts[: len(self.parts)] | python | def eq_or_parent(self, other):
"""Check whether ``other`` is an ancestor.
Returns:
(bool) True IFF ``other`` is an ancestor or equal to ``self``,
else False.
"""
return self.parts[: len(other.parts)] == other.parts[: len(self.parts)] | [
"def",
"eq_or_parent",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"parts",
"[",
":",
"len",
"(",
"other",
".",
"parts",
")",
"]",
"==",
"other",
".",
"parts",
"[",
":",
"len",
"(",
"self",
".",
"parts",
")",
"]"
] | Check whether ``other`` is an ancestor.
Returns:
(bool) True IFF ``other`` is an ancestor or equal to ``self``,
else False. | [
"Check",
"whether",
"other",
"is",
"an",
"ancestor",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/field_path.py#L371-L378 |
28,332 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/field_path.py | FieldPath.lineage | def lineage(self):
"""Return field paths for all parents.
Returns: Set[:class:`FieldPath`]
"""
indexes = six.moves.range(1, len(self.parts))
return {FieldPath(*self.parts[:index]) for index in indexes} | python | def lineage(self):
"""Return field paths for all parents.
Returns: Set[:class:`FieldPath`]
"""
indexes = six.moves.range(1, len(self.parts))
return {FieldPath(*self.parts[:index]) for index in indexes} | [
"def",
"lineage",
"(",
"self",
")",
":",
"indexes",
"=",
"six",
".",
"moves",
".",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"parts",
")",
")",
"return",
"{",
"FieldPath",
"(",
"*",
"self",
".",
"parts",
"[",
":",
"index",
"]",
")",
"for",
"index",
"in",
"indexes",
"}"
] | Return field paths for all parents.
Returns: Set[:class:`FieldPath`] | [
"Return",
"field",
"paths",
"for",
"all",
"parents",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/field_path.py#L380-L386 |
28,333 | googleapis/google-cloud-python | api_core/google/api_core/operations_v1/operations_client.py | OperationsClient.get_operation | def get_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
"""Gets the latest state of a long-running operation.
Clients can use this method to poll the operation result at intervals
as recommended by the API service.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>> response = api.get_operation(name)
Args:
name (str): The name of the operation resource.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Returns:
google.longrunning.operations_pb2.Operation: The state of the
operation.
Raises:
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised.
"""
request = operations_pb2.GetOperationRequest(name=name)
return self._get_operation(request, retry=retry, timeout=timeout) | python | def get_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
"""Gets the latest state of a long-running operation.
Clients can use this method to poll the operation result at intervals
as recommended by the API service.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>> response = api.get_operation(name)
Args:
name (str): The name of the operation resource.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Returns:
google.longrunning.operations_pb2.Operation: The state of the
operation.
Raises:
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised.
"""
request = operations_pb2.GetOperationRequest(name=name)
return self._get_operation(request, retry=retry, timeout=timeout) | [
"def",
"get_operation",
"(",
"self",
",",
"name",
",",
"retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
")",
":",
"request",
"=",
"operations_pb2",
".",
"GetOperationRequest",
"(",
"name",
"=",
"name",
")",
"return",
"self",
".",
"_get_operation",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
")"
] | Gets the latest state of a long-running operation.
Clients can use this method to poll the operation result at intervals
as recommended by the API service.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>> response = api.get_operation(name)
Args:
name (str): The name of the operation resource.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Returns:
google.longrunning.operations_pb2.Operation: The state of the
operation.
Raises:
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised. | [
"Gets",
"the",
"latest",
"state",
"of",
"a",
"long",
"-",
"running",
"operation",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operations_v1/operations_client.py#L93-L131 |
28,334 | googleapis/google-cloud-python | api_core/google/api_core/operations_v1/operations_client.py | OperationsClient.list_operations | def list_operations(
self,
name,
filter_,
retry=gapic_v1.method.DEFAULT,
timeout=gapic_v1.method.DEFAULT,
):
"""
Lists operations that match the specified filter in the request.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>>
>>> # Iterate over all results
>>> for operation in api.list_operations(name):
>>> # process operation
>>> pass
>>>
>>> # Or iterate over results one page at a time
>>> iter = api.list_operations(name)
>>> for page in iter.pages:
>>> for operation in page:
>>> # process operation
>>> pass
Args:
name (str): The name of the operation collection.
filter_ (str): The standard list filter.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Returns:
google.api_core.page_iterator.Iterator: An iterator that yields
:class:`google.longrunning.operations_pb2.Operation` instances.
Raises:
google.api_core.exceptions.MethodNotImplemented: If the server
does not support this method. Services are not required to
implement this method.
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised.
"""
# Create the request object.
request = operations_pb2.ListOperationsRequest(name=name, filter=filter_)
# Create the method used to fetch pages
method = functools.partial(self._list_operations, retry=retry, timeout=timeout)
iterator = page_iterator.GRPCIterator(
client=None,
method=method,
request=request,
items_field="operations",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | python | def list_operations(
self,
name,
filter_,
retry=gapic_v1.method.DEFAULT,
timeout=gapic_v1.method.DEFAULT,
):
"""
Lists operations that match the specified filter in the request.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>>
>>> # Iterate over all results
>>> for operation in api.list_operations(name):
>>> # process operation
>>> pass
>>>
>>> # Or iterate over results one page at a time
>>> iter = api.list_operations(name)
>>> for page in iter.pages:
>>> for operation in page:
>>> # process operation
>>> pass
Args:
name (str): The name of the operation collection.
filter_ (str): The standard list filter.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Returns:
google.api_core.page_iterator.Iterator: An iterator that yields
:class:`google.longrunning.operations_pb2.Operation` instances.
Raises:
google.api_core.exceptions.MethodNotImplemented: If the server
does not support this method. Services are not required to
implement this method.
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised.
"""
# Create the request object.
request = operations_pb2.ListOperationsRequest(name=name, filter=filter_)
# Create the method used to fetch pages
method = functools.partial(self._list_operations, retry=retry, timeout=timeout)
iterator = page_iterator.GRPCIterator(
client=None,
method=method,
request=request,
items_field="operations",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | [
"def",
"list_operations",
"(",
"self",
",",
"name",
",",
"filter_",
",",
"retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
")",
":",
"# Create the request object.",
"request",
"=",
"operations_pb2",
".",
"ListOperationsRequest",
"(",
"name",
"=",
"name",
",",
"filter",
"=",
"filter_",
")",
"# Create the method used to fetch pages",
"method",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_list_operations",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
")",
"iterator",
"=",
"page_iterator",
".",
"GRPCIterator",
"(",
"client",
"=",
"None",
",",
"method",
"=",
"method",
",",
"request",
"=",
"request",
",",
"items_field",
"=",
"\"operations\"",
",",
"request_token_field",
"=",
"\"page_token\"",
",",
"response_token_field",
"=",
"\"next_page_token\"",
",",
")",
"return",
"iterator"
] | Lists operations that match the specified filter in the request.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>>
>>> # Iterate over all results
>>> for operation in api.list_operations(name):
>>> # process operation
>>> pass
>>>
>>> # Or iterate over results one page at a time
>>> iter = api.list_operations(name)
>>> for page in iter.pages:
>>> for operation in page:
>>> # process operation
>>> pass
Args:
name (str): The name of the operation collection.
filter_ (str): The standard list filter.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Returns:
google.api_core.page_iterator.Iterator: An iterator that yields
:class:`google.longrunning.operations_pb2.Operation` instances.
Raises:
google.api_core.exceptions.MethodNotImplemented: If the server
does not support this method. Services are not required to
implement this method.
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised. | [
"Lists",
"operations",
"that",
"match",
"the",
"specified",
"filter",
"in",
"the",
"request",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operations_v1/operations_client.py#L133-L202 |
28,335 | googleapis/google-cloud-python | api_core/google/api_core/operations_v1/operations_client.py | OperationsClient.cancel_operation | def cancel_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
"""Starts asynchronous cancellation on a long-running operation.
The server makes a best effort to cancel the operation, but success is
not guaranteed. Clients can use :meth:`get_operation` or service-
specific methods to check whether the cancellation succeeded or whether
the operation completed despite cancellation. On successful
cancellation, the operation is not deleted; instead, it becomes an
operation with an ``Operation.error`` value with a
``google.rpc.Status.code`` of ``1``, corresponding to
``Code.CANCELLED``.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>> api.cancel_operation(name)
Args:
name (str): The name of the operation resource to be cancelled.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Raises:
google.api_core.exceptions.MethodNotImplemented: If the server
does not support this method. Services are not required to
implement this method.
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised.
"""
# Create the request object.
request = operations_pb2.CancelOperationRequest(name=name)
self._cancel_operation(request, retry=retry, timeout=timeout) | python | def cancel_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
"""Starts asynchronous cancellation on a long-running operation.
The server makes a best effort to cancel the operation, but success is
not guaranteed. Clients can use :meth:`get_operation` or service-
specific methods to check whether the cancellation succeeded or whether
the operation completed despite cancellation. On successful
cancellation, the operation is not deleted; instead, it becomes an
operation with an ``Operation.error`` value with a
``google.rpc.Status.code`` of ``1``, corresponding to
``Code.CANCELLED``.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>> api.cancel_operation(name)
Args:
name (str): The name of the operation resource to be cancelled.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Raises:
google.api_core.exceptions.MethodNotImplemented: If the server
does not support this method. Services are not required to
implement this method.
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised.
"""
# Create the request object.
request = operations_pb2.CancelOperationRequest(name=name)
self._cancel_operation(request, retry=retry, timeout=timeout) | [
"def",
"cancel_operation",
"(",
"self",
",",
"name",
",",
"retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
")",
":",
"# Create the request object.",
"request",
"=",
"operations_pb2",
".",
"CancelOperationRequest",
"(",
"name",
"=",
"name",
")",
"self",
".",
"_cancel_operation",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
")"
] | Starts asynchronous cancellation on a long-running operation.
The server makes a best effort to cancel the operation, but success is
not guaranteed. Clients can use :meth:`get_operation` or service-
specific methods to check whether the cancellation succeeded or whether
the operation completed despite cancellation. On successful
cancellation, the operation is not deleted; instead, it becomes an
operation with an ``Operation.error`` value with a
``google.rpc.Status.code`` of ``1``, corresponding to
``Code.CANCELLED``.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>> api.cancel_operation(name)
Args:
name (str): The name of the operation resource to be cancelled.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Raises:
google.api_core.exceptions.MethodNotImplemented: If the server
does not support this method. Services are not required to
implement this method.
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised. | [
"Starts",
"asynchronous",
"cancellation",
"on",
"a",
"long",
"-",
"running",
"operation",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operations_v1/operations_client.py#L204-L248 |
28,336 | googleapis/google-cloud-python | api_core/google/api_core/operations_v1/operations_client.py | OperationsClient.delete_operation | def delete_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
"""Deletes a long-running operation.
This method indicates that the client is no longer interested in the
operation result. It does not cancel the operation.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>> api.delete_operation(name)
Args:
name (str): The name of the operation resource to be deleted.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Raises:
google.api_core.exceptions.MethodNotImplemented: If the server
does not support this method. Services are not required to
implement this method.
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised.
"""
# Create the request object.
request = operations_pb2.DeleteOperationRequest(name=name)
self._delete_operation(request, retry=retry, timeout=timeout) | python | def delete_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
"""Deletes a long-running operation.
This method indicates that the client is no longer interested in the
operation result. It does not cancel the operation.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>> api.delete_operation(name)
Args:
name (str): The name of the operation resource to be deleted.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Raises:
google.api_core.exceptions.MethodNotImplemented: If the server
does not support this method. Services are not required to
implement this method.
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised.
"""
# Create the request object.
request = operations_pb2.DeleteOperationRequest(name=name)
self._delete_operation(request, retry=retry, timeout=timeout) | [
"def",
"delete_operation",
"(",
"self",
",",
"name",
",",
"retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
")",
":",
"# Create the request object.",
"request",
"=",
"operations_pb2",
".",
"DeleteOperationRequest",
"(",
"name",
"=",
"name",
")",
"self",
".",
"_delete_operation",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
")"
] | Deletes a long-running operation.
This method indicates that the client is no longer interested in the
operation result. It does not cancel the operation.
Example:
>>> from google.api_core import operations_v1
>>> api = operations_v1.OperationsClient()
>>> name = ''
>>> api.delete_operation(name)
Args:
name (str): The name of the operation resource to be deleted.
retry (google.api_core.retry.Retry): The retry strategy to use
when invoking the RPC. If unspecified, the default retry from
the client configuration will be used. If ``None``, then this
method will not retry the RPC at all.
timeout (float): The amount of time in seconds to wait for the RPC
to complete. Note that if ``retry`` is used, this timeout
applies to each individual attempt and the overall time it
takes for this method to complete may be longer. If
unspecified, the the default timeout in the client
configuration is used. If ``None``, then the RPC method will
not time out.
Raises:
google.api_core.exceptions.MethodNotImplemented: If the server
does not support this method. Services are not required to
implement this method.
google.api_core.exceptions.GoogleAPICallError: If an error occurred
while invoking the RPC, the appropriate ``GoogleAPICallError``
subclass will be raised. | [
"Deletes",
"a",
"long",
"-",
"running",
"operation",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operations_v1/operations_client.py#L250-L288 |
28,337 | googleapis/google-cloud-python | runtimeconfig/google/cloud/runtimeconfig/_helpers.py | config_name_from_full_name | def config_name_from_full_name(full_name):
"""Extract the config name from a full resource name.
>>> config_name_from_full_name('projects/my-proj/configs/my-config')
"my-config"
:type full_name: str
:param full_name:
The full resource name of a config. The full resource name looks like
``projects/project-name/configs/config-name`` and is returned as the
``name`` field of a config resource. See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs
:rtype: str
:returns: The config's short name, given its full resource name.
:raises: :class:`ValueError` if ``full_name`` is not the expected format
"""
projects, _, configs, result = full_name.split("/")
if projects != "projects" or configs != "configs":
raise ValueError(
"Unexpected format of resource",
full_name,
'Expected "projects/{proj}/configs/{cfg}"',
)
return result | python | def config_name_from_full_name(full_name):
"""Extract the config name from a full resource name.
>>> config_name_from_full_name('projects/my-proj/configs/my-config')
"my-config"
:type full_name: str
:param full_name:
The full resource name of a config. The full resource name looks like
``projects/project-name/configs/config-name`` and is returned as the
``name`` field of a config resource. See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs
:rtype: str
:returns: The config's short name, given its full resource name.
:raises: :class:`ValueError` if ``full_name`` is not the expected format
"""
projects, _, configs, result = full_name.split("/")
if projects != "projects" or configs != "configs":
raise ValueError(
"Unexpected format of resource",
full_name,
'Expected "projects/{proj}/configs/{cfg}"',
)
return result | [
"def",
"config_name_from_full_name",
"(",
"full_name",
")",
":",
"projects",
",",
"_",
",",
"configs",
",",
"result",
"=",
"full_name",
".",
"split",
"(",
"\"/\"",
")",
"if",
"projects",
"!=",
"\"projects\"",
"or",
"configs",
"!=",
"\"configs\"",
":",
"raise",
"ValueError",
"(",
"\"Unexpected format of resource\"",
",",
"full_name",
",",
"'Expected \"projects/{proj}/configs/{cfg}\"'",
",",
")",
"return",
"result"
] | Extract the config name from a full resource name.
>>> config_name_from_full_name('projects/my-proj/configs/my-config')
"my-config"
:type full_name: str
:param full_name:
The full resource name of a config. The full resource name looks like
``projects/project-name/configs/config-name`` and is returned as the
``name`` field of a config resource. See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs
:rtype: str
:returns: The config's short name, given its full resource name.
:raises: :class:`ValueError` if ``full_name`` is not the expected format | [
"Extract",
"the",
"config",
"name",
"from",
"a",
"full",
"resource",
"name",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/runtimeconfig/google/cloud/runtimeconfig/_helpers.py#L18-L42 |
28,338 | googleapis/google-cloud-python | runtimeconfig/google/cloud/runtimeconfig/_helpers.py | variable_name_from_full_name | def variable_name_from_full_name(full_name):
"""Extract the variable name from a full resource name.
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-config/variables/var-name')
"var-name"
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-config/variables/another/var/name')
"another/var/name"
:type full_name: str
:param full_name:
The full resource name of a variable. The full resource name looks like
``projects/prj-name/configs/cfg-name/variables/var-name`` and is
returned as the ``name`` field of a variable resource. See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables
:rtype: str
:returns: The variable's short name, given its full resource name.
:raises: :class:`ValueError` if ``full_name`` is not the expected format
"""
projects, _, configs, _, variables, result = full_name.split("/", 5)
if projects != "projects" or configs != "configs" or variables != "variables":
raise ValueError(
"Unexpected format of resource",
full_name,
'Expected "projects/{proj}/configs/{cfg}/variables/..."',
)
return result | python | def variable_name_from_full_name(full_name):
"""Extract the variable name from a full resource name.
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-config/variables/var-name')
"var-name"
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-config/variables/another/var/name')
"another/var/name"
:type full_name: str
:param full_name:
The full resource name of a variable. The full resource name looks like
``projects/prj-name/configs/cfg-name/variables/var-name`` and is
returned as the ``name`` field of a variable resource. See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables
:rtype: str
:returns: The variable's short name, given its full resource name.
:raises: :class:`ValueError` if ``full_name`` is not the expected format
"""
projects, _, configs, _, variables, result = full_name.split("/", 5)
if projects != "projects" or configs != "configs" or variables != "variables":
raise ValueError(
"Unexpected format of resource",
full_name,
'Expected "projects/{proj}/configs/{cfg}/variables/..."',
)
return result | [
"def",
"variable_name_from_full_name",
"(",
"full_name",
")",
":",
"projects",
",",
"_",
",",
"configs",
",",
"_",
",",
"variables",
",",
"result",
"=",
"full_name",
".",
"split",
"(",
"\"/\"",
",",
"5",
")",
"if",
"projects",
"!=",
"\"projects\"",
"or",
"configs",
"!=",
"\"configs\"",
"or",
"variables",
"!=",
"\"variables\"",
":",
"raise",
"ValueError",
"(",
"\"Unexpected format of resource\"",
",",
"full_name",
",",
"'Expected \"projects/{proj}/configs/{cfg}/variables/...\"'",
",",
")",
"return",
"result"
] | Extract the variable name from a full resource name.
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-config/variables/var-name')
"var-name"
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-config/variables/another/var/name')
"another/var/name"
:type full_name: str
:param full_name:
The full resource name of a variable. The full resource name looks like
``projects/prj-name/configs/cfg-name/variables/var-name`` and is
returned as the ``name`` field of a variable resource. See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables
:rtype: str
:returns: The variable's short name, given its full resource name.
:raises: :class:`ValueError` if ``full_name`` is not the expected format | [
"Extract",
"the",
"variable",
"name",
"from",
"a",
"full",
"resource",
"name",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/runtimeconfig/google/cloud/runtimeconfig/_helpers.py#L45-L73 |
28,339 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/_protocol/histogram.py | Histogram.max | def max(self):
"""Return the maximum value in this histogram.
If there are no values in the histogram at all, return 600.
Returns:
int: The maximum value in the histogram.
"""
if len(self._data) == 0:
return 600
return next(iter(reversed(sorted(self._data.keys())))) | python | def max(self):
"""Return the maximum value in this histogram.
If there are no values in the histogram at all, return 600.
Returns:
int: The maximum value in the histogram.
"""
if len(self._data) == 0:
return 600
return next(iter(reversed(sorted(self._data.keys())))) | [
"def",
"max",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_data",
")",
"==",
"0",
":",
"return",
"600",
"return",
"next",
"(",
"iter",
"(",
"reversed",
"(",
"sorted",
"(",
"self",
".",
"_data",
".",
"keys",
"(",
")",
")",
")",
")",
")"
] | Return the maximum value in this histogram.
If there are no values in the histogram at all, return 600.
Returns:
int: The maximum value in the histogram. | [
"Return",
"the",
"maximum",
"value",
"in",
"this",
"histogram",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/histogram.py#L83-L93 |
28,340 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/_protocol/histogram.py | Histogram.min | def min(self):
"""Return the minimum value in this histogram.
If there are no values in the histogram at all, return 10.
Returns:
int: The minimum value in the histogram.
"""
if len(self._data) == 0:
return 10
return next(iter(sorted(self._data.keys()))) | python | def min(self):
"""Return the minimum value in this histogram.
If there are no values in the histogram at all, return 10.
Returns:
int: The minimum value in the histogram.
"""
if len(self._data) == 0:
return 10
return next(iter(sorted(self._data.keys()))) | [
"def",
"min",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_data",
")",
"==",
"0",
":",
"return",
"10",
"return",
"next",
"(",
"iter",
"(",
"sorted",
"(",
"self",
".",
"_data",
".",
"keys",
"(",
")",
")",
")",
")"
] | Return the minimum value in this histogram.
If there are no values in the histogram at all, return 10.
Returns:
int: The minimum value in the histogram. | [
"Return",
"the",
"minimum",
"value",
"in",
"this",
"histogram",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/histogram.py#L96-L106 |
28,341 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/_protocol/histogram.py | Histogram.add | def add(self, value):
"""Add the value to this histogram.
Args:
value (int): The value. Values outside of ``10 <= x <= 600``
will be raised to ``10`` or reduced to ``600``.
"""
# If the value is out of bounds, bring it in bounds.
value = int(value)
if value < 10:
value = 10
if value > 600:
value = 600
# Add the value to the histogram's data dictionary.
self._data.setdefault(value, 0)
self._data[value] += 1
self._len += 1 | python | def add(self, value):
"""Add the value to this histogram.
Args:
value (int): The value. Values outside of ``10 <= x <= 600``
will be raised to ``10`` or reduced to ``600``.
"""
# If the value is out of bounds, bring it in bounds.
value = int(value)
if value < 10:
value = 10
if value > 600:
value = 600
# Add the value to the histogram's data dictionary.
self._data.setdefault(value, 0)
self._data[value] += 1
self._len += 1 | [
"def",
"add",
"(",
"self",
",",
"value",
")",
":",
"# If the value is out of bounds, bring it in bounds.",
"value",
"=",
"int",
"(",
"value",
")",
"if",
"value",
"<",
"10",
":",
"value",
"=",
"10",
"if",
"value",
">",
"600",
":",
"value",
"=",
"600",
"# Add the value to the histogram's data dictionary.",
"self",
".",
"_data",
".",
"setdefault",
"(",
"value",
",",
"0",
")",
"self",
".",
"_data",
"[",
"value",
"]",
"+=",
"1",
"self",
".",
"_len",
"+=",
"1"
] | Add the value to this histogram.
Args:
value (int): The value. Values outside of ``10 <= x <= 600``
will be raised to ``10`` or reduced to ``600``. | [
"Add",
"the",
"value",
"to",
"this",
"histogram",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/histogram.py#L108-L125 |
28,342 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/_protocol/histogram.py | Histogram.percentile | def percentile(self, percent):
"""Return the value that is the Nth precentile in the histogram.
Args:
percent (Union[int, float]): The precentile being sought. The
default consumer implementations use consistently use ``99``.
Returns:
int: The value corresponding to the requested percentile.
"""
# Sanity check: Any value over 100 should become 100.
if percent >= 100:
percent = 100
# Determine the actual target number.
target = len(self) - len(self) * (percent / 100)
# Iterate over the values in reverse, dropping the target by the
# number of times each value has been seen. When the target passes
# 0, return the value we are currently viewing.
for k in reversed(sorted(self._data.keys())):
target -= self._data[k]
if target < 0:
return k
# The only way to get here is if there was no data.
# In this case, just return 10 seconds.
return 10 | python | def percentile(self, percent):
"""Return the value that is the Nth precentile in the histogram.
Args:
percent (Union[int, float]): The precentile being sought. The
default consumer implementations use consistently use ``99``.
Returns:
int: The value corresponding to the requested percentile.
"""
# Sanity check: Any value over 100 should become 100.
if percent >= 100:
percent = 100
# Determine the actual target number.
target = len(self) - len(self) * (percent / 100)
# Iterate over the values in reverse, dropping the target by the
# number of times each value has been seen. When the target passes
# 0, return the value we are currently viewing.
for k in reversed(sorted(self._data.keys())):
target -= self._data[k]
if target < 0:
return k
# The only way to get here is if there was no data.
# In this case, just return 10 seconds.
return 10 | [
"def",
"percentile",
"(",
"self",
",",
"percent",
")",
":",
"# Sanity check: Any value over 100 should become 100.",
"if",
"percent",
">=",
"100",
":",
"percent",
"=",
"100",
"# Determine the actual target number.",
"target",
"=",
"len",
"(",
"self",
")",
"-",
"len",
"(",
"self",
")",
"*",
"(",
"percent",
"/",
"100",
")",
"# Iterate over the values in reverse, dropping the target by the",
"# number of times each value has been seen. When the target passes",
"# 0, return the value we are currently viewing.",
"for",
"k",
"in",
"reversed",
"(",
"sorted",
"(",
"self",
".",
"_data",
".",
"keys",
"(",
")",
")",
")",
":",
"target",
"-=",
"self",
".",
"_data",
"[",
"k",
"]",
"if",
"target",
"<",
"0",
":",
"return",
"k",
"# The only way to get here is if there was no data.",
"# In this case, just return 10 seconds.",
"return",
"10"
] | Return the value that is the Nth precentile in the histogram.
Args:
percent (Union[int, float]): The precentile being sought. The
default consumer implementations use consistently use ``99``.
Returns:
int: The value corresponding to the requested percentile. | [
"Return",
"the",
"value",
"that",
"is",
"the",
"Nth",
"precentile",
"in",
"the",
"histogram",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/histogram.py#L127-L154 |
28,343 | googleapis/google-cloud-python | scheduler/google/cloud/scheduler_v1beta1/gapic/cloud_scheduler_client.py | CloudSchedulerClient.create_job | def create_job(
self,
parent,
job,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a job.
Example:
>>> from google.cloud import scheduler_v1beta1
>>>
>>> client = scheduler_v1beta1.CloudSchedulerClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `job`:
>>> job = {}
>>>
>>> response = client.create_job(parent, job)
Args:
parent (str): Required.
The location name. For example:
``projects/PROJECT_ID/locations/LOCATION_ID``.
job (Union[dict, ~google.cloud.scheduler_v1beta1.types.Job]): Required.
The job to add. The user can optionally specify a name for the job in
``name``. ``name`` cannot be the same as an existing job. If a name is
not specified then the system will generate a random unique name that
will be returned (``name``) in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.scheduler_v1beta1.types.Job`
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.scheduler_v1beta1.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 "create_job" not in self._inner_api_calls:
self._inner_api_calls[
"create_job"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_job,
default_retry=self._method_configs["CreateJob"].retry,
default_timeout=self._method_configs["CreateJob"].timeout,
client_info=self._client_info,
)
request = cloudscheduler_pb2.CreateJobRequest(parent=parent, job=job)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["create_job"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def create_job(
self,
parent,
job,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a job.
Example:
>>> from google.cloud import scheduler_v1beta1
>>>
>>> client = scheduler_v1beta1.CloudSchedulerClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `job`:
>>> job = {}
>>>
>>> response = client.create_job(parent, job)
Args:
parent (str): Required.
The location name. For example:
``projects/PROJECT_ID/locations/LOCATION_ID``.
job (Union[dict, ~google.cloud.scheduler_v1beta1.types.Job]): Required.
The job to add. The user can optionally specify a name for the job in
``name``. ``name`` cannot be the same as an existing job. If a name is
not specified then the system will generate a random unique name that
will be returned (``name``) in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.scheduler_v1beta1.types.Job`
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.scheduler_v1beta1.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 "create_job" not in self._inner_api_calls:
self._inner_api_calls[
"create_job"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_job,
default_retry=self._method_configs["CreateJob"].retry,
default_timeout=self._method_configs["CreateJob"].timeout,
client_info=self._client_info,
)
request = cloudscheduler_pb2.CreateJobRequest(parent=parent, job=job)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["create_job"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"create_job",
"(",
"self",
",",
"parent",
",",
"job",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"create_job\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"create_job\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_job",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateJob\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateJob\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"cloudscheduler_pb2",
".",
"CreateJobRequest",
"(",
"parent",
"=",
"parent",
",",
"job",
"=",
"job",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"parent\"",
",",
"parent",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"create_job\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Creates a job.
Example:
>>> from google.cloud import scheduler_v1beta1
>>>
>>> client = scheduler_v1beta1.CloudSchedulerClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `job`:
>>> job = {}
>>>
>>> response = client.create_job(parent, job)
Args:
parent (str): Required.
The location name. For example:
``projects/PROJECT_ID/locations/LOCATION_ID``.
job (Union[dict, ~google.cloud.scheduler_v1beta1.types.Job]): Required.
The job to add. The user can optionally specify a name for the job in
``name``. ``name`` cannot be the same as an existing job. If a name is
not specified then the system will generate a random unique name that
will be returned (``name``) in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.scheduler_v1beta1.types.Job`
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.scheduler_v1beta1.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. | [
"Creates",
"a",
"job",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/scheduler/google/cloud/scheduler_v1beta1/gapic/cloud_scheduler_client.py#L382-L465 |
28,344 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/model.py | ModelReference.from_string | def from_string(cls, model_id, default_project=None):
"""Construct a model reference from model ID string.
Args:
model_id (str):
A model ID in standard SQL format. If ``default_project``
is not specified, this must included a project ID, dataset
ID, and model ID, each separated by ``.``.
default_project (str):
Optional. The project ID to use when ``model_id`` does not
include a project ID.
Returns:
google.cloud.bigquery.model.ModelReference:
Model reference parsed from ``model_id``.
Raises:
ValueError:
If ``model_id`` is not a fully-qualified table ID in
standard SQL format.
"""
proj, dset, model = _helpers._parse_3_part_id(
model_id, default_project=default_project, property_name="model_id"
)
return cls.from_api_repr(
{"projectId": proj, "datasetId": dset, "modelId": model}
) | python | def from_string(cls, model_id, default_project=None):
"""Construct a model reference from model ID string.
Args:
model_id (str):
A model ID in standard SQL format. If ``default_project``
is not specified, this must included a project ID, dataset
ID, and model ID, each separated by ``.``.
default_project (str):
Optional. The project ID to use when ``model_id`` does not
include a project ID.
Returns:
google.cloud.bigquery.model.ModelReference:
Model reference parsed from ``model_id``.
Raises:
ValueError:
If ``model_id`` is not a fully-qualified table ID in
standard SQL format.
"""
proj, dset, model = _helpers._parse_3_part_id(
model_id, default_project=default_project, property_name="model_id"
)
return cls.from_api_repr(
{"projectId": proj, "datasetId": dset, "modelId": model}
) | [
"def",
"from_string",
"(",
"cls",
",",
"model_id",
",",
"default_project",
"=",
"None",
")",
":",
"proj",
",",
"dset",
",",
"model",
"=",
"_helpers",
".",
"_parse_3_part_id",
"(",
"model_id",
",",
"default_project",
"=",
"default_project",
",",
"property_name",
"=",
"\"model_id\"",
")",
"return",
"cls",
".",
"from_api_repr",
"(",
"{",
"\"projectId\"",
":",
"proj",
",",
"\"datasetId\"",
":",
"dset",
",",
"\"modelId\"",
":",
"model",
"}",
")"
] | Construct a model reference from model ID string.
Args:
model_id (str):
A model ID in standard SQL format. If ``default_project``
is not specified, this must included a project ID, dataset
ID, and model ID, each separated by ``.``.
default_project (str):
Optional. The project ID to use when ``model_id`` does not
include a project ID.
Returns:
google.cloud.bigquery.model.ModelReference:
Model reference parsed from ``model_id``.
Raises:
ValueError:
If ``model_id`` is not a fully-qualified table ID in
standard SQL format. | [
"Construct",
"a",
"model",
"reference",
"from",
"model",
"ID",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/model.py#L349-L375 |
28,345 | googleapis/google-cloud-python | tasks/google/cloud/tasks_v2beta2/gapic/cloud_tasks_client.py | CloudTasksClient.lease_tasks | def lease_tasks(
self,
parent,
lease_duration,
max_tasks=None,
response_view=None,
filter_=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Leases tasks from a pull queue for ``lease_duration``.
This method is invoked by the worker to obtain a lease. The worker must
acknowledge the task via ``AcknowledgeTask`` after they have performed
the work associated with the task.
The ``payload`` is intended to store data that the worker needs to
perform the work associated with the task. To return the payloads in the
``response``, set ``response_view`` to ``FULL``.
A maximum of 10 qps of ``LeaseTasks`` requests are allowed per queue.
``RESOURCE_EXHAUSTED`` is returned when this limit is exceeded.
``RESOURCE_EXHAUSTED`` is also returned when
``max_tasks_dispatched_per_second`` is exceeded.
Example:
>>> from google.cloud import tasks_v2beta2
>>>
>>> client = tasks_v2beta2.CloudTasksClient()
>>>
>>> parent = client.queue_path('[PROJECT]', '[LOCATION]', '[QUEUE]')
>>>
>>> # TODO: Initialize `lease_duration`:
>>> lease_duration = {}
>>>
>>> response = client.lease_tasks(parent, lease_duration)
Args:
parent (str): Required.
The queue name. For example:
``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID``
lease_duration (Union[dict, ~google.cloud.tasks_v2beta2.types.Duration]): After the worker has successfully finished the work associated with the
task, the worker must call via ``AcknowledgeTask`` before the
``schedule_time``. Otherwise the task will be returned to a later
``LeaseTasks`` call so that another worker can retry it.
The maximum lease duration is 1 week. ``lease_duration`` will be
truncated to the nearest second.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.tasks_v2beta2.types.Duration`
max_tasks (int): The maximum number of tasks to lease.
The system will make a best effort to return as close to as
``max_tasks`` as possible.
The largest that ``max_tasks`` can be is 1000.
response_view (~google.cloud.tasks_v2beta2.types.View): The response\_view specifies which subset of the ``Task`` will be
returned.
By default response\_view is ``BASIC``; not all information is retrieved
by default because some data, such as payloads, might be desirable to
return only when needed because of its large size or because of the
sensitivity of data that it contains.
Authorization for ``FULL`` requires ``cloudtasks.tasks.fullView``
`Google IAM <https://cloud.google.com/iam/>`___ permission on the
``Task`` resource.
filter_ (str): ``filter`` can be used to specify a subset of tasks to lease.
When ``filter`` is set to ``tag=<my-tag>`` then the ``response`` will
contain only tasks whose ``tag`` is equal to ``<my-tag>``. ``<my-tag>``
must be less than 500 characters.
When ``filter`` is set to ``tag_function=oldest_tag()``, only tasks
which have the same tag as the task with the oldest ``schedule_time``
will be returned.
Grammar Syntax:
- ``filter = "tag=" tag | "tag_function=" function``
- ``tag = string``
- ``function = "oldest_tag()"``
The ``oldest_tag()`` function returns tasks which have the same tag as
the oldest task (ordered by schedule time).
SDK compatibility: Although the SDK allows tags to be either string or
`bytes <https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/taskqueue/TaskOptions.html#tag-byte:A->`__,
only UTF-8 encoded tags can be used in Cloud Tasks. Tag which aren't
UTF-8 encoded can't be used in the ``filter`` and the task's ``tag``
will be displayed as empty in Cloud Tasks.
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.tasks_v2beta2.types.LeaseTasksResponse` 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 "lease_tasks" not in self._inner_api_calls:
self._inner_api_calls[
"lease_tasks"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.lease_tasks,
default_retry=self._method_configs["LeaseTasks"].retry,
default_timeout=self._method_configs["LeaseTasks"].timeout,
client_info=self._client_info,
)
request = cloudtasks_pb2.LeaseTasksRequest(
parent=parent,
lease_duration=lease_duration,
max_tasks=max_tasks,
response_view=response_view,
filter=filter_,
)
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["lease_tasks"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def lease_tasks(
self,
parent,
lease_duration,
max_tasks=None,
response_view=None,
filter_=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Leases tasks from a pull queue for ``lease_duration``.
This method is invoked by the worker to obtain a lease. The worker must
acknowledge the task via ``AcknowledgeTask`` after they have performed
the work associated with the task.
The ``payload`` is intended to store data that the worker needs to
perform the work associated with the task. To return the payloads in the
``response``, set ``response_view`` to ``FULL``.
A maximum of 10 qps of ``LeaseTasks`` requests are allowed per queue.
``RESOURCE_EXHAUSTED`` is returned when this limit is exceeded.
``RESOURCE_EXHAUSTED`` is also returned when
``max_tasks_dispatched_per_second`` is exceeded.
Example:
>>> from google.cloud import tasks_v2beta2
>>>
>>> client = tasks_v2beta2.CloudTasksClient()
>>>
>>> parent = client.queue_path('[PROJECT]', '[LOCATION]', '[QUEUE]')
>>>
>>> # TODO: Initialize `lease_duration`:
>>> lease_duration = {}
>>>
>>> response = client.lease_tasks(parent, lease_duration)
Args:
parent (str): Required.
The queue name. For example:
``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID``
lease_duration (Union[dict, ~google.cloud.tasks_v2beta2.types.Duration]): After the worker has successfully finished the work associated with the
task, the worker must call via ``AcknowledgeTask`` before the
``schedule_time``. Otherwise the task will be returned to a later
``LeaseTasks`` call so that another worker can retry it.
The maximum lease duration is 1 week. ``lease_duration`` will be
truncated to the nearest second.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.tasks_v2beta2.types.Duration`
max_tasks (int): The maximum number of tasks to lease.
The system will make a best effort to return as close to as
``max_tasks`` as possible.
The largest that ``max_tasks`` can be is 1000.
response_view (~google.cloud.tasks_v2beta2.types.View): The response\_view specifies which subset of the ``Task`` will be
returned.
By default response\_view is ``BASIC``; not all information is retrieved
by default because some data, such as payloads, might be desirable to
return only when needed because of its large size or because of the
sensitivity of data that it contains.
Authorization for ``FULL`` requires ``cloudtasks.tasks.fullView``
`Google IAM <https://cloud.google.com/iam/>`___ permission on the
``Task`` resource.
filter_ (str): ``filter`` can be used to specify a subset of tasks to lease.
When ``filter`` is set to ``tag=<my-tag>`` then the ``response`` will
contain only tasks whose ``tag`` is equal to ``<my-tag>``. ``<my-tag>``
must be less than 500 characters.
When ``filter`` is set to ``tag_function=oldest_tag()``, only tasks
which have the same tag as the task with the oldest ``schedule_time``
will be returned.
Grammar Syntax:
- ``filter = "tag=" tag | "tag_function=" function``
- ``tag = string``
- ``function = "oldest_tag()"``
The ``oldest_tag()`` function returns tasks which have the same tag as
the oldest task (ordered by schedule time).
SDK compatibility: Although the SDK allows tags to be either string or
`bytes <https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/taskqueue/TaskOptions.html#tag-byte:A->`__,
only UTF-8 encoded tags can be used in Cloud Tasks. Tag which aren't
UTF-8 encoded can't be used in the ``filter`` and the task's ``tag``
will be displayed as empty in Cloud Tasks.
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.tasks_v2beta2.types.LeaseTasksResponse` 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 "lease_tasks" not in self._inner_api_calls:
self._inner_api_calls[
"lease_tasks"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.lease_tasks,
default_retry=self._method_configs["LeaseTasks"].retry,
default_timeout=self._method_configs["LeaseTasks"].timeout,
client_info=self._client_info,
)
request = cloudtasks_pb2.LeaseTasksRequest(
parent=parent,
lease_duration=lease_duration,
max_tasks=max_tasks,
response_view=response_view,
filter=filter_,
)
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["lease_tasks"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"lease_tasks",
"(",
"self",
",",
"parent",
",",
"lease_duration",
",",
"max_tasks",
"=",
"None",
",",
"response_view",
"=",
"None",
",",
"filter_",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"lease_tasks\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"lease_tasks\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"lease_tasks",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"LeaseTasks\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"LeaseTasks\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"cloudtasks_pb2",
".",
"LeaseTasksRequest",
"(",
"parent",
"=",
"parent",
",",
"lease_duration",
"=",
"lease_duration",
",",
"max_tasks",
"=",
"max_tasks",
",",
"response_view",
"=",
"response_view",
",",
"filter",
"=",
"filter_",
",",
")",
"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",
"[",
"\"lease_tasks\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Leases tasks from a pull queue for ``lease_duration``.
This method is invoked by the worker to obtain a lease. The worker must
acknowledge the task via ``AcknowledgeTask`` after they have performed
the work associated with the task.
The ``payload`` is intended to store data that the worker needs to
perform the work associated with the task. To return the payloads in the
``response``, set ``response_view`` to ``FULL``.
A maximum of 10 qps of ``LeaseTasks`` requests are allowed per queue.
``RESOURCE_EXHAUSTED`` is returned when this limit is exceeded.
``RESOURCE_EXHAUSTED`` is also returned when
``max_tasks_dispatched_per_second`` is exceeded.
Example:
>>> from google.cloud import tasks_v2beta2
>>>
>>> client = tasks_v2beta2.CloudTasksClient()
>>>
>>> parent = client.queue_path('[PROJECT]', '[LOCATION]', '[QUEUE]')
>>>
>>> # TODO: Initialize `lease_duration`:
>>> lease_duration = {}
>>>
>>> response = client.lease_tasks(parent, lease_duration)
Args:
parent (str): Required.
The queue name. For example:
``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID``
lease_duration (Union[dict, ~google.cloud.tasks_v2beta2.types.Duration]): After the worker has successfully finished the work associated with the
task, the worker must call via ``AcknowledgeTask`` before the
``schedule_time``. Otherwise the task will be returned to a later
``LeaseTasks`` call so that another worker can retry it.
The maximum lease duration is 1 week. ``lease_duration`` will be
truncated to the nearest second.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.tasks_v2beta2.types.Duration`
max_tasks (int): The maximum number of tasks to lease.
The system will make a best effort to return as close to as
``max_tasks`` as possible.
The largest that ``max_tasks`` can be is 1000.
response_view (~google.cloud.tasks_v2beta2.types.View): The response\_view specifies which subset of the ``Task`` will be
returned.
By default response\_view is ``BASIC``; not all information is retrieved
by default because some data, such as payloads, might be desirable to
return only when needed because of its large size or because of the
sensitivity of data that it contains.
Authorization for ``FULL`` requires ``cloudtasks.tasks.fullView``
`Google IAM <https://cloud.google.com/iam/>`___ permission on the
``Task`` resource.
filter_ (str): ``filter`` can be used to specify a subset of tasks to lease.
When ``filter`` is set to ``tag=<my-tag>`` then the ``response`` will
contain only tasks whose ``tag`` is equal to ``<my-tag>``. ``<my-tag>``
must be less than 500 characters.
When ``filter`` is set to ``tag_function=oldest_tag()``, only tasks
which have the same tag as the task with the oldest ``schedule_time``
will be returned.
Grammar Syntax:
- ``filter = "tag=" tag | "tag_function=" function``
- ``tag = string``
- ``function = "oldest_tag()"``
The ``oldest_tag()`` function returns tasks which have the same tag as
the oldest task (ordered by schedule time).
SDK compatibility: Although the SDK allows tags to be either string or
`bytes <https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/taskqueue/TaskOptions.html#tag-byte:A->`__,
only UTF-8 encoded tags can be used in Cloud Tasks. Tag which aren't
UTF-8 encoded can't be used in the ``filter`` and the task's ``tag``
will be displayed as empty in Cloud Tasks.
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.tasks_v2beta2.types.LeaseTasksResponse` 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. | [
"Leases",
"tasks",
"from",
"a",
"pull",
"queue",
"for",
"lease_duration",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/tasks/google/cloud/tasks_v2beta2/gapic/cloud_tasks_client.py#L1594-L1743 |
28,346 | googleapis/google-cloud-python | logging/google/cloud/logging/handlers/_helpers.py | format_stackdriver_json | def format_stackdriver_json(record, message):
"""Helper to format a LogRecord in in Stackdriver fluentd format.
:rtype: str
:returns: JSON str to be written to the log file.
"""
subsecond, second = math.modf(record.created)
payload = {
"message": message,
"timestamp": {"seconds": int(second), "nanos": int(subsecond * 1e9)},
"thread": record.thread,
"severity": record.levelname,
}
return json.dumps(payload) | python | def format_stackdriver_json(record, message):
"""Helper to format a LogRecord in in Stackdriver fluentd format.
:rtype: str
:returns: JSON str to be written to the log file.
"""
subsecond, second = math.modf(record.created)
payload = {
"message": message,
"timestamp": {"seconds": int(second), "nanos": int(subsecond * 1e9)},
"thread": record.thread,
"severity": record.levelname,
}
return json.dumps(payload) | [
"def",
"format_stackdriver_json",
"(",
"record",
",",
"message",
")",
":",
"subsecond",
",",
"second",
"=",
"math",
".",
"modf",
"(",
"record",
".",
"created",
")",
"payload",
"=",
"{",
"\"message\"",
":",
"message",
",",
"\"timestamp\"",
":",
"{",
"\"seconds\"",
":",
"int",
"(",
"second",
")",
",",
"\"nanos\"",
":",
"int",
"(",
"subsecond",
"*",
"1e9",
")",
"}",
",",
"\"thread\"",
":",
"record",
".",
"thread",
",",
"\"severity\"",
":",
"record",
".",
"levelname",
",",
"}",
"return",
"json",
".",
"dumps",
"(",
"payload",
")"
] | Helper to format a LogRecord in in Stackdriver fluentd format.
:rtype: str
:returns: JSON str to be written to the log file. | [
"Helper",
"to",
"format",
"a",
"LogRecord",
"in",
"in",
"Stackdriver",
"fluentd",
"format",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/_helpers.py#L41-L56 |
28,347 | googleapis/google-cloud-python | logging/google/cloud/logging/handlers/_helpers.py | get_trace_id_from_flask | def get_trace_id_from_flask():
"""Get trace_id from flask request headers.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
if flask is None or not flask.request:
return None
header = flask.request.headers.get(_FLASK_TRACE_HEADER)
if header is None:
return None
trace_id = header.split("/", 1)[0]
return trace_id | python | def get_trace_id_from_flask():
"""Get trace_id from flask request headers.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
if flask is None or not flask.request:
return None
header = flask.request.headers.get(_FLASK_TRACE_HEADER)
if header is None:
return None
trace_id = header.split("/", 1)[0]
return trace_id | [
"def",
"get_trace_id_from_flask",
"(",
")",
":",
"if",
"flask",
"is",
"None",
"or",
"not",
"flask",
".",
"request",
":",
"return",
"None",
"header",
"=",
"flask",
".",
"request",
".",
"headers",
".",
"get",
"(",
"_FLASK_TRACE_HEADER",
")",
"if",
"header",
"is",
"None",
":",
"return",
"None",
"trace_id",
"=",
"header",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"[",
"0",
"]",
"return",
"trace_id"
] | Get trace_id from flask request headers.
:rtype: str
:returns: TraceID in HTTP request headers. | [
"Get",
"trace_id",
"from",
"flask",
"request",
"headers",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/_helpers.py#L59-L75 |
28,348 | googleapis/google-cloud-python | logging/google/cloud/logging/handlers/_helpers.py | get_trace_id_from_webapp2 | def get_trace_id_from_webapp2():
"""Get trace_id from webapp2 request headers.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
if webapp2 is None:
return None
try:
# get_request() succeeds if we're in the middle of a webapp2
# request, or raises an assertion error otherwise:
# "Request global variable is not set".
req = webapp2.get_request()
except AssertionError:
return None
header = req.headers.get(_WEBAPP2_TRACE_HEADER)
if header is None:
return None
trace_id = header.split("/", 1)[0]
return trace_id | python | def get_trace_id_from_webapp2():
"""Get trace_id from webapp2 request headers.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
if webapp2 is None:
return None
try:
# get_request() succeeds if we're in the middle of a webapp2
# request, or raises an assertion error otherwise:
# "Request global variable is not set".
req = webapp2.get_request()
except AssertionError:
return None
header = req.headers.get(_WEBAPP2_TRACE_HEADER)
if header is None:
return None
trace_id = header.split("/", 1)[0]
return trace_id | [
"def",
"get_trace_id_from_webapp2",
"(",
")",
":",
"if",
"webapp2",
"is",
"None",
":",
"return",
"None",
"try",
":",
"# get_request() succeeds if we're in the middle of a webapp2",
"# request, or raises an assertion error otherwise:",
"# \"Request global variable is not set\".",
"req",
"=",
"webapp2",
".",
"get_request",
"(",
")",
"except",
"AssertionError",
":",
"return",
"None",
"header",
"=",
"req",
".",
"headers",
".",
"get",
"(",
"_WEBAPP2_TRACE_HEADER",
")",
"if",
"header",
"is",
"None",
":",
"return",
"None",
"trace_id",
"=",
"header",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"[",
"0",
"]",
"return",
"trace_id"
] | Get trace_id from webapp2 request headers.
:rtype: str
:returns: TraceID in HTTP request headers. | [
"Get",
"trace_id",
"from",
"webapp2",
"request",
"headers",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/_helpers.py#L78-L102 |
28,349 | googleapis/google-cloud-python | logging/google/cloud/logging/handlers/_helpers.py | get_trace_id_from_django | def get_trace_id_from_django():
"""Get trace_id from django request headers.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
request = _get_django_request()
if request is None:
return None
header = request.META.get(_DJANGO_TRACE_HEADER)
if header is None:
return None
trace_id = header.split("/", 1)[0]
return trace_id | python | def get_trace_id_from_django():
"""Get trace_id from django request headers.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
request = _get_django_request()
if request is None:
return None
header = request.META.get(_DJANGO_TRACE_HEADER)
if header is None:
return None
trace_id = header.split("/", 1)[0]
return trace_id | [
"def",
"get_trace_id_from_django",
"(",
")",
":",
"request",
"=",
"_get_django_request",
"(",
")",
"if",
"request",
"is",
"None",
":",
"return",
"None",
"header",
"=",
"request",
".",
"META",
".",
"get",
"(",
"_DJANGO_TRACE_HEADER",
")",
"if",
"header",
"is",
"None",
":",
"return",
"None",
"trace_id",
"=",
"header",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"[",
"0",
"]",
"return",
"trace_id"
] | Get trace_id from django request headers.
:rtype: str
:returns: TraceID in HTTP request headers. | [
"Get",
"trace_id",
"from",
"django",
"request",
"headers",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/_helpers.py#L105-L122 |
28,350 | googleapis/google-cloud-python | logging/google/cloud/logging/handlers/_helpers.py | get_trace_id | def get_trace_id():
"""Helper to get trace_id from web application request header.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
checkers = (
get_trace_id_from_django,
get_trace_id_from_flask,
get_trace_id_from_webapp2,
)
for checker in checkers:
trace_id = checker()
if trace_id is not None:
return trace_id
return None | python | def get_trace_id():
"""Helper to get trace_id from web application request header.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
checkers = (
get_trace_id_from_django,
get_trace_id_from_flask,
get_trace_id_from_webapp2,
)
for checker in checkers:
trace_id = checker()
if trace_id is not None:
return trace_id
return None | [
"def",
"get_trace_id",
"(",
")",
":",
"checkers",
"=",
"(",
"get_trace_id_from_django",
",",
"get_trace_id_from_flask",
",",
"get_trace_id_from_webapp2",
",",
")",
"for",
"checker",
"in",
"checkers",
":",
"trace_id",
"=",
"checker",
"(",
")",
"if",
"trace_id",
"is",
"not",
"None",
":",
"return",
"trace_id",
"return",
"None"
] | Helper to get trace_id from web application request header.
:rtype: str
:returns: TraceID in HTTP request headers. | [
"Helper",
"to",
"get",
"trace_id",
"from",
"web",
"application",
"request",
"header",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/_helpers.py#L125-L142 |
28,351 | googleapis/google-cloud-python | monitoring/google/cloud/monitoring_v3/gapic/group_service_client.py | GroupServiceClient.group_path | def group_path(cls, project, group):
"""Return a fully-qualified group string."""
return google.api_core.path_template.expand(
"projects/{project}/groups/{group}", project=project, group=group
) | python | def group_path(cls, project, group):
"""Return a fully-qualified group string."""
return google.api_core.path_template.expand(
"projects/{project}/groups/{group}", project=project, group=group
) | [
"def",
"group_path",
"(",
"cls",
",",
"project",
",",
"group",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/groups/{group}\"",
",",
"project",
"=",
"project",
",",
"group",
"=",
"group",
")"
] | Return a fully-qualified group string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"group",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/gapic/group_service_client.py#L101-L105 |
28,352 | googleapis/google-cloud-python | monitoring/google/cloud/monitoring_v3/gapic/group_service_client.py | GroupServiceClient.list_groups | def list_groups(
self,
name,
children_of_group=None,
ancestors_of_group=None,
descendants_of_group=None,
page_size=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Lists the existing groups.
Example:
>>> from google.cloud import monitoring_v3
>>>
>>> client = monitoring_v3.GroupServiceClient()
>>>
>>> name = client.project_path('[PROJECT]')
>>>
>>> # Iterate over all results
>>> for element in client.list_groups(name):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_groups(name).pages:
... for element in page:
... # process element
... pass
Args:
name (str): The project whose groups are to be listed. The format is
``"projects/{project_id_or_number}"``.
children_of_group (str): A group name: ``"projects/{project_id_or_number}/groups/{group_id}"``.
Returns groups whose ``parentName`` field contains the group name. If no
groups have this parent, the results are empty.
ancestors_of_group (str): A group name: ``"projects/{project_id_or_number}/groups/{group_id}"``.
Returns groups that are ancestors of the specified group. The groups are
returned in order, starting with the immediate parent and ending with
the most distant ancestor. If the specified group has no immediate
parent, the results are empty.
descendants_of_group (str): A group name: ``"projects/{project_id_or_number}/groups/{group_id}"``.
Returns the descendants of the specified group. This is a superset of
the results returned by the ``childrenOfGroup`` filter, and includes
children-of-children, and so forth.
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
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.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.monitoring_v3.types.Group` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
if metadata is None:
metadata = []
metadata = list(metadata)
# Wrap the transport method to add retry and timeout logic.
if "list_groups" not in self._inner_api_calls:
self._inner_api_calls[
"list_groups"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_groups,
default_retry=self._method_configs["ListGroups"].retry,
default_timeout=self._method_configs["ListGroups"].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(
children_of_group=children_of_group,
ancestors_of_group=ancestors_of_group,
descendants_of_group=descendants_of_group,
)
request = group_service_pb2.ListGroupsRequest(
name=name,
children_of_group=children_of_group,
ancestors_of_group=ancestors_of_group,
descendants_of_group=descendants_of_group,
page_size=page_size,
)
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)
iterator = google.api_core.page_iterator.GRPCIterator(
client=None,
method=functools.partial(
self._inner_api_calls["list_groups"],
retry=retry,
timeout=timeout,
metadata=metadata,
),
request=request,
items_field="group",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | python | def list_groups(
self,
name,
children_of_group=None,
ancestors_of_group=None,
descendants_of_group=None,
page_size=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Lists the existing groups.
Example:
>>> from google.cloud import monitoring_v3
>>>
>>> client = monitoring_v3.GroupServiceClient()
>>>
>>> name = client.project_path('[PROJECT]')
>>>
>>> # Iterate over all results
>>> for element in client.list_groups(name):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_groups(name).pages:
... for element in page:
... # process element
... pass
Args:
name (str): The project whose groups are to be listed. The format is
``"projects/{project_id_or_number}"``.
children_of_group (str): A group name: ``"projects/{project_id_or_number}/groups/{group_id}"``.
Returns groups whose ``parentName`` field contains the group name. If no
groups have this parent, the results are empty.
ancestors_of_group (str): A group name: ``"projects/{project_id_or_number}/groups/{group_id}"``.
Returns groups that are ancestors of the specified group. The groups are
returned in order, starting with the immediate parent and ending with
the most distant ancestor. If the specified group has no immediate
parent, the results are empty.
descendants_of_group (str): A group name: ``"projects/{project_id_or_number}/groups/{group_id}"``.
Returns the descendants of the specified group. This is a superset of
the results returned by the ``childrenOfGroup`` filter, and includes
children-of-children, and so forth.
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
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.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.monitoring_v3.types.Group` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
if metadata is None:
metadata = []
metadata = list(metadata)
# Wrap the transport method to add retry and timeout logic.
if "list_groups" not in self._inner_api_calls:
self._inner_api_calls[
"list_groups"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_groups,
default_retry=self._method_configs["ListGroups"].retry,
default_timeout=self._method_configs["ListGroups"].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(
children_of_group=children_of_group,
ancestors_of_group=ancestors_of_group,
descendants_of_group=descendants_of_group,
)
request = group_service_pb2.ListGroupsRequest(
name=name,
children_of_group=children_of_group,
ancestors_of_group=ancestors_of_group,
descendants_of_group=descendants_of_group,
page_size=page_size,
)
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)
iterator = google.api_core.page_iterator.GRPCIterator(
client=None,
method=functools.partial(
self._inner_api_calls["list_groups"],
retry=retry,
timeout=timeout,
metadata=metadata,
),
request=request,
items_field="group",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | [
"def",
"list_groups",
"(",
"self",
",",
"name",
",",
"children_of_group",
"=",
"None",
",",
"ancestors_of_group",
"=",
"None",
",",
"descendants_of_group",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"list_groups\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"list_groups\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"list_groups",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"ListGroups\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"ListGroups\"",
"]",
".",
"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",
"(",
"children_of_group",
"=",
"children_of_group",
",",
"ancestors_of_group",
"=",
"ancestors_of_group",
",",
"descendants_of_group",
"=",
"descendants_of_group",
",",
")",
"request",
"=",
"group_service_pb2",
".",
"ListGroupsRequest",
"(",
"name",
"=",
"name",
",",
"children_of_group",
"=",
"children_of_group",
",",
"ancestors_of_group",
"=",
"ancestors_of_group",
",",
"descendants_of_group",
"=",
"descendants_of_group",
",",
"page_size",
"=",
"page_size",
",",
")",
"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",
")",
"iterator",
"=",
"google",
".",
"api_core",
".",
"page_iterator",
".",
"GRPCIterator",
"(",
"client",
"=",
"None",
",",
"method",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_inner_api_calls",
"[",
"\"list_groups\"",
"]",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
",",
")",
",",
"request",
"=",
"request",
",",
"items_field",
"=",
"\"group\"",
",",
"request_token_field",
"=",
"\"page_token\"",
",",
"response_token_field",
"=",
"\"next_page_token\"",
",",
")",
"return",
"iterator"
] | Lists the existing groups.
Example:
>>> from google.cloud import monitoring_v3
>>>
>>> client = monitoring_v3.GroupServiceClient()
>>>
>>> name = client.project_path('[PROJECT]')
>>>
>>> # Iterate over all results
>>> for element in client.list_groups(name):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_groups(name).pages:
... for element in page:
... # process element
... pass
Args:
name (str): The project whose groups are to be listed. The format is
``"projects/{project_id_or_number}"``.
children_of_group (str): A group name: ``"projects/{project_id_or_number}/groups/{group_id}"``.
Returns groups whose ``parentName`` field contains the group name. If no
groups have this parent, the results are empty.
ancestors_of_group (str): A group name: ``"projects/{project_id_or_number}/groups/{group_id}"``.
Returns groups that are ancestors of the specified group. The groups are
returned in order, starting with the immediate parent and ending with
the most distant ancestor. If the specified group has no immediate
parent, the results are empty.
descendants_of_group (str): A group name: ``"projects/{project_id_or_number}/groups/{group_id}"``.
Returns the descendants of the specified group. This is a superset of
the results returned by the ``childrenOfGroup`` filter, and includes
children-of-children, and so forth.
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
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.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.monitoring_v3.types.Group` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
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. | [
"Lists",
"the",
"existing",
"groups",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/gapic/group_service_client.py#L206-L338 |
28,353 | googleapis/google-cloud-python | texttospeech/google/cloud/texttospeech_v1beta1/gapic/text_to_speech_client.py | TextToSpeechClient.list_voices | def list_voices(
self,
language_code=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Returns a list of ``Voice`` supported for synthesis.
Example:
>>> from google.cloud import texttospeech_v1beta1
>>>
>>> client = texttospeech_v1beta1.TextToSpeechClient()
>>>
>>> response = client.list_voices()
Args:
language_code (str): Optional (but recommended)
`BCP-47 <https://www.rfc-editor.org/rfc/bcp/bcp47.txt>`__ language tag.
If specified, the ListVoices call will only return voices that can be
used to synthesize this language\_code. E.g. when specifying "en-NZ",
you will get supported "en-*" voices; when specifying "no", you will get
supported "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices;
specifying "zh" will also get supported "cmn-*" voices; specifying
"zh-hk" will also get supported "yue-\*" voices.
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.texttospeech_v1beta1.types.ListVoicesResponse` 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_voices" not in self._inner_api_calls:
self._inner_api_calls[
"list_voices"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_voices,
default_retry=self._method_configs["ListVoices"].retry,
default_timeout=self._method_configs["ListVoices"].timeout,
client_info=self._client_info,
)
request = cloud_tts_pb2.ListVoicesRequest(language_code=language_code)
return self._inner_api_calls["list_voices"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def list_voices(
self,
language_code=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Returns a list of ``Voice`` supported for synthesis.
Example:
>>> from google.cloud import texttospeech_v1beta1
>>>
>>> client = texttospeech_v1beta1.TextToSpeechClient()
>>>
>>> response = client.list_voices()
Args:
language_code (str): Optional (but recommended)
`BCP-47 <https://www.rfc-editor.org/rfc/bcp/bcp47.txt>`__ language tag.
If specified, the ListVoices call will only return voices that can be
used to synthesize this language\_code. E.g. when specifying "en-NZ",
you will get supported "en-*" voices; when specifying "no", you will get
supported "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices;
specifying "zh" will also get supported "cmn-*" voices; specifying
"zh-hk" will also get supported "yue-\*" voices.
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.texttospeech_v1beta1.types.ListVoicesResponse` 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_voices" not in self._inner_api_calls:
self._inner_api_calls[
"list_voices"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_voices,
default_retry=self._method_configs["ListVoices"].retry,
default_timeout=self._method_configs["ListVoices"].timeout,
client_info=self._client_info,
)
request = cloud_tts_pb2.ListVoicesRequest(language_code=language_code)
return self._inner_api_calls["list_voices"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"list_voices",
"(",
"self",
",",
"language_code",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"list_voices\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"list_voices\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"list_voices",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"ListVoices\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"ListVoices\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"cloud_tts_pb2",
".",
"ListVoicesRequest",
"(",
"language_code",
"=",
"language_code",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"list_voices\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Returns a list of ``Voice`` supported for synthesis.
Example:
>>> from google.cloud import texttospeech_v1beta1
>>>
>>> client = texttospeech_v1beta1.TextToSpeechClient()
>>>
>>> response = client.list_voices()
Args:
language_code (str): Optional (but recommended)
`BCP-47 <https://www.rfc-editor.org/rfc/bcp/bcp47.txt>`__ language tag.
If specified, the ListVoices call will only return voices that can be
used to synthesize this language\_code. E.g. when specifying "en-NZ",
you will get supported "en-*" voices; when specifying "no", you will get
supported "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices;
specifying "zh" will also get supported "cmn-*" voices; specifying
"zh-hk" will also get supported "yue-\*" voices.
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.texttospeech_v1beta1.types.ListVoicesResponse` 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. | [
"Returns",
"a",
"list",
"of",
"Voice",
"supported",
"for",
"synthesis",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/texttospeech/google/cloud/texttospeech_v1beta1/gapic/text_to_speech_client.py#L170-L229 |
28,354 | googleapis/google-cloud-python | storage/google/cloud/storage/_signing.py | ensure_signed_credentials | def ensure_signed_credentials(credentials):
"""Raise AttributeError if the credentials are unsigned.
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: The credentials used to create a private key
for signing text.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
"""
if not isinstance(credentials, google.auth.credentials.Signing):
auth_uri = (
"https://google-cloud-python.readthedocs.io/en/latest/"
"core/auth.html?highlight=authentication#setting-up-"
"a-service-account"
)
raise AttributeError(
"you need a private key to sign credentials."
"the credentials you are currently using %s "
"just contains a token. see %s for more "
"details." % (type(credentials), auth_uri)
) | python | def ensure_signed_credentials(credentials):
"""Raise AttributeError if the credentials are unsigned.
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: The credentials used to create a private key
for signing text.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
"""
if not isinstance(credentials, google.auth.credentials.Signing):
auth_uri = (
"https://google-cloud-python.readthedocs.io/en/latest/"
"core/auth.html?highlight=authentication#setting-up-"
"a-service-account"
)
raise AttributeError(
"you need a private key to sign credentials."
"the credentials you are currently using %s "
"just contains a token. see %s for more "
"details." % (type(credentials), auth_uri)
) | [
"def",
"ensure_signed_credentials",
"(",
"credentials",
")",
":",
"if",
"not",
"isinstance",
"(",
"credentials",
",",
"google",
".",
"auth",
".",
"credentials",
".",
"Signing",
")",
":",
"auth_uri",
"=",
"(",
"\"https://google-cloud-python.readthedocs.io/en/latest/\"",
"\"core/auth.html?highlight=authentication#setting-up-\"",
"\"a-service-account\"",
")",
"raise",
"AttributeError",
"(",
"\"you need a private key to sign credentials.\"",
"\"the credentials you are currently using %s \"",
"\"just contains a token. see %s for more \"",
"\"details.\"",
"%",
"(",
"type",
"(",
"credentials",
")",
",",
"auth_uri",
")",
")"
] | Raise AttributeError if the credentials are unsigned.
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: The credentials used to create a private key
for signing text.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`. | [
"Raise",
"AttributeError",
"if",
"the",
"credentials",
"are",
"unsigned",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_signing.py#L34-L55 |
28,355 | googleapis/google-cloud-python | storage/google/cloud/storage/_signing.py | get_signed_query_params_v2 | def get_signed_query_params_v2(credentials, expiration, string_to_sign):
"""Gets query parameters for creating a signed URL.
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: The credentials used to create a private key
for signing text.
:type expiration: int or long
:param expiration: When the signed URL should expire.
:type string_to_sign: str
:param string_to_sign: The string to be signed by the credentials.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
:rtype: dict
:returns: Query parameters matching the signing credentials with a
signed payload.
"""
ensure_signed_credentials(credentials)
signature_bytes = credentials.sign_bytes(string_to_sign)
signature = base64.b64encode(signature_bytes)
service_account_name = credentials.signer_email
return {
"GoogleAccessId": service_account_name,
"Expires": str(expiration),
"Signature": signature,
} | python | def get_signed_query_params_v2(credentials, expiration, string_to_sign):
"""Gets query parameters for creating a signed URL.
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: The credentials used to create a private key
for signing text.
:type expiration: int or long
:param expiration: When the signed URL should expire.
:type string_to_sign: str
:param string_to_sign: The string to be signed by the credentials.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
:rtype: dict
:returns: Query parameters matching the signing credentials with a
signed payload.
"""
ensure_signed_credentials(credentials)
signature_bytes = credentials.sign_bytes(string_to_sign)
signature = base64.b64encode(signature_bytes)
service_account_name = credentials.signer_email
return {
"GoogleAccessId": service_account_name,
"Expires": str(expiration),
"Signature": signature,
} | [
"def",
"get_signed_query_params_v2",
"(",
"credentials",
",",
"expiration",
",",
"string_to_sign",
")",
":",
"ensure_signed_credentials",
"(",
"credentials",
")",
"signature_bytes",
"=",
"credentials",
".",
"sign_bytes",
"(",
"string_to_sign",
")",
"signature",
"=",
"base64",
".",
"b64encode",
"(",
"signature_bytes",
")",
"service_account_name",
"=",
"credentials",
".",
"signer_email",
"return",
"{",
"\"GoogleAccessId\"",
":",
"service_account_name",
",",
"\"Expires\"",
":",
"str",
"(",
"expiration",
")",
",",
"\"Signature\"",
":",
"signature",
",",
"}"
] | Gets query parameters for creating a signed URL.
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: The credentials used to create a private key
for signing text.
:type expiration: int or long
:param expiration: When the signed URL should expire.
:type string_to_sign: str
:param string_to_sign: The string to be signed by the credentials.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
:rtype: dict
:returns: Query parameters matching the signing credentials with a
signed payload. | [
"Gets",
"query",
"parameters",
"for",
"creating",
"a",
"signed",
"URL",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_signing.py#L58-L86 |
28,356 | googleapis/google-cloud-python | storage/google/cloud/storage/_signing.py | get_expiration_seconds_v2 | def get_expiration_seconds_v2(expiration):
"""Convert 'expiration' to a number of seconds in the future.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:raises: :exc:`TypeError` when expiration is not a valid type.
:rtype: int
:returns: a timestamp as an absolute number of seconds since epoch.
"""
# If it's a timedelta, add it to `now` in UTC.
if isinstance(expiration, datetime.timedelta):
now = NOW().replace(tzinfo=_helpers.UTC)
expiration = now + expiration
# If it's a datetime, convert to a timestamp.
if isinstance(expiration, datetime.datetime):
micros = _helpers._microseconds_from_datetime(expiration)
expiration = micros // 10 ** 6
if not isinstance(expiration, six.integer_types):
raise TypeError(
"Expected an integer timestamp, datetime, or "
"timedelta. Got %s" % type(expiration)
)
return expiration | python | def get_expiration_seconds_v2(expiration):
"""Convert 'expiration' to a number of seconds in the future.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:raises: :exc:`TypeError` when expiration is not a valid type.
:rtype: int
:returns: a timestamp as an absolute number of seconds since epoch.
"""
# If it's a timedelta, add it to `now` in UTC.
if isinstance(expiration, datetime.timedelta):
now = NOW().replace(tzinfo=_helpers.UTC)
expiration = now + expiration
# If it's a datetime, convert to a timestamp.
if isinstance(expiration, datetime.datetime):
micros = _helpers._microseconds_from_datetime(expiration)
expiration = micros // 10 ** 6
if not isinstance(expiration, six.integer_types):
raise TypeError(
"Expected an integer timestamp, datetime, or "
"timedelta. Got %s" % type(expiration)
)
return expiration | [
"def",
"get_expiration_seconds_v2",
"(",
"expiration",
")",
":",
"# If it's a timedelta, add it to `now` in UTC.",
"if",
"isinstance",
"(",
"expiration",
",",
"datetime",
".",
"timedelta",
")",
":",
"now",
"=",
"NOW",
"(",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"_helpers",
".",
"UTC",
")",
"expiration",
"=",
"now",
"+",
"expiration",
"# If it's a datetime, convert to a timestamp.",
"if",
"isinstance",
"(",
"expiration",
",",
"datetime",
".",
"datetime",
")",
":",
"micros",
"=",
"_helpers",
".",
"_microseconds_from_datetime",
"(",
"expiration",
")",
"expiration",
"=",
"micros",
"//",
"10",
"**",
"6",
"if",
"not",
"isinstance",
"(",
"expiration",
",",
"six",
".",
"integer_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected an integer timestamp, datetime, or \"",
"\"timedelta. Got %s\"",
"%",
"type",
"(",
"expiration",
")",
")",
"return",
"expiration"
] | Convert 'expiration' to a number of seconds in the future.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:raises: :exc:`TypeError` when expiration is not a valid type.
:rtype: int
:returns: a timestamp as an absolute number of seconds since epoch. | [
"Convert",
"expiration",
"to",
"a",
"number",
"of",
"seconds",
"in",
"the",
"future",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_signing.py#L89-L115 |
28,357 | googleapis/google-cloud-python | storage/google/cloud/storage/_signing.py | get_expiration_seconds_v4 | def get_expiration_seconds_v4(expiration):
"""Convert 'expiration' to a number of seconds offset from the current time.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`ValueError` when expiration is too large.
:rtype: Integer
:returns: seconds in the future when the signed URL will expire
"""
if not isinstance(expiration, _EXPIRATION_TYPES):
raise TypeError(
"Expected an integer timestamp, datetime, or "
"timedelta. Got %s" % type(expiration)
)
now = NOW().replace(tzinfo=_helpers.UTC)
if isinstance(expiration, six.integer_types):
seconds = expiration
if isinstance(expiration, datetime.datetime):
if expiration.tzinfo is None:
expiration = expiration.replace(tzinfo=_helpers.UTC)
expiration = expiration - now
if isinstance(expiration, datetime.timedelta):
seconds = int(expiration.total_seconds())
if seconds > SEVEN_DAYS:
raise ValueError(
"Max allowed expiration interval is seven days (%d seconds)".format(
SEVEN_DAYS
)
)
return seconds | python | def get_expiration_seconds_v4(expiration):
"""Convert 'expiration' to a number of seconds offset from the current time.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`ValueError` when expiration is too large.
:rtype: Integer
:returns: seconds in the future when the signed URL will expire
"""
if not isinstance(expiration, _EXPIRATION_TYPES):
raise TypeError(
"Expected an integer timestamp, datetime, or "
"timedelta. Got %s" % type(expiration)
)
now = NOW().replace(tzinfo=_helpers.UTC)
if isinstance(expiration, six.integer_types):
seconds = expiration
if isinstance(expiration, datetime.datetime):
if expiration.tzinfo is None:
expiration = expiration.replace(tzinfo=_helpers.UTC)
expiration = expiration - now
if isinstance(expiration, datetime.timedelta):
seconds = int(expiration.total_seconds())
if seconds > SEVEN_DAYS:
raise ValueError(
"Max allowed expiration interval is seven days (%d seconds)".format(
SEVEN_DAYS
)
)
return seconds | [
"def",
"get_expiration_seconds_v4",
"(",
"expiration",
")",
":",
"if",
"not",
"isinstance",
"(",
"expiration",
",",
"_EXPIRATION_TYPES",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected an integer timestamp, datetime, or \"",
"\"timedelta. Got %s\"",
"%",
"type",
"(",
"expiration",
")",
")",
"now",
"=",
"NOW",
"(",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"_helpers",
".",
"UTC",
")",
"if",
"isinstance",
"(",
"expiration",
",",
"six",
".",
"integer_types",
")",
":",
"seconds",
"=",
"expiration",
"if",
"isinstance",
"(",
"expiration",
",",
"datetime",
".",
"datetime",
")",
":",
"if",
"expiration",
".",
"tzinfo",
"is",
"None",
":",
"expiration",
"=",
"expiration",
".",
"replace",
"(",
"tzinfo",
"=",
"_helpers",
".",
"UTC",
")",
"expiration",
"=",
"expiration",
"-",
"now",
"if",
"isinstance",
"(",
"expiration",
",",
"datetime",
".",
"timedelta",
")",
":",
"seconds",
"=",
"int",
"(",
"expiration",
".",
"total_seconds",
"(",
")",
")",
"if",
"seconds",
">",
"SEVEN_DAYS",
":",
"raise",
"ValueError",
"(",
"\"Max allowed expiration interval is seven days (%d seconds)\"",
".",
"format",
"(",
"SEVEN_DAYS",
")",
")",
"return",
"seconds"
] | Convert 'expiration' to a number of seconds offset from the current time.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`ValueError` when expiration is too large.
:rtype: Integer
:returns: seconds in the future when the signed URL will expire | [
"Convert",
"expiration",
"to",
"a",
"number",
"of",
"seconds",
"offset",
"from",
"the",
"current",
"time",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_signing.py#L121-L160 |
28,358 | googleapis/google-cloud-python | storage/google/cloud/storage/_signing.py | get_canonical_headers | def get_canonical_headers(headers):
"""Canonicalize headers for signing.
See:
https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers
:type headers: Union[dict|List(Tuple(str,str))]
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:rtype: str
:returns: List of headers, normalized / sortted per the URL refernced above.
"""
if headers is None:
headers = []
elif isinstance(headers, dict):
headers = list(headers.items())
if not headers:
return [], []
normalized = collections.defaultdict(list)
for key, val in headers:
key = key.lower().strip()
val = MULTIPLE_SPACES.sub(" ", val.strip())
normalized[key].append(val)
ordered_headers = sorted((key, ",".join(val)) for key, val in normalized.items())
canonical_headers = ["{}:{}".format(*item) for item in ordered_headers]
return canonical_headers, ordered_headers | python | def get_canonical_headers(headers):
"""Canonicalize headers for signing.
See:
https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers
:type headers: Union[dict|List(Tuple(str,str))]
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:rtype: str
:returns: List of headers, normalized / sortted per the URL refernced above.
"""
if headers is None:
headers = []
elif isinstance(headers, dict):
headers = list(headers.items())
if not headers:
return [], []
normalized = collections.defaultdict(list)
for key, val in headers:
key = key.lower().strip()
val = MULTIPLE_SPACES.sub(" ", val.strip())
normalized[key].append(val)
ordered_headers = sorted((key, ",".join(val)) for key, val in normalized.items())
canonical_headers = ["{}:{}".format(*item) for item in ordered_headers]
return canonical_headers, ordered_headers | [
"def",
"get_canonical_headers",
"(",
"headers",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"[",
"]",
"elif",
"isinstance",
"(",
"headers",
",",
"dict",
")",
":",
"headers",
"=",
"list",
"(",
"headers",
".",
"items",
"(",
")",
")",
"if",
"not",
"headers",
":",
"return",
"[",
"]",
",",
"[",
"]",
"normalized",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"key",
",",
"val",
"in",
"headers",
":",
"key",
"=",
"key",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"val",
"=",
"MULTIPLE_SPACES",
".",
"sub",
"(",
"\" \"",
",",
"val",
".",
"strip",
"(",
")",
")",
"normalized",
"[",
"key",
"]",
".",
"append",
"(",
"val",
")",
"ordered_headers",
"=",
"sorted",
"(",
"(",
"key",
",",
"\",\"",
".",
"join",
"(",
"val",
")",
")",
"for",
"key",
",",
"val",
"in",
"normalized",
".",
"items",
"(",
")",
")",
"canonical_headers",
"=",
"[",
"\"{}:{}\"",
".",
"format",
"(",
"*",
"item",
")",
"for",
"item",
"in",
"ordered_headers",
"]",
"return",
"canonical_headers",
",",
"ordered_headers"
] | Canonicalize headers for signing.
See:
https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers
:type headers: Union[dict|List(Tuple(str,str))]
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:rtype: str
:returns: List of headers, normalized / sortted per the URL refernced above. | [
"Canonicalize",
"headers",
"for",
"signing",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_signing.py#L163-L197 |
28,359 | googleapis/google-cloud-python | storage/google/cloud/storage/_signing.py | canonicalize | def canonicalize(method, resource, query_parameters, headers):
"""Canonicalize method, resource
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
signature will additionally contain the `x-goog-resumable`
header, and the method changed to POST. See the signed URL
docs regarding this flow:
https://cloud.google.com/storage/docs/access-control/signed-urls
:type resource: str
:param resource: A pointer to a specific resource
(typically, ``/bucket-name/path/to/blob.txt``).
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
:type headers: Union[dict|List(Tuple(str,str))]
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:rtype: :class:_Canonical
:returns: Canonical method, resource, query_parameters, and headers.
"""
headers, _ = get_canonical_headers(headers)
if method == "RESUMABLE":
method = "POST"
headers.append("x-goog-resumable:start")
if query_parameters is None:
return _Canonical(method, resource, [], headers)
normalized_qp = sorted(
(key.lower(), value and value.strip() or "")
for key, value in query_parameters.items()
)
encoded_qp = six.moves.urllib.parse.urlencode(normalized_qp)
canonical_resource = "{}?{}".format(resource, encoded_qp)
return _Canonical(method, canonical_resource, normalized_qp, headers) | python | def canonicalize(method, resource, query_parameters, headers):
"""Canonicalize method, resource
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
signature will additionally contain the `x-goog-resumable`
header, and the method changed to POST. See the signed URL
docs regarding this flow:
https://cloud.google.com/storage/docs/access-control/signed-urls
:type resource: str
:param resource: A pointer to a specific resource
(typically, ``/bucket-name/path/to/blob.txt``).
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
:type headers: Union[dict|List(Tuple(str,str))]
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:rtype: :class:_Canonical
:returns: Canonical method, resource, query_parameters, and headers.
"""
headers, _ = get_canonical_headers(headers)
if method == "RESUMABLE":
method = "POST"
headers.append("x-goog-resumable:start")
if query_parameters is None:
return _Canonical(method, resource, [], headers)
normalized_qp = sorted(
(key.lower(), value and value.strip() or "")
for key, value in query_parameters.items()
)
encoded_qp = six.moves.urllib.parse.urlencode(normalized_qp)
canonical_resource = "{}?{}".format(resource, encoded_qp)
return _Canonical(method, canonical_resource, normalized_qp, headers) | [
"def",
"canonicalize",
"(",
"method",
",",
"resource",
",",
"query_parameters",
",",
"headers",
")",
":",
"headers",
",",
"_",
"=",
"get_canonical_headers",
"(",
"headers",
")",
"if",
"method",
"==",
"\"RESUMABLE\"",
":",
"method",
"=",
"\"POST\"",
"headers",
".",
"append",
"(",
"\"x-goog-resumable:start\"",
")",
"if",
"query_parameters",
"is",
"None",
":",
"return",
"_Canonical",
"(",
"method",
",",
"resource",
",",
"[",
"]",
",",
"headers",
")",
"normalized_qp",
"=",
"sorted",
"(",
"(",
"key",
".",
"lower",
"(",
")",
",",
"value",
"and",
"value",
".",
"strip",
"(",
")",
"or",
"\"\"",
")",
"for",
"key",
",",
"value",
"in",
"query_parameters",
".",
"items",
"(",
")",
")",
"encoded_qp",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlencode",
"(",
"normalized_qp",
")",
"canonical_resource",
"=",
"\"{}?{}\"",
".",
"format",
"(",
"resource",
",",
"encoded_qp",
")",
"return",
"_Canonical",
"(",
"method",
",",
"canonical_resource",
",",
"normalized_qp",
",",
"headers",
")"
] | Canonicalize method, resource
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
signature will additionally contain the `x-goog-resumable`
header, and the method changed to POST. See the signed URL
docs regarding this flow:
https://cloud.google.com/storage/docs/access-control/signed-urls
:type resource: str
:param resource: A pointer to a specific resource
(typically, ``/bucket-name/path/to/blob.txt``).
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
:type headers: Union[dict|List(Tuple(str,str))]
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:rtype: :class:_Canonical
:returns: Canonical method, resource, query_parameters, and headers. | [
"Canonicalize",
"method",
"resource"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_signing.py#L205-L252 |
28,360 | googleapis/google-cloud-python | storage/google/cloud/storage/_signing.py | generate_signed_url_v2 | def generate_signed_url_v2(
credentials,
resource,
expiration,
api_access_endpoint="",
method="GET",
content_md5=None,
content_type=None,
response_type=None,
response_disposition=None,
generation=None,
headers=None,
query_parameters=None,
):
"""Generate a V2 signed URL to provide query-string auth'n to a resource.
.. note::
Assumes ``credentials`` implements the
:class:`google.auth.credentials.Signing` interface. Also assumes
``credentials`` has a ``service_account_email`` property which
identifies the credentials.
.. note::
If you are on Google Compute Engine, you can't generate a signed URL.
Follow `Issue 922`_ for updates on this. If you'd like to be able to
generate a signed URL from GCE, you can use a standard service account
from a JSON file rather than a GCE service account.
See headers `reference`_ for more details on optional arguments.
.. _Issue 922: https://github.com/GoogleCloudPlatform/\
google-cloud-python/issues/922
.. _reference: https://cloud.google.com/storage/docs/reference-headers
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: Credentials object with an associated private key to
sign text.
:type resource: str
:param resource: A pointer to a specific resource
(typically, ``/bucket-name/path/to/blob.txt``).
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:type api_access_endpoint: str
:param api_access_endpoint: Optional URI base. Defaults to empty string.
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
signature will additionally contain the `x-goog-resumable`
header, and the method changed to POST. See the signed URL
docs regarding this flow:
https://cloud.google.com/storage/docs/access-control/signed-urls
:type content_md5: str
:param content_md5: (Optional) The MD5 hash of the object referenced by
``resource``.
:type content_type: str
:param content_type: (Optional) The content type of the object referenced
by ``resource``.
:type response_type: str
:param response_type: (Optional) Content type of responses to requests for
the signed URL. Used to over-ride the content type of
the underlying resource.
:type response_disposition: str
:param response_disposition: (Optional) Content disposition of responses to
requests for the signed URL.
:type generation: str
:param generation: (Optional) A value that indicates which generation of
the resource to fetch.
:type headers: Union[dict|List(Tuple(str,str))]
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
:rtype: str
:returns: A signed URL you can use to access the resource
until expiration.
"""
expiration_stamp = get_expiration_seconds_v2(expiration)
canonical = canonicalize(method, resource, query_parameters, headers)
# Generate the string to sign.
elements_to_sign = [
canonical.method,
content_md5 or "",
content_type or "",
str(expiration_stamp),
]
elements_to_sign.extend(canonical.headers)
elements_to_sign.append(canonical.resource)
string_to_sign = "\n".join(elements_to_sign)
# Set the right query parameters.
signed_query_params = get_signed_query_params_v2(
credentials, expiration_stamp, string_to_sign
)
if response_type is not None:
signed_query_params["response-content-type"] = response_type
if response_disposition is not None:
signed_query_params["response-content-disposition"] = response_disposition
if generation is not None:
signed_query_params["generation"] = generation
signed_query_params.update(canonical.query_parameters)
sorted_signed_query_params = sorted(signed_query_params.items())
# Return the built URL.
return "{endpoint}{resource}?{querystring}".format(
endpoint=api_access_endpoint,
resource=resource,
querystring=six.moves.urllib.parse.urlencode(sorted_signed_query_params),
) | python | def generate_signed_url_v2(
credentials,
resource,
expiration,
api_access_endpoint="",
method="GET",
content_md5=None,
content_type=None,
response_type=None,
response_disposition=None,
generation=None,
headers=None,
query_parameters=None,
):
"""Generate a V2 signed URL to provide query-string auth'n to a resource.
.. note::
Assumes ``credentials`` implements the
:class:`google.auth.credentials.Signing` interface. Also assumes
``credentials`` has a ``service_account_email`` property which
identifies the credentials.
.. note::
If you are on Google Compute Engine, you can't generate a signed URL.
Follow `Issue 922`_ for updates on this. If you'd like to be able to
generate a signed URL from GCE, you can use a standard service account
from a JSON file rather than a GCE service account.
See headers `reference`_ for more details on optional arguments.
.. _Issue 922: https://github.com/GoogleCloudPlatform/\
google-cloud-python/issues/922
.. _reference: https://cloud.google.com/storage/docs/reference-headers
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: Credentials object with an associated private key to
sign text.
:type resource: str
:param resource: A pointer to a specific resource
(typically, ``/bucket-name/path/to/blob.txt``).
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:type api_access_endpoint: str
:param api_access_endpoint: Optional URI base. Defaults to empty string.
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
signature will additionally contain the `x-goog-resumable`
header, and the method changed to POST. See the signed URL
docs regarding this flow:
https://cloud.google.com/storage/docs/access-control/signed-urls
:type content_md5: str
:param content_md5: (Optional) The MD5 hash of the object referenced by
``resource``.
:type content_type: str
:param content_type: (Optional) The content type of the object referenced
by ``resource``.
:type response_type: str
:param response_type: (Optional) Content type of responses to requests for
the signed URL. Used to over-ride the content type of
the underlying resource.
:type response_disposition: str
:param response_disposition: (Optional) Content disposition of responses to
requests for the signed URL.
:type generation: str
:param generation: (Optional) A value that indicates which generation of
the resource to fetch.
:type headers: Union[dict|List(Tuple(str,str))]
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
:rtype: str
:returns: A signed URL you can use to access the resource
until expiration.
"""
expiration_stamp = get_expiration_seconds_v2(expiration)
canonical = canonicalize(method, resource, query_parameters, headers)
# Generate the string to sign.
elements_to_sign = [
canonical.method,
content_md5 or "",
content_type or "",
str(expiration_stamp),
]
elements_to_sign.extend(canonical.headers)
elements_to_sign.append(canonical.resource)
string_to_sign = "\n".join(elements_to_sign)
# Set the right query parameters.
signed_query_params = get_signed_query_params_v2(
credentials, expiration_stamp, string_to_sign
)
if response_type is not None:
signed_query_params["response-content-type"] = response_type
if response_disposition is not None:
signed_query_params["response-content-disposition"] = response_disposition
if generation is not None:
signed_query_params["generation"] = generation
signed_query_params.update(canonical.query_parameters)
sorted_signed_query_params = sorted(signed_query_params.items())
# Return the built URL.
return "{endpoint}{resource}?{querystring}".format(
endpoint=api_access_endpoint,
resource=resource,
querystring=six.moves.urllib.parse.urlencode(sorted_signed_query_params),
) | [
"def",
"generate_signed_url_v2",
"(",
"credentials",
",",
"resource",
",",
"expiration",
",",
"api_access_endpoint",
"=",
"\"\"",
",",
"method",
"=",
"\"GET\"",
",",
"content_md5",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"response_type",
"=",
"None",
",",
"response_disposition",
"=",
"None",
",",
"generation",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"query_parameters",
"=",
"None",
",",
")",
":",
"expiration_stamp",
"=",
"get_expiration_seconds_v2",
"(",
"expiration",
")",
"canonical",
"=",
"canonicalize",
"(",
"method",
",",
"resource",
",",
"query_parameters",
",",
"headers",
")",
"# Generate the string to sign.",
"elements_to_sign",
"=",
"[",
"canonical",
".",
"method",
",",
"content_md5",
"or",
"\"\"",
",",
"content_type",
"or",
"\"\"",
",",
"str",
"(",
"expiration_stamp",
")",
",",
"]",
"elements_to_sign",
".",
"extend",
"(",
"canonical",
".",
"headers",
")",
"elements_to_sign",
".",
"append",
"(",
"canonical",
".",
"resource",
")",
"string_to_sign",
"=",
"\"\\n\"",
".",
"join",
"(",
"elements_to_sign",
")",
"# Set the right query parameters.",
"signed_query_params",
"=",
"get_signed_query_params_v2",
"(",
"credentials",
",",
"expiration_stamp",
",",
"string_to_sign",
")",
"if",
"response_type",
"is",
"not",
"None",
":",
"signed_query_params",
"[",
"\"response-content-type\"",
"]",
"=",
"response_type",
"if",
"response_disposition",
"is",
"not",
"None",
":",
"signed_query_params",
"[",
"\"response-content-disposition\"",
"]",
"=",
"response_disposition",
"if",
"generation",
"is",
"not",
"None",
":",
"signed_query_params",
"[",
"\"generation\"",
"]",
"=",
"generation",
"signed_query_params",
".",
"update",
"(",
"canonical",
".",
"query_parameters",
")",
"sorted_signed_query_params",
"=",
"sorted",
"(",
"signed_query_params",
".",
"items",
"(",
")",
")",
"# Return the built URL.",
"return",
"\"{endpoint}{resource}?{querystring}\"",
".",
"format",
"(",
"endpoint",
"=",
"api_access_endpoint",
",",
"resource",
"=",
"resource",
",",
"querystring",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlencode",
"(",
"sorted_signed_query_params",
")",
",",
")"
] | Generate a V2 signed URL to provide query-string auth'n to a resource.
.. note::
Assumes ``credentials`` implements the
:class:`google.auth.credentials.Signing` interface. Also assumes
``credentials`` has a ``service_account_email`` property which
identifies the credentials.
.. note::
If you are on Google Compute Engine, you can't generate a signed URL.
Follow `Issue 922`_ for updates on this. If you'd like to be able to
generate a signed URL from GCE, you can use a standard service account
from a JSON file rather than a GCE service account.
See headers `reference`_ for more details on optional arguments.
.. _Issue 922: https://github.com/GoogleCloudPlatform/\
google-cloud-python/issues/922
.. _reference: https://cloud.google.com/storage/docs/reference-headers
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: Credentials object with an associated private key to
sign text.
:type resource: str
:param resource: A pointer to a specific resource
(typically, ``/bucket-name/path/to/blob.txt``).
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:type api_access_endpoint: str
:param api_access_endpoint: Optional URI base. Defaults to empty string.
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
signature will additionally contain the `x-goog-resumable`
header, and the method changed to POST. See the signed URL
docs regarding this flow:
https://cloud.google.com/storage/docs/access-control/signed-urls
:type content_md5: str
:param content_md5: (Optional) The MD5 hash of the object referenced by
``resource``.
:type content_type: str
:param content_type: (Optional) The content type of the object referenced
by ``resource``.
:type response_type: str
:param response_type: (Optional) Content type of responses to requests for
the signed URL. Used to over-ride the content type of
the underlying resource.
:type response_disposition: str
:param response_disposition: (Optional) Content disposition of responses to
requests for the signed URL.
:type generation: str
:param generation: (Optional) A value that indicates which generation of
the resource to fetch.
:type headers: Union[dict|List(Tuple(str,str))]
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
:rtype: str
:returns: A signed URL you can use to access the resource
until expiration. | [
"Generate",
"a",
"V2",
"signed",
"URL",
"to",
"provide",
"query",
"-",
"string",
"auth",
"n",
"to",
"a",
"resource",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_signing.py#L255-L392 |
28,361 | googleapis/google-cloud-python | storage/google/cloud/storage/_signing.py | generate_signed_url_v4 | def generate_signed_url_v4(
credentials,
resource,
expiration,
api_access_endpoint=DEFAULT_ENDPOINT,
method="GET",
content_md5=None,
content_type=None,
response_type=None,
response_disposition=None,
generation=None,
headers=None,
query_parameters=None,
_request_timestamp=None, # for testing only
):
"""Generate a V4 signed URL to provide query-string auth'n to a resource.
.. note::
Assumes ``credentials`` implements the
:class:`google.auth.credentials.Signing` interface. Also assumes
``credentials`` has a ``service_account_email`` property which
identifies the credentials.
.. note::
If you are on Google Compute Engine, you can't generate a signed URL.
Follow `Issue 922`_ for updates on this. If you'd like to be able to
generate a signed URL from GCE, you can use a standard service account
from a JSON file rather than a GCE service account.
See headers `reference`_ for more details on optional arguments.
.. _Issue 922: https://github.com/GoogleCloudPlatform/\
google-cloud-python/issues/922
.. _reference: https://cloud.google.com/storage/docs/reference-headers
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: Credentials object with an associated private key to
sign text.
:type resource: str
:param resource: A pointer to a specific resource
(typically, ``/bucket-name/path/to/blob.txt``).
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:type api_access_endpoint: str
:param api_access_endpoint: Optional URI base. Defaults to
"https://storage.googleapis.com/"
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
signature will additionally contain the `x-goog-resumable`
header, and the method changed to POST. See the signed URL
docs regarding this flow:
https://cloud.google.com/storage/docs/access-control/signed-urls
:type content_md5: str
:param content_md5: (Optional) The MD5 hash of the object referenced by
``resource``.
:type content_type: str
:param content_type: (Optional) The content type of the object referenced
by ``resource``.
:type response_type: str
:param response_type: (Optional) Content type of responses to requests for
the signed URL. Used to over-ride the content type of
the underlying resource.
:type response_disposition: str
:param response_disposition: (Optional) Content disposition of responses to
requests for the signed URL.
:type generation: str
:param generation: (Optional) A value that indicates which generation of
the resource to fetch.
:type headers: dict
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
:rtype: str
:returns: A signed URL you can use to access the resource
until expiration.
"""
ensure_signed_credentials(credentials)
expiration_seconds = get_expiration_seconds_v4(expiration)
if _request_timestamp is None:
now = NOW()
request_timestamp = now.strftime("%Y%m%dT%H%M%SZ")
datestamp = now.date().strftime("%Y%m%d")
else:
request_timestamp = _request_timestamp
datestamp = _request_timestamp[:8]
client_email = credentials.signer_email
credential_scope = "{}/auto/storage/goog4_request".format(datestamp)
credential = "{}/{}".format(client_email, credential_scope)
if headers is None:
headers = {}
if content_type is not None:
headers["Content-Type"] = content_type
if content_md5 is not None:
headers["Content-MD5"] = content_md5
header_names = [key.lower() for key in headers]
if "host" not in header_names:
headers["Host"] = "storage.googleapis.com"
if method.upper() == "RESUMABLE":
method = "POST"
headers["x-goog-resumable"] = "start"
canonical_headers, ordered_headers = get_canonical_headers(headers)
canonical_header_string = (
"\n".join(canonical_headers) + "\n"
) # Yes, Virginia, the extra newline is part of the spec.
signed_headers = ";".join([key for key, _ in ordered_headers])
if query_parameters is None:
query_parameters = {}
else:
query_parameters = {key: value or "" for key, value in query_parameters.items()}
query_parameters["X-Goog-Algorithm"] = "GOOG4-RSA-SHA256"
query_parameters["X-Goog-Credential"] = credential
query_parameters["X-Goog-Date"] = request_timestamp
query_parameters["X-Goog-Expires"] = expiration_seconds
query_parameters["X-Goog-SignedHeaders"] = signed_headers
if response_type is not None:
query_parameters["response-content-type"] = response_type
if response_disposition is not None:
query_parameters["response-content-disposition"] = response_disposition
if generation is not None:
query_parameters["generation"] = generation
ordered_query_parameters = sorted(query_parameters.items())
canonical_query_string = six.moves.urllib.parse.urlencode(ordered_query_parameters)
canonical_elements = [
method,
resource,
canonical_query_string,
canonical_header_string,
signed_headers,
"UNSIGNED-PAYLOAD",
]
canonical_request = "\n".join(canonical_elements)
canonical_request_hash = hashlib.sha256(
canonical_request.encode("ascii")
).hexdigest()
string_elements = [
"GOOG4-RSA-SHA256",
request_timestamp,
credential_scope,
canonical_request_hash,
]
string_to_sign = "\n".join(string_elements)
signature_bytes = credentials.sign_bytes(string_to_sign.encode("ascii"))
signature = binascii.hexlify(signature_bytes).decode("ascii")
return "{}{}?{}&X-Goog-Signature={}".format(
api_access_endpoint, resource, canonical_query_string, signature
) | python | def generate_signed_url_v4(
credentials,
resource,
expiration,
api_access_endpoint=DEFAULT_ENDPOINT,
method="GET",
content_md5=None,
content_type=None,
response_type=None,
response_disposition=None,
generation=None,
headers=None,
query_parameters=None,
_request_timestamp=None, # for testing only
):
"""Generate a V4 signed URL to provide query-string auth'n to a resource.
.. note::
Assumes ``credentials`` implements the
:class:`google.auth.credentials.Signing` interface. Also assumes
``credentials`` has a ``service_account_email`` property which
identifies the credentials.
.. note::
If you are on Google Compute Engine, you can't generate a signed URL.
Follow `Issue 922`_ for updates on this. If you'd like to be able to
generate a signed URL from GCE, you can use a standard service account
from a JSON file rather than a GCE service account.
See headers `reference`_ for more details on optional arguments.
.. _Issue 922: https://github.com/GoogleCloudPlatform/\
google-cloud-python/issues/922
.. _reference: https://cloud.google.com/storage/docs/reference-headers
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: Credentials object with an associated private key to
sign text.
:type resource: str
:param resource: A pointer to a specific resource
(typically, ``/bucket-name/path/to/blob.txt``).
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:type api_access_endpoint: str
:param api_access_endpoint: Optional URI base. Defaults to
"https://storage.googleapis.com/"
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
signature will additionally contain the `x-goog-resumable`
header, and the method changed to POST. See the signed URL
docs regarding this flow:
https://cloud.google.com/storage/docs/access-control/signed-urls
:type content_md5: str
:param content_md5: (Optional) The MD5 hash of the object referenced by
``resource``.
:type content_type: str
:param content_type: (Optional) The content type of the object referenced
by ``resource``.
:type response_type: str
:param response_type: (Optional) Content type of responses to requests for
the signed URL. Used to over-ride the content type of
the underlying resource.
:type response_disposition: str
:param response_disposition: (Optional) Content disposition of responses to
requests for the signed URL.
:type generation: str
:param generation: (Optional) A value that indicates which generation of
the resource to fetch.
:type headers: dict
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
:rtype: str
:returns: A signed URL you can use to access the resource
until expiration.
"""
ensure_signed_credentials(credentials)
expiration_seconds = get_expiration_seconds_v4(expiration)
if _request_timestamp is None:
now = NOW()
request_timestamp = now.strftime("%Y%m%dT%H%M%SZ")
datestamp = now.date().strftime("%Y%m%d")
else:
request_timestamp = _request_timestamp
datestamp = _request_timestamp[:8]
client_email = credentials.signer_email
credential_scope = "{}/auto/storage/goog4_request".format(datestamp)
credential = "{}/{}".format(client_email, credential_scope)
if headers is None:
headers = {}
if content_type is not None:
headers["Content-Type"] = content_type
if content_md5 is not None:
headers["Content-MD5"] = content_md5
header_names = [key.lower() for key in headers]
if "host" not in header_names:
headers["Host"] = "storage.googleapis.com"
if method.upper() == "RESUMABLE":
method = "POST"
headers["x-goog-resumable"] = "start"
canonical_headers, ordered_headers = get_canonical_headers(headers)
canonical_header_string = (
"\n".join(canonical_headers) + "\n"
) # Yes, Virginia, the extra newline is part of the spec.
signed_headers = ";".join([key for key, _ in ordered_headers])
if query_parameters is None:
query_parameters = {}
else:
query_parameters = {key: value or "" for key, value in query_parameters.items()}
query_parameters["X-Goog-Algorithm"] = "GOOG4-RSA-SHA256"
query_parameters["X-Goog-Credential"] = credential
query_parameters["X-Goog-Date"] = request_timestamp
query_parameters["X-Goog-Expires"] = expiration_seconds
query_parameters["X-Goog-SignedHeaders"] = signed_headers
if response_type is not None:
query_parameters["response-content-type"] = response_type
if response_disposition is not None:
query_parameters["response-content-disposition"] = response_disposition
if generation is not None:
query_parameters["generation"] = generation
ordered_query_parameters = sorted(query_parameters.items())
canonical_query_string = six.moves.urllib.parse.urlencode(ordered_query_parameters)
canonical_elements = [
method,
resource,
canonical_query_string,
canonical_header_string,
signed_headers,
"UNSIGNED-PAYLOAD",
]
canonical_request = "\n".join(canonical_elements)
canonical_request_hash = hashlib.sha256(
canonical_request.encode("ascii")
).hexdigest()
string_elements = [
"GOOG4-RSA-SHA256",
request_timestamp,
credential_scope,
canonical_request_hash,
]
string_to_sign = "\n".join(string_elements)
signature_bytes = credentials.sign_bytes(string_to_sign.encode("ascii"))
signature = binascii.hexlify(signature_bytes).decode("ascii")
return "{}{}?{}&X-Goog-Signature={}".format(
api_access_endpoint, resource, canonical_query_string, signature
) | [
"def",
"generate_signed_url_v4",
"(",
"credentials",
",",
"resource",
",",
"expiration",
",",
"api_access_endpoint",
"=",
"DEFAULT_ENDPOINT",
",",
"method",
"=",
"\"GET\"",
",",
"content_md5",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"response_type",
"=",
"None",
",",
"response_disposition",
"=",
"None",
",",
"generation",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"query_parameters",
"=",
"None",
",",
"_request_timestamp",
"=",
"None",
",",
"# for testing only",
")",
":",
"ensure_signed_credentials",
"(",
"credentials",
")",
"expiration_seconds",
"=",
"get_expiration_seconds_v4",
"(",
"expiration",
")",
"if",
"_request_timestamp",
"is",
"None",
":",
"now",
"=",
"NOW",
"(",
")",
"request_timestamp",
"=",
"now",
".",
"strftime",
"(",
"\"%Y%m%dT%H%M%SZ\"",
")",
"datestamp",
"=",
"now",
".",
"date",
"(",
")",
".",
"strftime",
"(",
"\"%Y%m%d\"",
")",
"else",
":",
"request_timestamp",
"=",
"_request_timestamp",
"datestamp",
"=",
"_request_timestamp",
"[",
":",
"8",
"]",
"client_email",
"=",
"credentials",
".",
"signer_email",
"credential_scope",
"=",
"\"{}/auto/storage/goog4_request\"",
".",
"format",
"(",
"datestamp",
")",
"credential",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"client_email",
",",
"credential_scope",
")",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"}",
"if",
"content_type",
"is",
"not",
"None",
":",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"content_type",
"if",
"content_md5",
"is",
"not",
"None",
":",
"headers",
"[",
"\"Content-MD5\"",
"]",
"=",
"content_md5",
"header_names",
"=",
"[",
"key",
".",
"lower",
"(",
")",
"for",
"key",
"in",
"headers",
"]",
"if",
"\"host\"",
"not",
"in",
"header_names",
":",
"headers",
"[",
"\"Host\"",
"]",
"=",
"\"storage.googleapis.com\"",
"if",
"method",
".",
"upper",
"(",
")",
"==",
"\"RESUMABLE\"",
":",
"method",
"=",
"\"POST\"",
"headers",
"[",
"\"x-goog-resumable\"",
"]",
"=",
"\"start\"",
"canonical_headers",
",",
"ordered_headers",
"=",
"get_canonical_headers",
"(",
"headers",
")",
"canonical_header_string",
"=",
"(",
"\"\\n\"",
".",
"join",
"(",
"canonical_headers",
")",
"+",
"\"\\n\"",
")",
"# Yes, Virginia, the extra newline is part of the spec.",
"signed_headers",
"=",
"\";\"",
".",
"join",
"(",
"[",
"key",
"for",
"key",
",",
"_",
"in",
"ordered_headers",
"]",
")",
"if",
"query_parameters",
"is",
"None",
":",
"query_parameters",
"=",
"{",
"}",
"else",
":",
"query_parameters",
"=",
"{",
"key",
":",
"value",
"or",
"\"\"",
"for",
"key",
",",
"value",
"in",
"query_parameters",
".",
"items",
"(",
")",
"}",
"query_parameters",
"[",
"\"X-Goog-Algorithm\"",
"]",
"=",
"\"GOOG4-RSA-SHA256\"",
"query_parameters",
"[",
"\"X-Goog-Credential\"",
"]",
"=",
"credential",
"query_parameters",
"[",
"\"X-Goog-Date\"",
"]",
"=",
"request_timestamp",
"query_parameters",
"[",
"\"X-Goog-Expires\"",
"]",
"=",
"expiration_seconds",
"query_parameters",
"[",
"\"X-Goog-SignedHeaders\"",
"]",
"=",
"signed_headers",
"if",
"response_type",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"\"response-content-type\"",
"]",
"=",
"response_type",
"if",
"response_disposition",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"\"response-content-disposition\"",
"]",
"=",
"response_disposition",
"if",
"generation",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"\"generation\"",
"]",
"=",
"generation",
"ordered_query_parameters",
"=",
"sorted",
"(",
"query_parameters",
".",
"items",
"(",
")",
")",
"canonical_query_string",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlencode",
"(",
"ordered_query_parameters",
")",
"canonical_elements",
"=",
"[",
"method",
",",
"resource",
",",
"canonical_query_string",
",",
"canonical_header_string",
",",
"signed_headers",
",",
"\"UNSIGNED-PAYLOAD\"",
",",
"]",
"canonical_request",
"=",
"\"\\n\"",
".",
"join",
"(",
"canonical_elements",
")",
"canonical_request_hash",
"=",
"hashlib",
".",
"sha256",
"(",
"canonical_request",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
".",
"hexdigest",
"(",
")",
"string_elements",
"=",
"[",
"\"GOOG4-RSA-SHA256\"",
",",
"request_timestamp",
",",
"credential_scope",
",",
"canonical_request_hash",
",",
"]",
"string_to_sign",
"=",
"\"\\n\"",
".",
"join",
"(",
"string_elements",
")",
"signature_bytes",
"=",
"credentials",
".",
"sign_bytes",
"(",
"string_to_sign",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
"signature",
"=",
"binascii",
".",
"hexlify",
"(",
"signature_bytes",
")",
".",
"decode",
"(",
"\"ascii\"",
")",
"return",
"\"{}{}?{}&X-Goog-Signature={}\"",
".",
"format",
"(",
"api_access_endpoint",
",",
"resource",
",",
"canonical_query_string",
",",
"signature",
")"
] | Generate a V4 signed URL to provide query-string auth'n to a resource.
.. note::
Assumes ``credentials`` implements the
:class:`google.auth.credentials.Signing` interface. Also assumes
``credentials`` has a ``service_account_email`` property which
identifies the credentials.
.. note::
If you are on Google Compute Engine, you can't generate a signed URL.
Follow `Issue 922`_ for updates on this. If you'd like to be able to
generate a signed URL from GCE, you can use a standard service account
from a JSON file rather than a GCE service account.
See headers `reference`_ for more details on optional arguments.
.. _Issue 922: https://github.com/GoogleCloudPlatform/\
google-cloud-python/issues/922
.. _reference: https://cloud.google.com/storage/docs/reference-headers
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: Credentials object with an associated private key to
sign text.
:type resource: str
:param resource: A pointer to a specific resource
(typically, ``/bucket-name/path/to/blob.txt``).
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:type api_access_endpoint: str
:param api_access_endpoint: Optional URI base. Defaults to
"https://storage.googleapis.com/"
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
signature will additionally contain the `x-goog-resumable`
header, and the method changed to POST. See the signed URL
docs regarding this flow:
https://cloud.google.com/storage/docs/access-control/signed-urls
:type content_md5: str
:param content_md5: (Optional) The MD5 hash of the object referenced by
``resource``.
:type content_type: str
:param content_type: (Optional) The content type of the object referenced
by ``resource``.
:type response_type: str
:param response_type: (Optional) Content type of responses to requests for
the signed URL. Used to over-ride the content type of
the underlying resource.
:type response_disposition: str
:param response_disposition: (Optional) Content disposition of responses to
requests for the signed URL.
:type generation: str
:param generation: (Optional) A value that indicates which generation of
the resource to fetch.
:type headers: dict
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
:rtype: str
:returns: A signed URL you can use to access the resource
until expiration. | [
"Generate",
"a",
"V4",
"signed",
"URL",
"to",
"provide",
"query",
"-",
"string",
"auth",
"n",
"to",
"a",
"resource",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_signing.py#L399-L591 |
28,362 | googleapis/google-cloud-python | translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py | TranslationServiceClient.glossary_path | def glossary_path(cls, project, location, glossary):
"""Return a fully-qualified glossary string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/glossaries/{glossary}",
project=project,
location=location,
glossary=glossary,
) | python | def glossary_path(cls, project, location, glossary):
"""Return a fully-qualified glossary string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/glossaries/{glossary}",
project=project,
location=location,
glossary=glossary,
) | [
"def",
"glossary_path",
"(",
"cls",
",",
"project",
",",
"location",
",",
"glossary",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/locations/{location}/glossaries/{glossary}\"",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
",",
"glossary",
"=",
"glossary",
",",
")"
] | Return a fully-qualified glossary string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"glossary",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L88-L95 |
28,363 | googleapis/google-cloud-python | translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py | TranslationServiceClient.translate_text | def translate_text(
self,
contents,
target_language_code,
mime_type=None,
source_language_code=None,
parent=None,
model=None,
glossary_config=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Translates input text and returns translated text.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> # TODO: Initialize `contents`:
>>> contents = []
>>>
>>> # TODO: Initialize `target_language_code`:
>>> target_language_code = ''
>>>
>>> response = client.translate_text(contents, target_language_code)
Args:
contents (list[str]): Required. The content of the input in string format.
We recommend the total contents to be less than 30k codepoints.
Please use BatchTranslateText for larger text.
target_language_code (str): Required. The BCP-47 language code to use for translation of the input
text, set to one of the language codes listed in Language Support.
mime_type (str): Optional. The format of the source text, for example, "text/html",
"text/plain". If left blank, the MIME type is assumed to be "text/html".
source_language_code (str): Optional. The BCP-47 language code of the input text if
known, for example, "en-US" or "sr-Latn". Supported language codes are
listed in Language Support. If the source language isn't specified, the API
attempts to identify the source language automatically and returns the
the source language within the response.
parent (str): Optional. Only used when making regionalized call.
Format:
projects/{project-id}/locations/{location-id}.
Only custom model/glossary within the same location-id can be used.
Otherwise 400 is returned.
model (str): Optional. The ``model`` type requested for this translation.
The format depends on model type:
1. Custom models:
projects/{project-id}/locations/{location-id}/models/{model-id}.
2. General (built-in) models:
projects/{project-id}/locations/{location-id}/models/general/nmt
projects/{project-id}/locations/{location-id}/models/general/base
For global (non-regionalized) requests, use {location-id} 'global'. For
example, projects/{project-id}/locations/global/models/general/nmt
If missing, the system decides which google base model to use.
glossary_config (Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]): Optional. Glossary to be applied. The glossary needs to be in the same
region as the model, otherwise an INVALID\_ARGUMENT error is returned.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig`
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.translate_v3beta1.types.TranslateTextResponse` 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 "translate_text" not in self._inner_api_calls:
self._inner_api_calls[
"translate_text"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.translate_text,
default_retry=self._method_configs["TranslateText"].retry,
default_timeout=self._method_configs["TranslateText"].timeout,
client_info=self._client_info,
)
request = translation_service_pb2.TranslateTextRequest(
contents=contents,
target_language_code=target_language_code,
mime_type=mime_type,
source_language_code=source_language_code,
parent=parent,
model=model,
glossary_config=glossary_config,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["translate_text"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def translate_text(
self,
contents,
target_language_code,
mime_type=None,
source_language_code=None,
parent=None,
model=None,
glossary_config=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Translates input text and returns translated text.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> # TODO: Initialize `contents`:
>>> contents = []
>>>
>>> # TODO: Initialize `target_language_code`:
>>> target_language_code = ''
>>>
>>> response = client.translate_text(contents, target_language_code)
Args:
contents (list[str]): Required. The content of the input in string format.
We recommend the total contents to be less than 30k codepoints.
Please use BatchTranslateText for larger text.
target_language_code (str): Required. The BCP-47 language code to use for translation of the input
text, set to one of the language codes listed in Language Support.
mime_type (str): Optional. The format of the source text, for example, "text/html",
"text/plain". If left blank, the MIME type is assumed to be "text/html".
source_language_code (str): Optional. The BCP-47 language code of the input text if
known, for example, "en-US" or "sr-Latn". Supported language codes are
listed in Language Support. If the source language isn't specified, the API
attempts to identify the source language automatically and returns the
the source language within the response.
parent (str): Optional. Only used when making regionalized call.
Format:
projects/{project-id}/locations/{location-id}.
Only custom model/glossary within the same location-id can be used.
Otherwise 400 is returned.
model (str): Optional. The ``model`` type requested for this translation.
The format depends on model type:
1. Custom models:
projects/{project-id}/locations/{location-id}/models/{model-id}.
2. General (built-in) models:
projects/{project-id}/locations/{location-id}/models/general/nmt
projects/{project-id}/locations/{location-id}/models/general/base
For global (non-regionalized) requests, use {location-id} 'global'. For
example, projects/{project-id}/locations/global/models/general/nmt
If missing, the system decides which google base model to use.
glossary_config (Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]): Optional. Glossary to be applied. The glossary needs to be in the same
region as the model, otherwise an INVALID\_ARGUMENT error is returned.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig`
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.translate_v3beta1.types.TranslateTextResponse` 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 "translate_text" not in self._inner_api_calls:
self._inner_api_calls[
"translate_text"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.translate_text,
default_retry=self._method_configs["TranslateText"].retry,
default_timeout=self._method_configs["TranslateText"].timeout,
client_info=self._client_info,
)
request = translation_service_pb2.TranslateTextRequest(
contents=contents,
target_language_code=target_language_code,
mime_type=mime_type,
source_language_code=source_language_code,
parent=parent,
model=model,
glossary_config=glossary_config,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["translate_text"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"translate_text",
"(",
"self",
",",
"contents",
",",
"target_language_code",
",",
"mime_type",
"=",
"None",
",",
"source_language_code",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"model",
"=",
"None",
",",
"glossary_config",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"translate_text\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"translate_text\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"translate_text",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"TranslateText\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"TranslateText\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"translation_service_pb2",
".",
"TranslateTextRequest",
"(",
"contents",
"=",
"contents",
",",
"target_language_code",
"=",
"target_language_code",
",",
"mime_type",
"=",
"mime_type",
",",
"source_language_code",
"=",
"source_language_code",
",",
"parent",
"=",
"parent",
",",
"model",
"=",
"model",
",",
"glossary_config",
"=",
"glossary_config",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"parent\"",
",",
"parent",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"translate_text\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Translates input text and returns translated text.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> # TODO: Initialize `contents`:
>>> contents = []
>>>
>>> # TODO: Initialize `target_language_code`:
>>> target_language_code = ''
>>>
>>> response = client.translate_text(contents, target_language_code)
Args:
contents (list[str]): Required. The content of the input in string format.
We recommend the total contents to be less than 30k codepoints.
Please use BatchTranslateText for larger text.
target_language_code (str): Required. The BCP-47 language code to use for translation of the input
text, set to one of the language codes listed in Language Support.
mime_type (str): Optional. The format of the source text, for example, "text/html",
"text/plain". If left blank, the MIME type is assumed to be "text/html".
source_language_code (str): Optional. The BCP-47 language code of the input text if
known, for example, "en-US" or "sr-Latn". Supported language codes are
listed in Language Support. If the source language isn't specified, the API
attempts to identify the source language automatically and returns the
the source language within the response.
parent (str): Optional. Only used when making regionalized call.
Format:
projects/{project-id}/locations/{location-id}.
Only custom model/glossary within the same location-id can be used.
Otherwise 400 is returned.
model (str): Optional. The ``model`` type requested for this translation.
The format depends on model type:
1. Custom models:
projects/{project-id}/locations/{location-id}/models/{model-id}.
2. General (built-in) models:
projects/{project-id}/locations/{location-id}/models/general/nmt
projects/{project-id}/locations/{location-id}/models/general/base
For global (non-regionalized) requests, use {location-id} 'global'. For
example, projects/{project-id}/locations/global/models/general/nmt
If missing, the system decides which google base model to use.
glossary_config (Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]): Optional. Glossary to be applied. The glossary needs to be in the same
region as the model, otherwise an INVALID\_ARGUMENT error is returned.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig`
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.translate_v3beta1.types.TranslateTextResponse` 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. | [
"Translates",
"input",
"text",
"and",
"returns",
"translated",
"text",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L196-L317 |
28,364 | googleapis/google-cloud-python | translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py | TranslationServiceClient.detect_language | def detect_language(
self,
parent=None,
model=None,
content=None,
mime_type=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Detects the language of text within a request.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> response = client.detect_language()
Args:
parent (str): Optional. Only used when making regionalized call.
Format:
projects/{project-id}/locations/{location-id}.
Only custom model within the same location-id can be used.
Otherwise 400 is returned.
model (str): Optional. The language detection model to be used.
projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}
If not specified, default will be used.
content (str): The content of the input stored as a string.
mime_type (str): Optional. The format of the source text, for example, "text/html",
"text/plain". If left blank, the MIME type is assumed to be "text/html".
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.translate_v3beta1.types.DetectLanguageResponse` 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 "detect_language" not in self._inner_api_calls:
self._inner_api_calls[
"detect_language"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.detect_language,
default_retry=self._method_configs["DetectLanguage"].retry,
default_timeout=self._method_configs["DetectLanguage"].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(content=content)
request = translation_service_pb2.DetectLanguageRequest(
parent=parent, model=model, content=content, mime_type=mime_type
)
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["detect_language"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def detect_language(
self,
parent=None,
model=None,
content=None,
mime_type=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Detects the language of text within a request.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> response = client.detect_language()
Args:
parent (str): Optional. Only used when making regionalized call.
Format:
projects/{project-id}/locations/{location-id}.
Only custom model within the same location-id can be used.
Otherwise 400 is returned.
model (str): Optional. The language detection model to be used.
projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}
If not specified, default will be used.
content (str): The content of the input stored as a string.
mime_type (str): Optional. The format of the source text, for example, "text/html",
"text/plain". If left blank, the MIME type is assumed to be "text/html".
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.translate_v3beta1.types.DetectLanguageResponse` 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 "detect_language" not in self._inner_api_calls:
self._inner_api_calls[
"detect_language"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.detect_language,
default_retry=self._method_configs["DetectLanguage"].retry,
default_timeout=self._method_configs["DetectLanguage"].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(content=content)
request = translation_service_pb2.DetectLanguageRequest(
parent=parent, model=model, content=content, mime_type=mime_type
)
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["detect_language"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"detect_language",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"model",
"=",
"None",
",",
"content",
"=",
"None",
",",
"mime_type",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"detect_language\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"detect_language\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"detect_language",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"DetectLanguage\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"DetectLanguage\"",
"]",
".",
"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",
"(",
"content",
"=",
"content",
")",
"request",
"=",
"translation_service_pb2",
".",
"DetectLanguageRequest",
"(",
"parent",
"=",
"parent",
",",
"model",
"=",
"model",
",",
"content",
"=",
"content",
",",
"mime_type",
"=",
"mime_type",
")",
"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",
"[",
"\"detect_language\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Detects the language of text within a request.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> response = client.detect_language()
Args:
parent (str): Optional. Only used when making regionalized call.
Format:
projects/{project-id}/locations/{location-id}.
Only custom model within the same location-id can be used.
Otherwise 400 is returned.
model (str): Optional. The language detection model to be used.
projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}
If not specified, default will be used.
content (str): The content of the input stored as a string.
mime_type (str): Optional. The format of the source text, for example, "text/html",
"text/plain". If left blank, the MIME type is assumed to be "text/html".
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.translate_v3beta1.types.DetectLanguageResponse` 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. | [
"Detects",
"the",
"language",
"of",
"text",
"within",
"a",
"request",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L319-L404 |
28,365 | googleapis/google-cloud-python | translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py | TranslationServiceClient.get_supported_languages | def get_supported_languages(
self,
parent=None,
display_language_code=None,
model=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Returns a list of supported languages for translation.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> response = client.get_supported_languages()
Args:
parent (str): Optional. Used for making regionalized calls.
Format: projects/{project-id}/locations/{location-id}.
For global calls, use projects/{project-id}/locations/global.
If missing, the call is treated as a global call.
Only custom model within the same location-id can be used.
Otherwise 400 is returned.
display_language_code (str): Optional. The language to use to return localized, human readable names
of supported languages. If missing, default language is ENGLISH.
model (str): Optional. Get supported languages of this model.
The format depends on model type:
1. Custom models:
projects/{project-id}/locations/{location-id}/models/{model-id}.
2. General (built-in) models:
projects/{project-id}/locations/{location-id}/models/general/nmt
projects/{project-id}/locations/{location-id}/models/general/base
Returns languages supported by the specified model.
If missing, we get supported languages of Google general NMT model.
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.translate_v3beta1.types.SupportedLanguages` 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_supported_languages" not in self._inner_api_calls:
self._inner_api_calls[
"get_supported_languages"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_supported_languages,
default_retry=self._method_configs["GetSupportedLanguages"].retry,
default_timeout=self._method_configs["GetSupportedLanguages"].timeout,
client_info=self._client_info,
)
request = translation_service_pb2.GetSupportedLanguagesRequest(
parent=parent, display_language_code=display_language_code, model=model
)
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["get_supported_languages"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def get_supported_languages(
self,
parent=None,
display_language_code=None,
model=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Returns a list of supported languages for translation.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> response = client.get_supported_languages()
Args:
parent (str): Optional. Used for making regionalized calls.
Format: projects/{project-id}/locations/{location-id}.
For global calls, use projects/{project-id}/locations/global.
If missing, the call is treated as a global call.
Only custom model within the same location-id can be used.
Otherwise 400 is returned.
display_language_code (str): Optional. The language to use to return localized, human readable names
of supported languages. If missing, default language is ENGLISH.
model (str): Optional. Get supported languages of this model.
The format depends on model type:
1. Custom models:
projects/{project-id}/locations/{location-id}/models/{model-id}.
2. General (built-in) models:
projects/{project-id}/locations/{location-id}/models/general/nmt
projects/{project-id}/locations/{location-id}/models/general/base
Returns languages supported by the specified model.
If missing, we get supported languages of Google general NMT model.
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.translate_v3beta1.types.SupportedLanguages` 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_supported_languages" not in self._inner_api_calls:
self._inner_api_calls[
"get_supported_languages"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_supported_languages,
default_retry=self._method_configs["GetSupportedLanguages"].retry,
default_timeout=self._method_configs["GetSupportedLanguages"].timeout,
client_info=self._client_info,
)
request = translation_service_pb2.GetSupportedLanguagesRequest(
parent=parent, display_language_code=display_language_code, model=model
)
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["get_supported_languages"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"get_supported_languages",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"display_language_code",
"=",
"None",
",",
"model",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"get_supported_languages\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"get_supported_languages\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"get_supported_languages",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"GetSupportedLanguages\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"GetSupportedLanguages\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"translation_service_pb2",
".",
"GetSupportedLanguagesRequest",
"(",
"parent",
"=",
"parent",
",",
"display_language_code",
"=",
"display_language_code",
",",
"model",
"=",
"model",
")",
"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",
"[",
"\"get_supported_languages\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Returns a list of supported languages for translation.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> response = client.get_supported_languages()
Args:
parent (str): Optional. Used for making regionalized calls.
Format: projects/{project-id}/locations/{location-id}.
For global calls, use projects/{project-id}/locations/global.
If missing, the call is treated as a global call.
Only custom model within the same location-id can be used.
Otherwise 400 is returned.
display_language_code (str): Optional. The language to use to return localized, human readable names
of supported languages. If missing, default language is ENGLISH.
model (str): Optional. Get supported languages of this model.
The format depends on model type:
1. Custom models:
projects/{project-id}/locations/{location-id}/models/{model-id}.
2. General (built-in) models:
projects/{project-id}/locations/{location-id}/models/general/nmt
projects/{project-id}/locations/{location-id}/models/general/base
Returns languages supported by the specified model.
If missing, we get supported languages of Google general NMT model.
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.translate_v3beta1.types.SupportedLanguages` 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. | [
"Returns",
"a",
"list",
"of",
"supported",
"languages",
"for",
"translation",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L406-L492 |
28,366 | googleapis/google-cloud-python | translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py | TranslationServiceClient.create_glossary | def create_glossary(
self,
parent,
glossary,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a glossary and returns the long-running operation. Returns
NOT\_FOUND, if the project doesn't exist.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `glossary`:
>>> glossary = {}
>>>
>>> response = client.create_glossary(parent, glossary)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Required. The project name.
glossary (Union[dict, ~google.cloud.translate_v3beta1.types.Glossary]): Required. The glossary to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.translate_v3beta1.types.Glossary`
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.translate_v3beta1.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_glossary" not in self._inner_api_calls:
self._inner_api_calls[
"create_glossary"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_glossary,
default_retry=self._method_configs["CreateGlossary"].retry,
default_timeout=self._method_configs["CreateGlossary"].timeout,
client_info=self._client_info,
)
request = translation_service_pb2.CreateGlossaryRequest(
parent=parent, glossary=glossary
)
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_glossary"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
translation_service_pb2.Glossary,
metadata_type=translation_service_pb2.CreateGlossaryMetadata,
) | python | def create_glossary(
self,
parent,
glossary,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a glossary and returns the long-running operation. Returns
NOT\_FOUND, if the project doesn't exist.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `glossary`:
>>> glossary = {}
>>>
>>> response = client.create_glossary(parent, glossary)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Required. The project name.
glossary (Union[dict, ~google.cloud.translate_v3beta1.types.Glossary]): Required. The glossary to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.translate_v3beta1.types.Glossary`
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.translate_v3beta1.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_glossary" not in self._inner_api_calls:
self._inner_api_calls[
"create_glossary"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_glossary,
default_retry=self._method_configs["CreateGlossary"].retry,
default_timeout=self._method_configs["CreateGlossary"].timeout,
client_info=self._client_info,
)
request = translation_service_pb2.CreateGlossaryRequest(
parent=parent, glossary=glossary
)
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_glossary"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
translation_service_pb2.Glossary,
metadata_type=translation_service_pb2.CreateGlossaryMetadata,
) | [
"def",
"create_glossary",
"(",
"self",
",",
"parent",
",",
"glossary",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"create_glossary\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"create_glossary\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_glossary",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateGlossary\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateGlossary\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"translation_service_pb2",
".",
"CreateGlossaryRequest",
"(",
"parent",
"=",
"parent",
",",
"glossary",
"=",
"glossary",
")",
"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_glossary\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")",
"return",
"google",
".",
"api_core",
".",
"operation",
".",
"from_gapic",
"(",
"operation",
",",
"self",
".",
"transport",
".",
"_operations_client",
",",
"translation_service_pb2",
".",
"Glossary",
",",
"metadata_type",
"=",
"translation_service_pb2",
".",
"CreateGlossaryMetadata",
",",
")"
] | Creates a glossary and returns the long-running operation. Returns
NOT\_FOUND, if the project doesn't exist.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `glossary`:
>>> glossary = {}
>>>
>>> response = client.create_glossary(parent, glossary)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Required. The project name.
glossary (Union[dict, ~google.cloud.translate_v3beta1.types.Glossary]): Required. The glossary to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.translate_v3beta1.types.Glossary`
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.translate_v3beta1.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. | [
"Creates",
"a",
"glossary",
"and",
"returns",
"the",
"long",
"-",
"running",
"operation",
".",
"Returns",
"NOT",
"\\",
"_FOUND",
"if",
"the",
"project",
"doesn",
"t",
"exist",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L646-L739 |
28,367 | googleapis/google-cloud-python | translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py | TranslationServiceClient.delete_glossary | def delete_glossary(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a glossary, or cancels glossary construction if the glossary
isn't created yet. Returns NOT\_FOUND, if the glossary doesn't exist.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> name = client.glossary_path('[PROJECT]', '[LOCATION]', '[GLOSSARY]')
>>>
>>> response = client.delete_glossary(name)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
name (str): Required. The name of the glossary to delete.
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.translate_v3beta1.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 "delete_glossary" not in self._inner_api_calls:
self._inner_api_calls[
"delete_glossary"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.delete_glossary,
default_retry=self._method_configs["DeleteGlossary"].retry,
default_timeout=self._method_configs["DeleteGlossary"].timeout,
client_info=self._client_info,
)
request = translation_service_pb2.DeleteGlossaryRequest(name=name)
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["delete_glossary"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
translation_service_pb2.DeleteGlossaryResponse,
metadata_type=translation_service_pb2.DeleteGlossaryMetadata,
) | python | def delete_glossary(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a glossary, or cancels glossary construction if the glossary
isn't created yet. Returns NOT\_FOUND, if the glossary doesn't exist.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> name = client.glossary_path('[PROJECT]', '[LOCATION]', '[GLOSSARY]')
>>>
>>> response = client.delete_glossary(name)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
name (str): Required. The name of the glossary to delete.
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.translate_v3beta1.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 "delete_glossary" not in self._inner_api_calls:
self._inner_api_calls[
"delete_glossary"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.delete_glossary,
default_retry=self._method_configs["DeleteGlossary"].retry,
default_timeout=self._method_configs["DeleteGlossary"].timeout,
client_info=self._client_info,
)
request = translation_service_pb2.DeleteGlossaryRequest(name=name)
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["delete_glossary"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
translation_service_pb2.DeleteGlossaryResponse,
metadata_type=translation_service_pb2.DeleteGlossaryMetadata,
) | [
"def",
"delete_glossary",
"(",
"self",
",",
"name",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"delete_glossary\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"delete_glossary\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"delete_glossary",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"DeleteGlossary\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"DeleteGlossary\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"translation_service_pb2",
".",
"DeleteGlossaryRequest",
"(",
"name",
"=",
"name",
")",
"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",
"[",
"\"delete_glossary\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")",
"return",
"google",
".",
"api_core",
".",
"operation",
".",
"from_gapic",
"(",
"operation",
",",
"self",
".",
"transport",
".",
"_operations_client",
",",
"translation_service_pb2",
".",
"DeleteGlossaryResponse",
",",
"metadata_type",
"=",
"translation_service_pb2",
".",
"DeleteGlossaryMetadata",
",",
")"
] | Deletes a glossary, or cancels glossary construction if the glossary
isn't created yet. Returns NOT\_FOUND, if the glossary doesn't exist.
Example:
>>> from google.cloud import translate_v3beta1
>>>
>>> client = translate_v3beta1.TranslationServiceClient()
>>>
>>> name = client.glossary_path('[PROJECT]', '[LOCATION]', '[GLOSSARY]')
>>>
>>> response = client.delete_glossary(name)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
name (str): Required. The name of the glossary to delete.
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.translate_v3beta1.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. | [
"Deletes",
"a",
"glossary",
"or",
"cancels",
"glossary",
"construction",
"if",
"the",
"glossary",
"isn",
"t",
"created",
"yet",
".",
"Returns",
"NOT",
"\\",
"_FOUND",
"if",
"the",
"glossary",
"doesn",
"t",
"exist",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L916-L999 |
28,368 | googleapis/google-cloud-python | monitoring/google/cloud/monitoring_v3/_dataframe.py | _extract_header | def _extract_header(time_series):
"""Return a copy of time_series with the points removed."""
return TimeSeries(
metric=time_series.metric,
resource=time_series.resource,
metric_kind=time_series.metric_kind,
value_type=time_series.value_type,
) | python | def _extract_header(time_series):
"""Return a copy of time_series with the points removed."""
return TimeSeries(
metric=time_series.metric,
resource=time_series.resource,
metric_kind=time_series.metric_kind,
value_type=time_series.value_type,
) | [
"def",
"_extract_header",
"(",
"time_series",
")",
":",
"return",
"TimeSeries",
"(",
"metric",
"=",
"time_series",
".",
"metric",
",",
"resource",
"=",
"time_series",
".",
"resource",
",",
"metric_kind",
"=",
"time_series",
".",
"metric_kind",
",",
"value_type",
"=",
"time_series",
".",
"value_type",
",",
")"
] | Return a copy of time_series with the points removed. | [
"Return",
"a",
"copy",
"of",
"time_series",
"with",
"the",
"points",
"removed",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/_dataframe.py#L29-L36 |
28,369 | googleapis/google-cloud-python | monitoring/google/cloud/monitoring_v3/_dataframe.py | _extract_labels | def _extract_labels(time_series):
"""Build the combined resource and metric labels, with resource_type."""
labels = {"resource_type": time_series.resource.type}
labels.update(time_series.resource.labels)
labels.update(time_series.metric.labels)
return labels | python | def _extract_labels(time_series):
"""Build the combined resource and metric labels, with resource_type."""
labels = {"resource_type": time_series.resource.type}
labels.update(time_series.resource.labels)
labels.update(time_series.metric.labels)
return labels | [
"def",
"_extract_labels",
"(",
"time_series",
")",
":",
"labels",
"=",
"{",
"\"resource_type\"",
":",
"time_series",
".",
"resource",
".",
"type",
"}",
"labels",
".",
"update",
"(",
"time_series",
".",
"resource",
".",
"labels",
")",
"labels",
".",
"update",
"(",
"time_series",
".",
"metric",
".",
"labels",
")",
"return",
"labels"
] | Build the combined resource and metric labels, with resource_type. | [
"Build",
"the",
"combined",
"resource",
"and",
"metric",
"labels",
"with",
"resource_type",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/_dataframe.py#L39-L44 |
28,370 | googleapis/google-cloud-python | monitoring/google/cloud/monitoring_v3/_dataframe.py | _sorted_resource_labels | def _sorted_resource_labels(labels):
"""Sort label names, putting well-known resource labels first."""
head = [label for label in TOP_RESOURCE_LABELS if label in labels]
tail = sorted(label for label in labels if label not in TOP_RESOURCE_LABELS)
return head + tail | python | def _sorted_resource_labels(labels):
"""Sort label names, putting well-known resource labels first."""
head = [label for label in TOP_RESOURCE_LABELS if label in labels]
tail = sorted(label for label in labels if label not in TOP_RESOURCE_LABELS)
return head + tail | [
"def",
"_sorted_resource_labels",
"(",
"labels",
")",
":",
"head",
"=",
"[",
"label",
"for",
"label",
"in",
"TOP_RESOURCE_LABELS",
"if",
"label",
"in",
"labels",
"]",
"tail",
"=",
"sorted",
"(",
"label",
"for",
"label",
"in",
"labels",
"if",
"label",
"not",
"in",
"TOP_RESOURCE_LABELS",
")",
"return",
"head",
"+",
"tail"
] | Sort label names, putting well-known resource labels first. | [
"Sort",
"label",
"names",
"putting",
"well",
"-",
"known",
"resource",
"labels",
"first",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/_dataframe.py#L143-L147 |
28,371 | googleapis/google-cloud-python | api_core/google/api_core/future/_helpers.py | start_daemon_thread | def start_daemon_thread(*args, **kwargs):
"""Starts a thread and marks it as a daemon thread."""
thread = threading.Thread(*args, **kwargs)
thread.daemon = True
thread.start()
return thread | python | def start_daemon_thread(*args, **kwargs):
"""Starts a thread and marks it as a daemon thread."""
thread = threading.Thread(*args, **kwargs)
thread.daemon = True
thread.start()
return thread | [
"def",
"start_daemon_thread",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"thread",
".",
"daemon",
"=",
"True",
"thread",
".",
"start",
"(",
")",
"return",
"thread"
] | Starts a thread and marks it as a daemon thread. | [
"Starts",
"a",
"thread",
"and",
"marks",
"it",
"as",
"a",
"daemon",
"thread",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/future/_helpers.py#L24-L29 |
28,372 | googleapis/google-cloud-python | api_core/google/api_core/future/_helpers.py | safe_invoke_callback | def safe_invoke_callback(callback, *args, **kwargs):
"""Invoke a callback, swallowing and logging any exceptions."""
# pylint: disable=bare-except
# We intentionally want to swallow all exceptions.
try:
return callback(*args, **kwargs)
except Exception:
_LOGGER.exception("Error while executing Future callback.") | python | def safe_invoke_callback(callback, *args, **kwargs):
"""Invoke a callback, swallowing and logging any exceptions."""
# pylint: disable=bare-except
# We intentionally want to swallow all exceptions.
try:
return callback(*args, **kwargs)
except Exception:
_LOGGER.exception("Error while executing Future callback.") | [
"def",
"safe_invoke_callback",
"(",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=bare-except",
"# We intentionally want to swallow all exceptions.",
"try",
":",
"return",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"_LOGGER",
".",
"exception",
"(",
"\"Error while executing Future callback.\"",
")"
] | Invoke a callback, swallowing and logging any exceptions. | [
"Invoke",
"a",
"callback",
"swallowing",
"and",
"logging",
"any",
"exceptions",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/future/_helpers.py#L32-L39 |
28,373 | googleapis/google-cloud-python | resource_manager/google/cloud/resource_manager/client.py | Client.new_project | def new_project(self, project_id, name=None, labels=None):
"""Create a project bound to the current client.
Use :meth:`Project.reload() \
<google.cloud.resource_manager.project.Project.reload>` to retrieve
project metadata after creating a
:class:`~google.cloud.resource_manager.project.Project` instance.
.. note:
This does not make an API call.
:type project_id: str
:param project_id: The ID for this project.
:type name: str
:param name: The display name of the project.
:type labels: dict
:param labels: A list of labels associated with the project.
:rtype: :class:`~google.cloud.resource_manager.project.Project`
:returns: A new instance of a
:class:`~google.cloud.resource_manager.project.Project`
**without** any metadata loaded.
"""
return Project(project_id=project_id, client=self, name=name, labels=labels) | python | def new_project(self, project_id, name=None, labels=None):
"""Create a project bound to the current client.
Use :meth:`Project.reload() \
<google.cloud.resource_manager.project.Project.reload>` to retrieve
project metadata after creating a
:class:`~google.cloud.resource_manager.project.Project` instance.
.. note:
This does not make an API call.
:type project_id: str
:param project_id: The ID for this project.
:type name: str
:param name: The display name of the project.
:type labels: dict
:param labels: A list of labels associated with the project.
:rtype: :class:`~google.cloud.resource_manager.project.Project`
:returns: A new instance of a
:class:`~google.cloud.resource_manager.project.Project`
**without** any metadata loaded.
"""
return Project(project_id=project_id, client=self, name=name, labels=labels) | [
"def",
"new_project",
"(",
"self",
",",
"project_id",
",",
"name",
"=",
"None",
",",
"labels",
"=",
"None",
")",
":",
"return",
"Project",
"(",
"project_id",
"=",
"project_id",
",",
"client",
"=",
"self",
",",
"name",
"=",
"name",
",",
"labels",
"=",
"labels",
")"
] | Create a project bound to the current client.
Use :meth:`Project.reload() \
<google.cloud.resource_manager.project.Project.reload>` to retrieve
project metadata after creating a
:class:`~google.cloud.resource_manager.project.Project` instance.
.. note:
This does not make an API call.
:type project_id: str
:param project_id: The ID for this project.
:type name: str
:param name: The display name of the project.
:type labels: dict
:param labels: A list of labels associated with the project.
:rtype: :class:`~google.cloud.resource_manager.project.Project`
:returns: A new instance of a
:class:`~google.cloud.resource_manager.project.Project`
**without** any metadata loaded. | [
"Create",
"a",
"project",
"bound",
"to",
"the",
"current",
"client",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/resource_manager/google/cloud/resource_manager/client.py#L61-L87 |
28,374 | googleapis/google-cloud-python | resource_manager/google/cloud/resource_manager/client.py | Client.fetch_project | def fetch_project(self, project_id):
"""Fetch an existing project and it's relevant metadata by ID.
.. note::
If the project does not exist, this will raise a
:class:`NotFound <google.cloud.exceptions.NotFound>` error.
:type project_id: str
:param project_id: The ID for this project.
:rtype: :class:`~google.cloud.resource_manager.project.Project`
:returns: A :class:`~google.cloud.resource_manager.project.Project`
with metadata fetched from the API.
"""
project = self.new_project(project_id)
project.reload()
return project | python | def fetch_project(self, project_id):
"""Fetch an existing project and it's relevant metadata by ID.
.. note::
If the project does not exist, this will raise a
:class:`NotFound <google.cloud.exceptions.NotFound>` error.
:type project_id: str
:param project_id: The ID for this project.
:rtype: :class:`~google.cloud.resource_manager.project.Project`
:returns: A :class:`~google.cloud.resource_manager.project.Project`
with metadata fetched from the API.
"""
project = self.new_project(project_id)
project.reload()
return project | [
"def",
"fetch_project",
"(",
"self",
",",
"project_id",
")",
":",
"project",
"=",
"self",
".",
"new_project",
"(",
"project_id",
")",
"project",
".",
"reload",
"(",
")",
"return",
"project"
] | Fetch an existing project and it's relevant metadata by ID.
.. note::
If the project does not exist, this will raise a
:class:`NotFound <google.cloud.exceptions.NotFound>` error.
:type project_id: str
:param project_id: The ID for this project.
:rtype: :class:`~google.cloud.resource_manager.project.Project`
:returns: A :class:`~google.cloud.resource_manager.project.Project`
with metadata fetched from the API. | [
"Fetch",
"an",
"existing",
"project",
"and",
"it",
"s",
"relevant",
"metadata",
"by",
"ID",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/resource_manager/google/cloud/resource_manager/client.py#L89-L106 |
28,375 | googleapis/google-cloud-python | resource_manager/google/cloud/resource_manager/client.py | Client.list_projects | def list_projects(self, filter_params=None, page_size=None):
"""List the projects visible to this client.
Example::
>>> from google.cloud import resource_manager
>>> client = resource_manager.Client()
>>> for project in client.list_projects():
... print(project.project_id)
List all projects with label ``'environment'`` set to ``'prod'``
(filtering by labels)::
>>> from google.cloud import resource_manager
>>> client = resource_manager.Client()
>>> env_filter = {'labels.environment': 'prod'}
>>> for project in client.list_projects(env_filter):
... print(project.project_id)
See
https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/list
Complete filtering example::
>>> project_filter = { # Return projects with...
... 'name': 'My Project', # name set to 'My Project'.
... 'id': 'my-project-id', # id set to 'my-project-id'.
... 'labels.stage': 'prod', # the label 'stage' set to 'prod'
... 'labels.color': '*' # a label 'color' set to anything.
... }
>>> client.list_projects(project_filter)
:type filter_params: dict
:param filter_params: (Optional) A dictionary of filter options where
each key is a property to filter on, and each
value is the (case-insensitive) value to check
(or the glob ``*`` to check for existence of the
property). See the example above for more
details.
:type page_size: int
:param page_size: (Optional) The maximum number of projects in each
page of results from this request. Non-positive
values are ignored. Defaults to a sensible value
set by the API.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of all
:class:`~google.cloud.resource_manager.project.Project`.
that the current user has access to.
"""
extra_params = {}
if page_size is not None:
extra_params["pageSize"] = page_size
if filter_params is not None:
extra_params["filter"] = [
"{}:{}".format(key, value)
for key, value in six.iteritems(filter_params)
]
return page_iterator.HTTPIterator(
client=self,
api_request=self._connection.api_request,
path="/projects",
item_to_value=_item_to_project,
items_key="projects",
extra_params=extra_params,
) | python | def list_projects(self, filter_params=None, page_size=None):
"""List the projects visible to this client.
Example::
>>> from google.cloud import resource_manager
>>> client = resource_manager.Client()
>>> for project in client.list_projects():
... print(project.project_id)
List all projects with label ``'environment'`` set to ``'prod'``
(filtering by labels)::
>>> from google.cloud import resource_manager
>>> client = resource_manager.Client()
>>> env_filter = {'labels.environment': 'prod'}
>>> for project in client.list_projects(env_filter):
... print(project.project_id)
See
https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/list
Complete filtering example::
>>> project_filter = { # Return projects with...
... 'name': 'My Project', # name set to 'My Project'.
... 'id': 'my-project-id', # id set to 'my-project-id'.
... 'labels.stage': 'prod', # the label 'stage' set to 'prod'
... 'labels.color': '*' # a label 'color' set to anything.
... }
>>> client.list_projects(project_filter)
:type filter_params: dict
:param filter_params: (Optional) A dictionary of filter options where
each key is a property to filter on, and each
value is the (case-insensitive) value to check
(or the glob ``*`` to check for existence of the
property). See the example above for more
details.
:type page_size: int
:param page_size: (Optional) The maximum number of projects in each
page of results from this request. Non-positive
values are ignored. Defaults to a sensible value
set by the API.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of all
:class:`~google.cloud.resource_manager.project.Project`.
that the current user has access to.
"""
extra_params = {}
if page_size is not None:
extra_params["pageSize"] = page_size
if filter_params is not None:
extra_params["filter"] = [
"{}:{}".format(key, value)
for key, value in six.iteritems(filter_params)
]
return page_iterator.HTTPIterator(
client=self,
api_request=self._connection.api_request,
path="/projects",
item_to_value=_item_to_project,
items_key="projects",
extra_params=extra_params,
) | [
"def",
"list_projects",
"(",
"self",
",",
"filter_params",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"extra_params",
"=",
"{",
"}",
"if",
"page_size",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"pageSize\"",
"]",
"=",
"page_size",
"if",
"filter_params",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"filter\"",
"]",
"=",
"[",
"\"{}:{}\"",
".",
"format",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"filter_params",
")",
"]",
"return",
"page_iterator",
".",
"HTTPIterator",
"(",
"client",
"=",
"self",
",",
"api_request",
"=",
"self",
".",
"_connection",
".",
"api_request",
",",
"path",
"=",
"\"/projects\"",
",",
"item_to_value",
"=",
"_item_to_project",
",",
"items_key",
"=",
"\"projects\"",
",",
"extra_params",
"=",
"extra_params",
",",
")"
] | List the projects visible to this client.
Example::
>>> from google.cloud import resource_manager
>>> client = resource_manager.Client()
>>> for project in client.list_projects():
... print(project.project_id)
List all projects with label ``'environment'`` set to ``'prod'``
(filtering by labels)::
>>> from google.cloud import resource_manager
>>> client = resource_manager.Client()
>>> env_filter = {'labels.environment': 'prod'}
>>> for project in client.list_projects(env_filter):
... print(project.project_id)
See
https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/list
Complete filtering example::
>>> project_filter = { # Return projects with...
... 'name': 'My Project', # name set to 'My Project'.
... 'id': 'my-project-id', # id set to 'my-project-id'.
... 'labels.stage': 'prod', # the label 'stage' set to 'prod'
... 'labels.color': '*' # a label 'color' set to anything.
... }
>>> client.list_projects(project_filter)
:type filter_params: dict
:param filter_params: (Optional) A dictionary of filter options where
each key is a property to filter on, and each
value is the (case-insensitive) value to check
(or the glob ``*`` to check for existence of the
property). See the example above for more
details.
:type page_size: int
:param page_size: (Optional) The maximum number of projects in each
page of results from this request. Non-positive
values are ignored. Defaults to a sensible value
set by the API.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of all
:class:`~google.cloud.resource_manager.project.Project`.
that the current user has access to. | [
"List",
"the",
"projects",
"visible",
"to",
"this",
"client",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/resource_manager/google/cloud/resource_manager/client.py#L108-L177 |
28,376 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/gapic/spanner_client.py | SpannerClient.execute_streaming_sql | def execute_streaming_sql(
self,
session,
sql,
transaction=None,
params=None,
param_types=None,
resume_token=None,
query_mode=None,
partition_token=None,
seqno=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Like ``ExecuteSql``, except returns the result set as a stream. Unlike
``ExecuteSql``, there is no limit on the size of the returned result
set. However, no individual row in the result set can exceed 100 MiB,
and no column value can exceed 10 MiB.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `sql`:
>>> sql = ''
>>>
>>> for element in client.execute_streaming_sql(session, sql):
... # process element
... pass
Args:
session (str): Required. The session in which the SQL query should be performed.
sql (str): Required. The SQL string.
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a
temporary read-only transaction with strong concurrency.
The transaction to use.
For queries, if none is provided, the default is a temporary read-only
transaction with strong concurrency.
Standard DML statements require a ReadWrite transaction. Single-use
transactions are not supported (to avoid replay). The caller must
either supply an existing transaction ID or begin a new transaction.
Partitioned DML requires an existing PartitionedDml transaction ID.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL string can contain parameter placeholders. A parameter
placeholder consists of ``'@'`` followed by the parameter name.
Parameter names consist of any combination of letters, numbers, and
underscores.
Parameters can appear anywhere that a literal value is expected. The
same parameter name can be used more than once, for example:
``"WHERE id > @msg_id AND id < @msg_id + 100"``
It is an error to execute an SQL statement with unbound parameters.
Parameter values are specified using ``params``, which is a JSON object
whose keys are parameter names, and whose values are the corresponding
parameter values.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Struct`
param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type
from a JSON value. For example, values of type ``BYTES`` and values of
type ``STRING`` both appear in ``params`` as JSON strings.
In these cases, ``param_types`` can be used to specify the exact SQL
type for some or all of the SQL statement parameters. See the definition
of ``Type`` for more information about SQL types.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Type`
resume_token (bytes): If this request is resuming a previously interrupted SQL statement
execution, ``resume_token`` should be copied from the last
``PartialResultSet`` yielded before the interruption. Doing this enables
the new SQL statement execution to resume where the last one left off.
The rest of the request parameters must exactly match the request that
yielded this token.
query_mode (~google.cloud.spanner_v1.types.QueryMode): Used to control the amount of debugging information returned in
``ResultSetStats``. If ``partition_token`` is set, ``query_mode`` can
only be set to ``QueryMode.NORMAL``.
partition_token (bytes): If present, results will be restricted to the specified partition
previously created using PartitionQuery(). There must be an exact match
for the values of fields common to this message and the
PartitionQueryRequest message used to create this partition\_token.
seqno (long): A per-transaction sequence number used to identify this request. This
makes each request idempotent such that if the request is received multiple
times, at most one will succeed.
The sequence number must be monotonically increasing within the
transaction. If a request arrives for the first time with an out-of-order
sequence number, the transaction may be aborted. Replays of previously
handled requests will yield the same response as the first execution.
Required for DML statements. Ignored for queries.
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:
Iterable[~google.cloud.spanner_v1.types.PartialResultSet].
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 "execute_streaming_sql" not in self._inner_api_calls:
self._inner_api_calls[
"execute_streaming_sql"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.execute_streaming_sql,
default_retry=self._method_configs["ExecuteStreamingSql"].retry,
default_timeout=self._method_configs["ExecuteStreamingSql"].timeout,
client_info=self._client_info,
)
request = spanner_pb2.ExecuteSqlRequest(
session=session,
sql=sql,
transaction=transaction,
params=params,
param_types=param_types,
resume_token=resume_token,
query_mode=query_mode,
partition_token=partition_token,
seqno=seqno,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session", session)]
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["execute_streaming_sql"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def execute_streaming_sql(
self,
session,
sql,
transaction=None,
params=None,
param_types=None,
resume_token=None,
query_mode=None,
partition_token=None,
seqno=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Like ``ExecuteSql``, except returns the result set as a stream. Unlike
``ExecuteSql``, there is no limit on the size of the returned result
set. However, no individual row in the result set can exceed 100 MiB,
and no column value can exceed 10 MiB.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `sql`:
>>> sql = ''
>>>
>>> for element in client.execute_streaming_sql(session, sql):
... # process element
... pass
Args:
session (str): Required. The session in which the SQL query should be performed.
sql (str): Required. The SQL string.
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a
temporary read-only transaction with strong concurrency.
The transaction to use.
For queries, if none is provided, the default is a temporary read-only
transaction with strong concurrency.
Standard DML statements require a ReadWrite transaction. Single-use
transactions are not supported (to avoid replay). The caller must
either supply an existing transaction ID or begin a new transaction.
Partitioned DML requires an existing PartitionedDml transaction ID.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL string can contain parameter placeholders. A parameter
placeholder consists of ``'@'`` followed by the parameter name.
Parameter names consist of any combination of letters, numbers, and
underscores.
Parameters can appear anywhere that a literal value is expected. The
same parameter name can be used more than once, for example:
``"WHERE id > @msg_id AND id < @msg_id + 100"``
It is an error to execute an SQL statement with unbound parameters.
Parameter values are specified using ``params``, which is a JSON object
whose keys are parameter names, and whose values are the corresponding
parameter values.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Struct`
param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type
from a JSON value. For example, values of type ``BYTES`` and values of
type ``STRING`` both appear in ``params`` as JSON strings.
In these cases, ``param_types`` can be used to specify the exact SQL
type for some or all of the SQL statement parameters. See the definition
of ``Type`` for more information about SQL types.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Type`
resume_token (bytes): If this request is resuming a previously interrupted SQL statement
execution, ``resume_token`` should be copied from the last
``PartialResultSet`` yielded before the interruption. Doing this enables
the new SQL statement execution to resume where the last one left off.
The rest of the request parameters must exactly match the request that
yielded this token.
query_mode (~google.cloud.spanner_v1.types.QueryMode): Used to control the amount of debugging information returned in
``ResultSetStats``. If ``partition_token`` is set, ``query_mode`` can
only be set to ``QueryMode.NORMAL``.
partition_token (bytes): If present, results will be restricted to the specified partition
previously created using PartitionQuery(). There must be an exact match
for the values of fields common to this message and the
PartitionQueryRequest message used to create this partition\_token.
seqno (long): A per-transaction sequence number used to identify this request. This
makes each request idempotent such that if the request is received multiple
times, at most one will succeed.
The sequence number must be monotonically increasing within the
transaction. If a request arrives for the first time with an out-of-order
sequence number, the transaction may be aborted. Replays of previously
handled requests will yield the same response as the first execution.
Required for DML statements. Ignored for queries.
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:
Iterable[~google.cloud.spanner_v1.types.PartialResultSet].
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 "execute_streaming_sql" not in self._inner_api_calls:
self._inner_api_calls[
"execute_streaming_sql"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.execute_streaming_sql,
default_retry=self._method_configs["ExecuteStreamingSql"].retry,
default_timeout=self._method_configs["ExecuteStreamingSql"].timeout,
client_info=self._client_info,
)
request = spanner_pb2.ExecuteSqlRequest(
session=session,
sql=sql,
transaction=transaction,
params=params,
param_types=param_types,
resume_token=resume_token,
query_mode=query_mode,
partition_token=partition_token,
seqno=seqno,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session", session)]
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["execute_streaming_sql"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"execute_streaming_sql",
"(",
"self",
",",
"session",
",",
"sql",
",",
"transaction",
"=",
"None",
",",
"params",
"=",
"None",
",",
"param_types",
"=",
"None",
",",
"resume_token",
"=",
"None",
",",
"query_mode",
"=",
"None",
",",
"partition_token",
"=",
"None",
",",
"seqno",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"execute_streaming_sql\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"execute_streaming_sql\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"execute_streaming_sql",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"ExecuteStreamingSql\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"ExecuteStreamingSql\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"spanner_pb2",
".",
"ExecuteSqlRequest",
"(",
"session",
"=",
"session",
",",
"sql",
"=",
"sql",
",",
"transaction",
"=",
"transaction",
",",
"params",
"=",
"params",
",",
"param_types",
"=",
"param_types",
",",
"resume_token",
"=",
"resume_token",
",",
"query_mode",
"=",
"query_mode",
",",
"partition_token",
"=",
"partition_token",
",",
"seqno",
"=",
"seqno",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"session\"",
",",
"session",
")",
"]",
"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",
"[",
"\"execute_streaming_sql\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Like ``ExecuteSql``, except returns the result set as a stream. Unlike
``ExecuteSql``, there is no limit on the size of the returned result
set. However, no individual row in the result set can exceed 100 MiB,
and no column value can exceed 10 MiB.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `sql`:
>>> sql = ''
>>>
>>> for element in client.execute_streaming_sql(session, sql):
... # process element
... pass
Args:
session (str): Required. The session in which the SQL query should be performed.
sql (str): Required. The SQL string.
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a
temporary read-only transaction with strong concurrency.
The transaction to use.
For queries, if none is provided, the default is a temporary read-only
transaction with strong concurrency.
Standard DML statements require a ReadWrite transaction. Single-use
transactions are not supported (to avoid replay). The caller must
either supply an existing transaction ID or begin a new transaction.
Partitioned DML requires an existing PartitionedDml transaction ID.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL string can contain parameter placeholders. A parameter
placeholder consists of ``'@'`` followed by the parameter name.
Parameter names consist of any combination of letters, numbers, and
underscores.
Parameters can appear anywhere that a literal value is expected. The
same parameter name can be used more than once, for example:
``"WHERE id > @msg_id AND id < @msg_id + 100"``
It is an error to execute an SQL statement with unbound parameters.
Parameter values are specified using ``params``, which is a JSON object
whose keys are parameter names, and whose values are the corresponding
parameter values.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Struct`
param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type
from a JSON value. For example, values of type ``BYTES`` and values of
type ``STRING`` both appear in ``params`` as JSON strings.
In these cases, ``param_types`` can be used to specify the exact SQL
type for some or all of the SQL statement parameters. See the definition
of ``Type`` for more information about SQL types.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Type`
resume_token (bytes): If this request is resuming a previously interrupted SQL statement
execution, ``resume_token`` should be copied from the last
``PartialResultSet`` yielded before the interruption. Doing this enables
the new SQL statement execution to resume where the last one left off.
The rest of the request parameters must exactly match the request that
yielded this token.
query_mode (~google.cloud.spanner_v1.types.QueryMode): Used to control the amount of debugging information returned in
``ResultSetStats``. If ``partition_token`` is set, ``query_mode`` can
only be set to ``QueryMode.NORMAL``.
partition_token (bytes): If present, results will be restricted to the specified partition
previously created using PartitionQuery(). There must be an exact match
for the values of fields common to this message and the
PartitionQueryRequest message used to create this partition\_token.
seqno (long): A per-transaction sequence number used to identify this request. This
makes each request idempotent such that if the request is received multiple
times, at most one will succeed.
The sequence number must be monotonically increasing within the
transaction. If a request arrives for the first time with an out-of-order
sequence number, the transaction may be aborted. Replays of previously
handled requests will yield the same response as the first execution.
Required for DML statements. Ignored for queries.
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:
Iterable[~google.cloud.spanner_v1.types.PartialResultSet].
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. | [
"Like",
"ExecuteSql",
"except",
"returns",
"the",
"result",
"set",
"as",
"a",
"stream",
".",
"Unlike",
"ExecuteSql",
"there",
"is",
"no",
"limit",
"on",
"the",
"size",
"of",
"the",
"returned",
"result",
"set",
".",
"However",
"no",
"individual",
"row",
"in",
"the",
"result",
"set",
"can",
"exceed",
"100",
"MiB",
"and",
"no",
"column",
"value",
"can",
"exceed",
"10",
"MiB",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L712-L872 |
28,377 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/gapic/spanner_client.py | SpannerClient.execute_batch_dml | def execute_batch_dml(
self,
session,
transaction,
statements,
seqno,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Executes a batch of SQL DML statements. This method allows many
statements to be run with lower latency than submitting them
sequentially with ``ExecuteSql``.
Statements are executed in order, sequentially.
``ExecuteBatchDmlResponse`` will contain a ``ResultSet`` for each DML
statement that has successfully executed. If a statement fails, its
error status will be returned as part of the
``ExecuteBatchDmlResponse``. Execution will stop at the first failed
statement; the remaining statements will not run.
ExecuteBatchDml is expected to return an OK status with a response even
if there was an error while processing one of the DML statements.
Clients must inspect response.status to determine if there were any
errors while processing the request.
See more details in ``ExecuteBatchDmlRequest`` and
``ExecuteBatchDmlResponse``.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `transaction`:
>>> transaction = {}
>>>
>>> # TODO: Initialize `statements`:
>>> statements = []
>>>
>>> # TODO: Initialize `seqno`:
>>> seqno = 0
>>>
>>> response = client.execute_batch_dml(session, transaction, statements, seqno)
Args:
session (str): Required. The session in which the DML statements should be performed.
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. A ReadWrite transaction is required. Single-use
transactions are not supported (to avoid replay). The caller must either
supply an existing transaction ID or begin a new transaction.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
statements (list[Union[dict, ~google.cloud.spanner_v1.types.Statement]]): The list of statements to execute in this batch. Statements are executed
serially, such that the effects of statement i are visible to statement
i+1. Each statement must be a DML statement. Execution will stop at the
first failed statement; the remaining statements will not run.
REQUIRES: statements\_size() > 0.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Statement`
seqno (long): A per-transaction sequence number used to identify this request. This is
used in the same space as the seqno in ``ExecuteSqlRequest``. See more
details in ``ExecuteSqlRequest``.
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.spanner_v1.types.ExecuteBatchDmlResponse` 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 "execute_batch_dml" not in self._inner_api_calls:
self._inner_api_calls[
"execute_batch_dml"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.execute_batch_dml,
default_retry=self._method_configs["ExecuteBatchDml"].retry,
default_timeout=self._method_configs["ExecuteBatchDml"].timeout,
client_info=self._client_info,
)
request = spanner_pb2.ExecuteBatchDmlRequest(
session=session, transaction=transaction, statements=statements, seqno=seqno
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session", session)]
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["execute_batch_dml"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def execute_batch_dml(
self,
session,
transaction,
statements,
seqno,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Executes a batch of SQL DML statements. This method allows many
statements to be run with lower latency than submitting them
sequentially with ``ExecuteSql``.
Statements are executed in order, sequentially.
``ExecuteBatchDmlResponse`` will contain a ``ResultSet`` for each DML
statement that has successfully executed. If a statement fails, its
error status will be returned as part of the
``ExecuteBatchDmlResponse``. Execution will stop at the first failed
statement; the remaining statements will not run.
ExecuteBatchDml is expected to return an OK status with a response even
if there was an error while processing one of the DML statements.
Clients must inspect response.status to determine if there were any
errors while processing the request.
See more details in ``ExecuteBatchDmlRequest`` and
``ExecuteBatchDmlResponse``.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `transaction`:
>>> transaction = {}
>>>
>>> # TODO: Initialize `statements`:
>>> statements = []
>>>
>>> # TODO: Initialize `seqno`:
>>> seqno = 0
>>>
>>> response = client.execute_batch_dml(session, transaction, statements, seqno)
Args:
session (str): Required. The session in which the DML statements should be performed.
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. A ReadWrite transaction is required. Single-use
transactions are not supported (to avoid replay). The caller must either
supply an existing transaction ID or begin a new transaction.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
statements (list[Union[dict, ~google.cloud.spanner_v1.types.Statement]]): The list of statements to execute in this batch. Statements are executed
serially, such that the effects of statement i are visible to statement
i+1. Each statement must be a DML statement. Execution will stop at the
first failed statement; the remaining statements will not run.
REQUIRES: statements\_size() > 0.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Statement`
seqno (long): A per-transaction sequence number used to identify this request. This is
used in the same space as the seqno in ``ExecuteSqlRequest``. See more
details in ``ExecuteSqlRequest``.
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.spanner_v1.types.ExecuteBatchDmlResponse` 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 "execute_batch_dml" not in self._inner_api_calls:
self._inner_api_calls[
"execute_batch_dml"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.execute_batch_dml,
default_retry=self._method_configs["ExecuteBatchDml"].retry,
default_timeout=self._method_configs["ExecuteBatchDml"].timeout,
client_info=self._client_info,
)
request = spanner_pb2.ExecuteBatchDmlRequest(
session=session, transaction=transaction, statements=statements, seqno=seqno
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session", session)]
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["execute_batch_dml"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"execute_batch_dml",
"(",
"self",
",",
"session",
",",
"transaction",
",",
"statements",
",",
"seqno",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"execute_batch_dml\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"execute_batch_dml\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"execute_batch_dml",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"ExecuteBatchDml\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"ExecuteBatchDml\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"spanner_pb2",
".",
"ExecuteBatchDmlRequest",
"(",
"session",
"=",
"session",
",",
"transaction",
"=",
"transaction",
",",
"statements",
"=",
"statements",
",",
"seqno",
"=",
"seqno",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"session\"",
",",
"session",
")",
"]",
"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",
"[",
"\"execute_batch_dml\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Executes a batch of SQL DML statements. This method allows many
statements to be run with lower latency than submitting them
sequentially with ``ExecuteSql``.
Statements are executed in order, sequentially.
``ExecuteBatchDmlResponse`` will contain a ``ResultSet`` for each DML
statement that has successfully executed. If a statement fails, its
error status will be returned as part of the
``ExecuteBatchDmlResponse``. Execution will stop at the first failed
statement; the remaining statements will not run.
ExecuteBatchDml is expected to return an OK status with a response even
if there was an error while processing one of the DML statements.
Clients must inspect response.status to determine if there were any
errors while processing the request.
See more details in ``ExecuteBatchDmlRequest`` and
``ExecuteBatchDmlResponse``.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `transaction`:
>>> transaction = {}
>>>
>>> # TODO: Initialize `statements`:
>>> statements = []
>>>
>>> # TODO: Initialize `seqno`:
>>> seqno = 0
>>>
>>> response = client.execute_batch_dml(session, transaction, statements, seqno)
Args:
session (str): Required. The session in which the DML statements should be performed.
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. A ReadWrite transaction is required. Single-use
transactions are not supported (to avoid replay). The caller must either
supply an existing transaction ID or begin a new transaction.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
statements (list[Union[dict, ~google.cloud.spanner_v1.types.Statement]]): The list of statements to execute in this batch. Statements are executed
serially, such that the effects of statement i are visible to statement
i+1. Each statement must be a DML statement. Execution will stop at the
first failed statement; the remaining statements will not run.
REQUIRES: statements\_size() > 0.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Statement`
seqno (long): A per-transaction sequence number used to identify this request. This is
used in the same space as the seqno in ``ExecuteSqlRequest``. See more
details in ``ExecuteSqlRequest``.
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.spanner_v1.types.ExecuteBatchDmlResponse` 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. | [
"Executes",
"a",
"batch",
"of",
"SQL",
"DML",
"statements",
".",
"This",
"method",
"allows",
"many",
"statements",
"to",
"be",
"run",
"with",
"lower",
"latency",
"than",
"submitting",
"them",
"sequentially",
"with",
"ExecuteSql",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L874-L990 |
28,378 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/gapic/spanner_client.py | SpannerClient.commit | def commit(
self,
session,
mutations,
transaction_id=None,
single_use_transaction=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Commits a transaction. The request includes the mutations to be applied
to rows in the database.
``Commit`` might return an ``ABORTED`` error. This can occur at any
time; commonly, the cause is conflicts with concurrent transactions.
However, it can also happen for a variety of other reasons. If
``Commit`` returns ``ABORTED``, the caller should re-attempt the
transaction from the beginning, re-using the same session.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `mutations`:
>>> mutations = []
>>>
>>> response = client.commit(session, mutations)
Args:
session (str): Required. The session in which the transaction to be committed is running.
mutations (list[Union[dict, ~google.cloud.spanner_v1.types.Mutation]]): The mutations to be executed when this transaction commits. All
mutations are applied atomically, in the order they appear in
this list.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Mutation`
transaction_id (bytes): Commit a previously-started transaction.
single_use_transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Execute mutations in a temporary transaction. Note that unlike commit of
a previously-started transaction, commit with a temporary transaction is
non-idempotent. That is, if the ``CommitRequest`` is sent to Cloud
Spanner more than once (for instance, due to retries in the application,
or in the transport library), it is possible that the mutations are
executed more than once. If this is undesirable, use
``BeginTransaction`` and ``Commit`` instead.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionOptions`
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.spanner_v1.types.CommitResponse` 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 "commit" not in self._inner_api_calls:
self._inner_api_calls[
"commit"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.commit,
default_retry=self._method_configs["Commit"].retry,
default_timeout=self._method_configs["Commit"].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(
transaction_id=transaction_id, single_use_transaction=single_use_transaction
)
request = spanner_pb2.CommitRequest(
session=session,
mutations=mutations,
transaction_id=transaction_id,
single_use_transaction=single_use_transaction,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session", session)]
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["commit"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def commit(
self,
session,
mutations,
transaction_id=None,
single_use_transaction=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Commits a transaction. The request includes the mutations to be applied
to rows in the database.
``Commit`` might return an ``ABORTED`` error. This can occur at any
time; commonly, the cause is conflicts with concurrent transactions.
However, it can also happen for a variety of other reasons. If
``Commit`` returns ``ABORTED``, the caller should re-attempt the
transaction from the beginning, re-using the same session.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `mutations`:
>>> mutations = []
>>>
>>> response = client.commit(session, mutations)
Args:
session (str): Required. The session in which the transaction to be committed is running.
mutations (list[Union[dict, ~google.cloud.spanner_v1.types.Mutation]]): The mutations to be executed when this transaction commits. All
mutations are applied atomically, in the order they appear in
this list.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Mutation`
transaction_id (bytes): Commit a previously-started transaction.
single_use_transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Execute mutations in a temporary transaction. Note that unlike commit of
a previously-started transaction, commit with a temporary transaction is
non-idempotent. That is, if the ``CommitRequest`` is sent to Cloud
Spanner more than once (for instance, due to retries in the application,
or in the transport library), it is possible that the mutations are
executed more than once. If this is undesirable, use
``BeginTransaction`` and ``Commit`` instead.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionOptions`
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.spanner_v1.types.CommitResponse` 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 "commit" not in self._inner_api_calls:
self._inner_api_calls[
"commit"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.commit,
default_retry=self._method_configs["Commit"].retry,
default_timeout=self._method_configs["Commit"].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(
transaction_id=transaction_id, single_use_transaction=single_use_transaction
)
request = spanner_pb2.CommitRequest(
session=session,
mutations=mutations,
transaction_id=transaction_id,
single_use_transaction=single_use_transaction,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session", session)]
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["commit"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"commit",
"(",
"self",
",",
"session",
",",
"mutations",
",",
"transaction_id",
"=",
"None",
",",
"single_use_transaction",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"commit\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"commit\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"commit",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"Commit\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"Commit\"",
"]",
".",
"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",
"(",
"transaction_id",
"=",
"transaction_id",
",",
"single_use_transaction",
"=",
"single_use_transaction",
")",
"request",
"=",
"spanner_pb2",
".",
"CommitRequest",
"(",
"session",
"=",
"session",
",",
"mutations",
"=",
"mutations",
",",
"transaction_id",
"=",
"transaction_id",
",",
"single_use_transaction",
"=",
"single_use_transaction",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"session\"",
",",
"session",
")",
"]",
"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",
"[",
"\"commit\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Commits a transaction. The request includes the mutations to be applied
to rows in the database.
``Commit`` might return an ``ABORTED`` error. This can occur at any
time; commonly, the cause is conflicts with concurrent transactions.
However, it can also happen for a variety of other reasons. If
``Commit`` returns ``ABORTED``, the caller should re-attempt the
transaction from the beginning, re-using the same session.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `mutations`:
>>> mutations = []
>>>
>>> response = client.commit(session, mutations)
Args:
session (str): Required. The session in which the transaction to be committed is running.
mutations (list[Union[dict, ~google.cloud.spanner_v1.types.Mutation]]): The mutations to be executed when this transaction commits. All
mutations are applied atomically, in the order they appear in
this list.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Mutation`
transaction_id (bytes): Commit a previously-started transaction.
single_use_transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Execute mutations in a temporary transaction. Note that unlike commit of
a previously-started transaction, commit with a temporary transaction is
non-idempotent. That is, if the ``CommitRequest`` is sent to Cloud
Spanner more than once (for instance, due to retries in the application,
or in the transport library), it is possible that the mutations are
executed more than once. If this is undesirable, use
``BeginTransaction`` and ``Commit`` instead.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionOptions`
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.spanner_v1.types.CommitResponse` 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. | [
"Commits",
"a",
"transaction",
".",
"The",
"request",
"includes",
"the",
"mutations",
"to",
"be",
"applied",
"to",
"rows",
"in",
"the",
"database",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L1352-L1460 |
28,379 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/gapic/spanner_client.py | SpannerClient.partition_query | def partition_query(
self,
session,
sql,
transaction=None,
params=None,
param_types=None,
partition_options=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a set of partition tokens that can be used to execute a query
operation in parallel. Each of the returned partition tokens can be used
by ``ExecuteStreamingSql`` to specify a subset of the query result to
read. The same session and read-only transaction must be used by the
PartitionQueryRequest used to create the partition tokens and the
ExecuteSqlRequests that use the partition tokens.
Partition tokens become invalid when the session used to create them is
deleted, is idle for too long, begins a new transaction, or becomes too
old. When any of these happen, it is not possible to resume the query,
and the whole operation must be restarted from the beginning.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `sql`:
>>> sql = ''
>>>
>>> response = client.partition_query(session, sql)
Args:
session (str): Required. The session used to create the partitions.
sql (str): The query request to generate partitions for. The request will fail if
the query is not root partitionable. The query plan of a root
partitionable query has a single distributed union operator. A
distributed union operator conceptually divides one or more tables into
multiple splits, remotely evaluates a subquery independently on each
split, and then unions all results.
This must not contain DML commands, such as INSERT, UPDATE, or DELETE.
Use ``ExecuteStreamingSql`` with a PartitionedDml transaction for large,
partition-friendly DML operations.
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use
transactions are not.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL query string can contain parameter placeholders. A parameter
placeholder consists of ``'@'`` followed by the parameter name.
Parameter names consist of any combination of letters, numbers, and
underscores.
Parameters can appear anywhere that a literal value is expected. The
same parameter name can be used more than once, for example:
``"WHERE id > @msg_id AND id < @msg_id + 100"``
It is an error to execute an SQL query with unbound parameters.
Parameter values are specified using ``params``, which is a JSON object
whose keys are parameter names, and whose values are the corresponding
parameter values.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Struct`
param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type
from a JSON value. For example, values of type ``BYTES`` and values of
type ``STRING`` both appear in ``params`` as JSON strings.
In these cases, ``param_types`` can be used to specify the exact SQL
type for some or all of the SQL query parameters. See the definition of
``Type`` for more information about SQL types.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Type`
partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.PartitionOptions`
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.spanner_v1.types.PartitionResponse` 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 "partition_query" not in self._inner_api_calls:
self._inner_api_calls[
"partition_query"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.partition_query,
default_retry=self._method_configs["PartitionQuery"].retry,
default_timeout=self._method_configs["PartitionQuery"].timeout,
client_info=self._client_info,
)
request = spanner_pb2.PartitionQueryRequest(
session=session,
sql=sql,
transaction=transaction,
params=params,
param_types=param_types,
partition_options=partition_options,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session", session)]
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["partition_query"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def partition_query(
self,
session,
sql,
transaction=None,
params=None,
param_types=None,
partition_options=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a set of partition tokens that can be used to execute a query
operation in parallel. Each of the returned partition tokens can be used
by ``ExecuteStreamingSql`` to specify a subset of the query result to
read. The same session and read-only transaction must be used by the
PartitionQueryRequest used to create the partition tokens and the
ExecuteSqlRequests that use the partition tokens.
Partition tokens become invalid when the session used to create them is
deleted, is idle for too long, begins a new transaction, or becomes too
old. When any of these happen, it is not possible to resume the query,
and the whole operation must be restarted from the beginning.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `sql`:
>>> sql = ''
>>>
>>> response = client.partition_query(session, sql)
Args:
session (str): Required. The session used to create the partitions.
sql (str): The query request to generate partitions for. The request will fail if
the query is not root partitionable. The query plan of a root
partitionable query has a single distributed union operator. A
distributed union operator conceptually divides one or more tables into
multiple splits, remotely evaluates a subquery independently on each
split, and then unions all results.
This must not contain DML commands, such as INSERT, UPDATE, or DELETE.
Use ``ExecuteStreamingSql`` with a PartitionedDml transaction for large,
partition-friendly DML operations.
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use
transactions are not.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL query string can contain parameter placeholders. A parameter
placeholder consists of ``'@'`` followed by the parameter name.
Parameter names consist of any combination of letters, numbers, and
underscores.
Parameters can appear anywhere that a literal value is expected. The
same parameter name can be used more than once, for example:
``"WHERE id > @msg_id AND id < @msg_id + 100"``
It is an error to execute an SQL query with unbound parameters.
Parameter values are specified using ``params``, which is a JSON object
whose keys are parameter names, and whose values are the corresponding
parameter values.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Struct`
param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type
from a JSON value. For example, values of type ``BYTES`` and values of
type ``STRING`` both appear in ``params`` as JSON strings.
In these cases, ``param_types`` can be used to specify the exact SQL
type for some or all of the SQL query parameters. See the definition of
``Type`` for more information about SQL types.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Type`
partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.PartitionOptions`
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.spanner_v1.types.PartitionResponse` 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 "partition_query" not in self._inner_api_calls:
self._inner_api_calls[
"partition_query"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.partition_query,
default_retry=self._method_configs["PartitionQuery"].retry,
default_timeout=self._method_configs["PartitionQuery"].timeout,
client_info=self._client_info,
)
request = spanner_pb2.PartitionQueryRequest(
session=session,
sql=sql,
transaction=transaction,
params=params,
param_types=param_types,
partition_options=partition_options,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session", session)]
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["partition_query"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"partition_query",
"(",
"self",
",",
"session",
",",
"sql",
",",
"transaction",
"=",
"None",
",",
"params",
"=",
"None",
",",
"param_types",
"=",
"None",
",",
"partition_options",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"partition_query\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"partition_query\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"partition_query",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"PartitionQuery\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"PartitionQuery\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"spanner_pb2",
".",
"PartitionQueryRequest",
"(",
"session",
"=",
"session",
",",
"sql",
"=",
"sql",
",",
"transaction",
"=",
"transaction",
",",
"params",
"=",
"params",
",",
"param_types",
"=",
"param_types",
",",
"partition_options",
"=",
"partition_options",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"session\"",
",",
"session",
")",
"]",
"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",
"[",
"\"partition_query\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Creates a set of partition tokens that can be used to execute a query
operation in parallel. Each of the returned partition tokens can be used
by ``ExecuteStreamingSql`` to specify a subset of the query result to
read. The same session and read-only transaction must be used by the
PartitionQueryRequest used to create the partition tokens and the
ExecuteSqlRequests that use the partition tokens.
Partition tokens become invalid when the session used to create them is
deleted, is idle for too long, begins a new transaction, or becomes too
old. When any of these happen, it is not possible to resume the query,
and the whole operation must be restarted from the beginning.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `sql`:
>>> sql = ''
>>>
>>> response = client.partition_query(session, sql)
Args:
session (str): Required. The session used to create the partitions.
sql (str): The query request to generate partitions for. The request will fail if
the query is not root partitionable. The query plan of a root
partitionable query has a single distributed union operator. A
distributed union operator conceptually divides one or more tables into
multiple splits, remotely evaluates a subquery independently on each
split, and then unions all results.
This must not contain DML commands, such as INSERT, UPDATE, or DELETE.
Use ``ExecuteStreamingSql`` with a PartitionedDml transaction for large,
partition-friendly DML operations.
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use
transactions are not.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL query string can contain parameter placeholders. A parameter
placeholder consists of ``'@'`` followed by the parameter name.
Parameter names consist of any combination of letters, numbers, and
underscores.
Parameters can appear anywhere that a literal value is expected. The
same parameter name can be used more than once, for example:
``"WHERE id > @msg_id AND id < @msg_id + 100"``
It is an error to execute an SQL query with unbound parameters.
Parameter values are specified using ``params``, which is a JSON object
whose keys are parameter names, and whose values are the corresponding
parameter values.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Struct`
param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type
from a JSON value. For example, values of type ``BYTES`` and values of
type ``STRING`` both appear in ``params`` as JSON strings.
In these cases, ``param_types`` can be used to specify the exact SQL
type for some or all of the SQL query parameters. See the definition of
``Type`` for more information about SQL types.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Type`
partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.PartitionOptions`
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.spanner_v1.types.PartitionResponse` 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. | [
"Creates",
"a",
"set",
"of",
"partition",
"tokens",
"that",
"can",
"be",
"used",
"to",
"execute",
"a",
"query",
"operation",
"in",
"parallel",
".",
"Each",
"of",
"the",
"returned",
"partition",
"tokens",
"can",
"be",
"used",
"by",
"ExecuteStreamingSql",
"to",
"specify",
"a",
"subset",
"of",
"the",
"query",
"result",
"to",
"read",
".",
"The",
"same",
"session",
"and",
"read",
"-",
"only",
"transaction",
"must",
"be",
"used",
"by",
"the",
"PartitionQueryRequest",
"used",
"to",
"create",
"the",
"partition",
"tokens",
"and",
"the",
"ExecuteSqlRequests",
"that",
"use",
"the",
"partition",
"tokens",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L1541-L1679 |
28,380 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/gapic/spanner_client.py | SpannerClient.partition_read | def partition_read(
self,
session,
table,
key_set,
transaction=None,
index=None,
columns=None,
partition_options=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a set of partition tokens that can be used to execute a read
operation in parallel. Each of the returned partition tokens can be used
by ``StreamingRead`` to specify a subset of the read result to read. The
same session and read-only transaction must be used by the
PartitionReadRequest used to create the partition tokens and the
ReadRequests that use the partition tokens. There are no ordering
guarantees on rows returned among the returned partition tokens, or even
within each individual StreamingRead call issued with a
partition\_token.
Partition tokens become invalid when the session used to create them is
deleted, is idle for too long, begins a new transaction, or becomes too
old. When any of these happen, it is not possible to resume the read,
and the whole operation must be restarted from the beginning.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `table`:
>>> table = ''
>>>
>>> # TODO: Initialize `key_set`:
>>> key_set = {}
>>>
>>> response = client.partition_read(session, table, key_set)
Args:
session (str): Required. The session used to create the partitions.
table (str): Required. The name of the table in the database to be read.
key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set``
names the primary keys of the rows in ``table`` to be yielded, unless
``index`` is present. If ``index`` is present, then ``key_set`` instead
names index keys in ``index``.
It is not an error for the ``key_set`` to name rows that do not exist in
the database. Read yields nothing for nonexistent rows.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.KeySet`
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use
transactions are not.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
index (str): If non-empty, the name of an index on ``table``. This index is used
instead of the table primary key when interpreting ``key_set`` and
sorting result rows. See ``key_set`` for further information.
columns (list[str]): The columns of ``table`` to be returned for each row matching this
request.
partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.PartitionOptions`
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.spanner_v1.types.PartitionResponse` 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 "partition_read" not in self._inner_api_calls:
self._inner_api_calls[
"partition_read"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.partition_read,
default_retry=self._method_configs["PartitionRead"].retry,
default_timeout=self._method_configs["PartitionRead"].timeout,
client_info=self._client_info,
)
request = spanner_pb2.PartitionReadRequest(
session=session,
table=table,
key_set=key_set,
transaction=transaction,
index=index,
columns=columns,
partition_options=partition_options,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session", session)]
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["partition_read"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def partition_read(
self,
session,
table,
key_set,
transaction=None,
index=None,
columns=None,
partition_options=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a set of partition tokens that can be used to execute a read
operation in parallel. Each of the returned partition tokens can be used
by ``StreamingRead`` to specify a subset of the read result to read. The
same session and read-only transaction must be used by the
PartitionReadRequest used to create the partition tokens and the
ReadRequests that use the partition tokens. There are no ordering
guarantees on rows returned among the returned partition tokens, or even
within each individual StreamingRead call issued with a
partition\_token.
Partition tokens become invalid when the session used to create them is
deleted, is idle for too long, begins a new transaction, or becomes too
old. When any of these happen, it is not possible to resume the read,
and the whole operation must be restarted from the beginning.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `table`:
>>> table = ''
>>>
>>> # TODO: Initialize `key_set`:
>>> key_set = {}
>>>
>>> response = client.partition_read(session, table, key_set)
Args:
session (str): Required. The session used to create the partitions.
table (str): Required. The name of the table in the database to be read.
key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set``
names the primary keys of the rows in ``table`` to be yielded, unless
``index`` is present. If ``index`` is present, then ``key_set`` instead
names index keys in ``index``.
It is not an error for the ``key_set`` to name rows that do not exist in
the database. Read yields nothing for nonexistent rows.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.KeySet`
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use
transactions are not.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
index (str): If non-empty, the name of an index on ``table``. This index is used
instead of the table primary key when interpreting ``key_set`` and
sorting result rows. See ``key_set`` for further information.
columns (list[str]): The columns of ``table`` to be returned for each row matching this
request.
partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.PartitionOptions`
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.spanner_v1.types.PartitionResponse` 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 "partition_read" not in self._inner_api_calls:
self._inner_api_calls[
"partition_read"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.partition_read,
default_retry=self._method_configs["PartitionRead"].retry,
default_timeout=self._method_configs["PartitionRead"].timeout,
client_info=self._client_info,
)
request = spanner_pb2.PartitionReadRequest(
session=session,
table=table,
key_set=key_set,
transaction=transaction,
index=index,
columns=columns,
partition_options=partition_options,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session", session)]
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["partition_read"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"partition_read",
"(",
"self",
",",
"session",
",",
"table",
",",
"key_set",
",",
"transaction",
"=",
"None",
",",
"index",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"partition_options",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"partition_read\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"partition_read\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"partition_read",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"PartitionRead\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"PartitionRead\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"spanner_pb2",
".",
"PartitionReadRequest",
"(",
"session",
"=",
"session",
",",
"table",
"=",
"table",
",",
"key_set",
"=",
"key_set",
",",
"transaction",
"=",
"transaction",
",",
"index",
"=",
"index",
",",
"columns",
"=",
"columns",
",",
"partition_options",
"=",
"partition_options",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"session\"",
",",
"session",
")",
"]",
"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",
"[",
"\"partition_read\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Creates a set of partition tokens that can be used to execute a read
operation in parallel. Each of the returned partition tokens can be used
by ``StreamingRead`` to specify a subset of the read result to read. The
same session and read-only transaction must be used by the
PartitionReadRequest used to create the partition tokens and the
ReadRequests that use the partition tokens. There are no ordering
guarantees on rows returned among the returned partition tokens, or even
within each individual StreamingRead call issued with a
partition\_token.
Partition tokens become invalid when the session used to create them is
deleted, is idle for too long, begins a new transaction, or becomes too
old. When any of these happen, it is not possible to resume the read,
and the whole operation must be restarted from the beginning.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `table`:
>>> table = ''
>>>
>>> # TODO: Initialize `key_set`:
>>> key_set = {}
>>>
>>> response = client.partition_read(session, table, key_set)
Args:
session (str): Required. The session used to create the partitions.
table (str): Required. The name of the table in the database to be read.
key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set``
names the primary keys of the rows in ``table`` to be yielded, unless
``index`` is present. If ``index`` is present, then ``key_set`` instead
names index keys in ``index``.
It is not an error for the ``key_set`` to name rows that do not exist in
the database. Read yields nothing for nonexistent rows.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.KeySet`
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use
transactions are not.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
index (str): If non-empty, the name of an index on ``table``. This index is used
instead of the table primary key when interpreting ``key_set`` and
sorting result rows. See ``key_set`` for further information.
columns (list[str]): The columns of ``table`` to be returned for each row matching this
request.
partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.PartitionOptions`
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.spanner_v1.types.PartitionResponse` 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. | [
"Creates",
"a",
"set",
"of",
"partition",
"tokens",
"that",
"can",
"be",
"used",
"to",
"execute",
"a",
"read",
"operation",
"in",
"parallel",
".",
"Each",
"of",
"the",
"returned",
"partition",
"tokens",
"can",
"be",
"used",
"by",
"StreamingRead",
"to",
"specify",
"a",
"subset",
"of",
"the",
"read",
"result",
"to",
"read",
".",
"The",
"same",
"session",
"and",
"read",
"-",
"only",
"transaction",
"must",
"be",
"used",
"by",
"the",
"PartitionReadRequest",
"used",
"to",
"create",
"the",
"partition",
"tokens",
"and",
"the",
"ReadRequests",
"that",
"use",
"the",
"partition",
"tokens",
".",
"There",
"are",
"no",
"ordering",
"guarantees",
"on",
"rows",
"returned",
"among",
"the",
"returned",
"partition",
"tokens",
"or",
"even",
"within",
"each",
"individual",
"StreamingRead",
"call",
"issued",
"with",
"a",
"partition",
"\\",
"_token",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L1681-L1806 |
28,381 | googleapis/google-cloud-python | datastore/google/cloud/datastore/_gapic.py | make_datastore_api | def make_datastore_api(client):
"""Create an instance of the GAPIC Datastore API.
:type client: :class:`~google.cloud.datastore.client.Client`
:param client: The client that holds configuration details.
:rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`
:returns: A datastore API instance with the proper credentials.
"""
parse_result = six.moves.urllib_parse.urlparse(client._base_url)
host = parse_result.netloc
if parse_result.scheme == "https":
channel = make_secure_channel(client._credentials, DEFAULT_USER_AGENT, host)
else:
channel = insecure_channel(host)
return datastore_client.DatastoreClient(
channel=channel,
client_info=client_info.ClientInfo(
client_library_version=__version__, gapic_version=__version__
),
) | python | def make_datastore_api(client):
"""Create an instance of the GAPIC Datastore API.
:type client: :class:`~google.cloud.datastore.client.Client`
:param client: The client that holds configuration details.
:rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`
:returns: A datastore API instance with the proper credentials.
"""
parse_result = six.moves.urllib_parse.urlparse(client._base_url)
host = parse_result.netloc
if parse_result.scheme == "https":
channel = make_secure_channel(client._credentials, DEFAULT_USER_AGENT, host)
else:
channel = insecure_channel(host)
return datastore_client.DatastoreClient(
channel=channel,
client_info=client_info.ClientInfo(
client_library_version=__version__, gapic_version=__version__
),
) | [
"def",
"make_datastore_api",
"(",
"client",
")",
":",
"parse_result",
"=",
"six",
".",
"moves",
".",
"urllib_parse",
".",
"urlparse",
"(",
"client",
".",
"_base_url",
")",
"host",
"=",
"parse_result",
".",
"netloc",
"if",
"parse_result",
".",
"scheme",
"==",
"\"https\"",
":",
"channel",
"=",
"make_secure_channel",
"(",
"client",
".",
"_credentials",
",",
"DEFAULT_USER_AGENT",
",",
"host",
")",
"else",
":",
"channel",
"=",
"insecure_channel",
"(",
"host",
")",
"return",
"datastore_client",
".",
"DatastoreClient",
"(",
"channel",
"=",
"channel",
",",
"client_info",
"=",
"client_info",
".",
"ClientInfo",
"(",
"client_library_version",
"=",
"__version__",
",",
"gapic_version",
"=",
"__version__",
")",
",",
")"
] | Create an instance of the GAPIC Datastore API.
:type client: :class:`~google.cloud.datastore.client.Client`
:param client: The client that holds configuration details.
:rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`
:returns: A datastore API instance with the proper credentials. | [
"Create",
"an",
"instance",
"of",
"the",
"GAPIC",
"Datastore",
"API",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/_gapic.py#L28-L49 |
28,382 | googleapis/google-cloud-python | bigquery/noxfile.py | snippets | def snippets(session):
"""Run the snippets test suite."""
# Sanity check: Only run snippets tests if the environment variable is set.
if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""):
session.skip("Credentials must be set via environment variable.")
# Install all test dependencies, then install local packages in place.
session.install("mock", "pytest")
for local_dep in LOCAL_DEPS:
session.install("-e", local_dep)
session.install("-e", os.path.join("..", "storage"))
session.install("-e", os.path.join("..", "test_utils"))
session.install("-e", ".[all]")
# Run py.test against the snippets tests.
session.run("py.test", os.path.join("docs", "snippets.py"), *session.posargs)
session.run("py.test", "samples", *session.posargs) | python | def snippets(session):
"""Run the snippets test suite."""
# Sanity check: Only run snippets tests if the environment variable is set.
if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""):
session.skip("Credentials must be set via environment variable.")
# Install all test dependencies, then install local packages in place.
session.install("mock", "pytest")
for local_dep in LOCAL_DEPS:
session.install("-e", local_dep)
session.install("-e", os.path.join("..", "storage"))
session.install("-e", os.path.join("..", "test_utils"))
session.install("-e", ".[all]")
# Run py.test against the snippets tests.
session.run("py.test", os.path.join("docs", "snippets.py"), *session.posargs)
session.run("py.test", "samples", *session.posargs) | [
"def",
"snippets",
"(",
"session",
")",
":",
"# Sanity check: Only run snippets tests if the environment variable is set.",
"if",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"\"GOOGLE_APPLICATION_CREDENTIALS\"",
",",
"\"\"",
")",
":",
"session",
".",
"skip",
"(",
"\"Credentials must be set via environment variable.\"",
")",
"# Install all test dependencies, then install local packages in place.",
"session",
".",
"install",
"(",
"\"mock\"",
",",
"\"pytest\"",
")",
"for",
"local_dep",
"in",
"LOCAL_DEPS",
":",
"session",
".",
"install",
"(",
"\"-e\"",
",",
"local_dep",
")",
"session",
".",
"install",
"(",
"\"-e\"",
",",
"os",
".",
"path",
".",
"join",
"(",
"\"..\"",
",",
"\"storage\"",
")",
")",
"session",
".",
"install",
"(",
"\"-e\"",
",",
"os",
".",
"path",
".",
"join",
"(",
"\"..\"",
",",
"\"test_utils\"",
")",
")",
"session",
".",
"install",
"(",
"\"-e\"",
",",
"\".[all]\"",
")",
"# Run py.test against the snippets tests.",
"session",
".",
"run",
"(",
"\"py.test\"",
",",
"os",
".",
"path",
".",
"join",
"(",
"\"docs\"",
",",
"\"snippets.py\"",
")",
",",
"*",
"session",
".",
"posargs",
")",
"session",
".",
"run",
"(",
"\"py.test\"",
",",
"\"samples\"",
",",
"*",
"session",
".",
"posargs",
")"
] | Run the snippets test suite. | [
"Run",
"the",
"snippets",
"test",
"suite",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/noxfile.py#L104-L121 |
28,383 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/message.py | _indent | def _indent(lines, prefix=" "):
"""Indent some text.
Note that this is present as ``textwrap.indent``, but not in Python 2.
Args:
lines (str): The newline delimited string to be indented.
prefix (Optional[str]): The prefix to indent each line with. Default
to two spaces.
Returns:
str: The newly indented content.
"""
indented = []
for line in lines.split("\n"):
indented.append(prefix + line)
return "\n".join(indented) | python | def _indent(lines, prefix=" "):
"""Indent some text.
Note that this is present as ``textwrap.indent``, but not in Python 2.
Args:
lines (str): The newline delimited string to be indented.
prefix (Optional[str]): The prefix to indent each line with. Default
to two spaces.
Returns:
str: The newly indented content.
"""
indented = []
for line in lines.split("\n"):
indented.append(prefix + line)
return "\n".join(indented) | [
"def",
"_indent",
"(",
"lines",
",",
"prefix",
"=",
"\" \"",
")",
":",
"indented",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"indented",
".",
"append",
"(",
"prefix",
"+",
"line",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"indented",
")"
] | Indent some text.
Note that this is present as ``textwrap.indent``, but not in Python 2.
Args:
lines (str): The newline delimited string to be indented.
prefix (Optional[str]): The prefix to indent each line with. Default
to two spaces.
Returns:
str: The newly indented content. | [
"Indent",
"some",
"text",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L33-L49 |
28,384 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/message.py | Message.publish_time | def publish_time(self):
"""Return the time that the message was originally published.
Returns:
datetime: The date and time that the message was published.
"""
timestamp = self._message.publish_time
delta = datetime.timedelta(
seconds=timestamp.seconds, microseconds=timestamp.nanos // 1000
)
return datetime_helpers._UTC_EPOCH + delta | python | def publish_time(self):
"""Return the time that the message was originally published.
Returns:
datetime: The date and time that the message was published.
"""
timestamp = self._message.publish_time
delta = datetime.timedelta(
seconds=timestamp.seconds, microseconds=timestamp.nanos // 1000
)
return datetime_helpers._UTC_EPOCH + delta | [
"def",
"publish_time",
"(",
"self",
")",
":",
"timestamp",
"=",
"self",
".",
"_message",
".",
"publish_time",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"timestamp",
".",
"seconds",
",",
"microseconds",
"=",
"timestamp",
".",
"nanos",
"//",
"1000",
")",
"return",
"datetime_helpers",
".",
"_UTC_EPOCH",
"+",
"delta"
] | Return the time that the message was originally published.
Returns:
datetime: The date and time that the message was published. | [
"Return",
"the",
"time",
"that",
"the",
"message",
"was",
"originally",
"published",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L147-L157 |
28,385 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/message.py | Message.ack | def ack(self):
"""Acknowledge the given message.
Acknowledging a message in Pub/Sub means that you are done
with it, and it will not be delivered to this subscription again.
You should avoid acknowledging messages until you have
*finished* processing them, so that in the event of a failure,
you receive the message again.
.. warning::
Acks in Pub/Sub are best effort. You should always
ensure that your processing code is idempotent, as you may
receive any given message more than once.
"""
time_to_ack = math.ceil(time.time() - self._received_timestamp)
self._request_queue.put(
requests.AckRequest(
ack_id=self._ack_id, byte_size=self.size, time_to_ack=time_to_ack
)
) | python | def ack(self):
"""Acknowledge the given message.
Acknowledging a message in Pub/Sub means that you are done
with it, and it will not be delivered to this subscription again.
You should avoid acknowledging messages until you have
*finished* processing them, so that in the event of a failure,
you receive the message again.
.. warning::
Acks in Pub/Sub are best effort. You should always
ensure that your processing code is idempotent, as you may
receive any given message more than once.
"""
time_to_ack = math.ceil(time.time() - self._received_timestamp)
self._request_queue.put(
requests.AckRequest(
ack_id=self._ack_id, byte_size=self.size, time_to_ack=time_to_ack
)
) | [
"def",
"ack",
"(",
"self",
")",
":",
"time_to_ack",
"=",
"math",
".",
"ceil",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_received_timestamp",
")",
"self",
".",
"_request_queue",
".",
"put",
"(",
"requests",
".",
"AckRequest",
"(",
"ack_id",
"=",
"self",
".",
"_ack_id",
",",
"byte_size",
"=",
"self",
".",
"size",
",",
"time_to_ack",
"=",
"time_to_ack",
")",
")"
] | Acknowledge the given message.
Acknowledging a message in Pub/Sub means that you are done
with it, and it will not be delivered to this subscription again.
You should avoid acknowledging messages until you have
*finished* processing them, so that in the event of a failure,
you receive the message again.
.. warning::
Acks in Pub/Sub are best effort. You should always
ensure that your processing code is idempotent, as you may
receive any given message more than once. | [
"Acknowledge",
"the",
"given",
"message",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L169-L188 |
28,386 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/message.py | Message.drop | def drop(self):
"""Release the message from lease management.
This informs the policy to no longer hold on to the lease for this
message. Pub/Sub will re-deliver the message if it is not acknowledged
before the existing lease expires.
.. warning::
For most use cases, the only reason to drop a message from
lease management is on :meth:`ack` or :meth:`nack`; these methods
both call this one. You probably do not want to call this method
directly.
"""
self._request_queue.put(
requests.DropRequest(ack_id=self._ack_id, byte_size=self.size)
) | python | def drop(self):
"""Release the message from lease management.
This informs the policy to no longer hold on to the lease for this
message. Pub/Sub will re-deliver the message if it is not acknowledged
before the existing lease expires.
.. warning::
For most use cases, the only reason to drop a message from
lease management is on :meth:`ack` or :meth:`nack`; these methods
both call this one. You probably do not want to call this method
directly.
"""
self._request_queue.put(
requests.DropRequest(ack_id=self._ack_id, byte_size=self.size)
) | [
"def",
"drop",
"(",
"self",
")",
":",
"self",
".",
"_request_queue",
".",
"put",
"(",
"requests",
".",
"DropRequest",
"(",
"ack_id",
"=",
"self",
".",
"_ack_id",
",",
"byte_size",
"=",
"self",
".",
"size",
")",
")"
] | Release the message from lease management.
This informs the policy to no longer hold on to the lease for this
message. Pub/Sub will re-deliver the message if it is not acknowledged
before the existing lease expires.
.. warning::
For most use cases, the only reason to drop a message from
lease management is on :meth:`ack` or :meth:`nack`; these methods
both call this one. You probably do not want to call this method
directly. | [
"Release",
"the",
"message",
"from",
"lease",
"management",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L190-L205 |
28,387 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/message.py | Message.lease | def lease(self):
"""Inform the policy to lease this message continually.
.. note::
This method is called by the constructor, and you should never
need to call it manually.
"""
self._request_queue.put(
requests.LeaseRequest(ack_id=self._ack_id, byte_size=self.size)
) | python | def lease(self):
"""Inform the policy to lease this message continually.
.. note::
This method is called by the constructor, and you should never
need to call it manually.
"""
self._request_queue.put(
requests.LeaseRequest(ack_id=self._ack_id, byte_size=self.size)
) | [
"def",
"lease",
"(",
"self",
")",
":",
"self",
".",
"_request_queue",
".",
"put",
"(",
"requests",
".",
"LeaseRequest",
"(",
"ack_id",
"=",
"self",
".",
"_ack_id",
",",
"byte_size",
"=",
"self",
".",
"size",
")",
")"
] | Inform the policy to lease this message continually.
.. note::
This method is called by the constructor, and you should never
need to call it manually. | [
"Inform",
"the",
"policy",
"to",
"lease",
"this",
"message",
"continually",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L207-L216 |
28,388 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/message.py | Message.modify_ack_deadline | def modify_ack_deadline(self, seconds):
"""Resets the deadline for acknowledgement.
New deadline will be the given value of seconds from now.
The default implementation handles this for you; you should not need
to manually deal with setting ack deadlines. The exception case is
if you are implementing your own custom subclass of
:class:`~.pubsub_v1.subcriber._consumer.Consumer`.
Args:
seconds (int): The number of seconds to set the lease deadline
to. This should be between 0 and 600. Due to network latency,
values below 10 are advised against.
"""
self._request_queue.put(
requests.ModAckRequest(ack_id=self._ack_id, seconds=seconds)
) | python | def modify_ack_deadline(self, seconds):
"""Resets the deadline for acknowledgement.
New deadline will be the given value of seconds from now.
The default implementation handles this for you; you should not need
to manually deal with setting ack deadlines. The exception case is
if you are implementing your own custom subclass of
:class:`~.pubsub_v1.subcriber._consumer.Consumer`.
Args:
seconds (int): The number of seconds to set the lease deadline
to. This should be between 0 and 600. Due to network latency,
values below 10 are advised against.
"""
self._request_queue.put(
requests.ModAckRequest(ack_id=self._ack_id, seconds=seconds)
) | [
"def",
"modify_ack_deadline",
"(",
"self",
",",
"seconds",
")",
":",
"self",
".",
"_request_queue",
".",
"put",
"(",
"requests",
".",
"ModAckRequest",
"(",
"ack_id",
"=",
"self",
".",
"_ack_id",
",",
"seconds",
"=",
"seconds",
")",
")"
] | Resets the deadline for acknowledgement.
New deadline will be the given value of seconds from now.
The default implementation handles this for you; you should not need
to manually deal with setting ack deadlines. The exception case is
if you are implementing your own custom subclass of
:class:`~.pubsub_v1.subcriber._consumer.Consumer`.
Args:
seconds (int): The number of seconds to set the lease deadline
to. This should be between 0 and 600. Due to network latency,
values below 10 are advised against. | [
"Resets",
"the",
"deadline",
"for",
"acknowledgement",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L218-L235 |
28,389 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/message.py | Message.nack | def nack(self):
"""Decline to acknowldge the given message.
This will cause the message to be re-delivered to the subscription.
"""
self._request_queue.put(
requests.NackRequest(ack_id=self._ack_id, byte_size=self.size)
) | python | def nack(self):
"""Decline to acknowldge the given message.
This will cause the message to be re-delivered to the subscription.
"""
self._request_queue.put(
requests.NackRequest(ack_id=self._ack_id, byte_size=self.size)
) | [
"def",
"nack",
"(",
"self",
")",
":",
"self",
".",
"_request_queue",
".",
"put",
"(",
"requests",
".",
"NackRequest",
"(",
"ack_id",
"=",
"self",
".",
"_ack_id",
",",
"byte_size",
"=",
"self",
".",
"size",
")",
")"
] | Decline to acknowldge the given message.
This will cause the message to be re-delivered to the subscription. | [
"Decline",
"to",
"acknowldge",
"the",
"given",
"message",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L237-L244 |
28,390 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/magics.py | _run_query | def _run_query(client, query, job_config=None):
"""Runs a query while printing status updates
Args:
client (google.cloud.bigquery.client.Client):
Client to bundle configuration needed for API requests.
query (str):
SQL query to be executed. Defaults to the standard SQL dialect.
Use the ``job_config`` parameter to change dialects.
job_config (google.cloud.bigquery.job.QueryJobConfig, optional):
Extra configuration options for the job.
Returns:
google.cloud.bigquery.job.QueryJob: the query job created
Example:
>>> client = bigquery.Client()
>>> _run_query(client, "SELECT 17")
Executing query with job ID: bf633912-af2c-4780-b568-5d868058632b
Query executing: 1.66s
Query complete after 2.07s
'bf633912-af2c-4780-b568-5d868058632b'
"""
start_time = time.time()
query_job = client.query(query, job_config=job_config)
print("Executing query with job ID: {}".format(query_job.job_id))
while True:
print("\rQuery executing: {:0.2f}s".format(time.time() - start_time), end="")
try:
query_job.result(timeout=0.5)
break
except futures.TimeoutError:
continue
print("\nQuery complete after {:0.2f}s".format(time.time() - start_time))
return query_job | python | def _run_query(client, query, job_config=None):
"""Runs a query while printing status updates
Args:
client (google.cloud.bigquery.client.Client):
Client to bundle configuration needed for API requests.
query (str):
SQL query to be executed. Defaults to the standard SQL dialect.
Use the ``job_config`` parameter to change dialects.
job_config (google.cloud.bigquery.job.QueryJobConfig, optional):
Extra configuration options for the job.
Returns:
google.cloud.bigquery.job.QueryJob: the query job created
Example:
>>> client = bigquery.Client()
>>> _run_query(client, "SELECT 17")
Executing query with job ID: bf633912-af2c-4780-b568-5d868058632b
Query executing: 1.66s
Query complete after 2.07s
'bf633912-af2c-4780-b568-5d868058632b'
"""
start_time = time.time()
query_job = client.query(query, job_config=job_config)
print("Executing query with job ID: {}".format(query_job.job_id))
while True:
print("\rQuery executing: {:0.2f}s".format(time.time() - start_time), end="")
try:
query_job.result(timeout=0.5)
break
except futures.TimeoutError:
continue
print("\nQuery complete after {:0.2f}s".format(time.time() - start_time))
return query_job | [
"def",
"_run_query",
"(",
"client",
",",
"query",
",",
"job_config",
"=",
"None",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"query_job",
"=",
"client",
".",
"query",
"(",
"query",
",",
"job_config",
"=",
"job_config",
")",
"print",
"(",
"\"Executing query with job ID: {}\"",
".",
"format",
"(",
"query_job",
".",
"job_id",
")",
")",
"while",
"True",
":",
"print",
"(",
"\"\\rQuery executing: {:0.2f}s\"",
".",
"format",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
",",
"end",
"=",
"\"\"",
")",
"try",
":",
"query_job",
".",
"result",
"(",
"timeout",
"=",
"0.5",
")",
"break",
"except",
"futures",
".",
"TimeoutError",
":",
"continue",
"print",
"(",
"\"\\nQuery complete after {:0.2f}s\"",
".",
"format",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
")",
"return",
"query_job"
] | Runs a query while printing status updates
Args:
client (google.cloud.bigquery.client.Client):
Client to bundle configuration needed for API requests.
query (str):
SQL query to be executed. Defaults to the standard SQL dialect.
Use the ``job_config`` parameter to change dialects.
job_config (google.cloud.bigquery.job.QueryJobConfig, optional):
Extra configuration options for the job.
Returns:
google.cloud.bigquery.job.QueryJob: the query job created
Example:
>>> client = bigquery.Client()
>>> _run_query(client, "SELECT 17")
Executing query with job ID: bf633912-af2c-4780-b568-5d868058632b
Query executing: 1.66s
Query complete after 2.07s
'bf633912-af2c-4780-b568-5d868058632b' | [
"Runs",
"a",
"query",
"while",
"printing",
"status",
"updates"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/magics.py#L243-L278 |
28,391 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/magics.py | _cell_magic | def _cell_magic(line, query):
"""Underlying function for bigquery cell magic
Note:
This function contains the underlying logic for the 'bigquery' cell
magic. This function is not meant to be called directly.
Args:
line (str): "%%bigquery" followed by arguments as required
query (str): SQL query to run
Returns:
pandas.DataFrame: the query results.
"""
args = magic_arguments.parse_argstring(_cell_magic, line)
params = []
if args.params is not None:
try:
params = _helpers.to_query_parameters(
ast.literal_eval("".join(args.params))
)
except Exception:
raise SyntaxError(
"--params is not a correctly formatted JSON string or a JSON "
"serializable dictionary"
)
project = args.project or context.project
client = bigquery.Client(project=project, credentials=context.credentials)
bqstorage_client = _make_bqstorage_client(
args.use_bqstorage_api or context.use_bqstorage_api, context.credentials
)
job_config = bigquery.job.QueryJobConfig()
job_config.query_parameters = params
job_config.use_legacy_sql = args.use_legacy_sql
query_job = _run_query(client, query, job_config)
if not args.verbose:
display.clear_output()
result = query_job.to_dataframe(bqstorage_client=bqstorage_client)
if args.destination_var:
IPython.get_ipython().push({args.destination_var: result})
else:
return result | python | def _cell_magic(line, query):
"""Underlying function for bigquery cell magic
Note:
This function contains the underlying logic for the 'bigquery' cell
magic. This function is not meant to be called directly.
Args:
line (str): "%%bigquery" followed by arguments as required
query (str): SQL query to run
Returns:
pandas.DataFrame: the query results.
"""
args = magic_arguments.parse_argstring(_cell_magic, line)
params = []
if args.params is not None:
try:
params = _helpers.to_query_parameters(
ast.literal_eval("".join(args.params))
)
except Exception:
raise SyntaxError(
"--params is not a correctly formatted JSON string or a JSON "
"serializable dictionary"
)
project = args.project or context.project
client = bigquery.Client(project=project, credentials=context.credentials)
bqstorage_client = _make_bqstorage_client(
args.use_bqstorage_api or context.use_bqstorage_api, context.credentials
)
job_config = bigquery.job.QueryJobConfig()
job_config.query_parameters = params
job_config.use_legacy_sql = args.use_legacy_sql
query_job = _run_query(client, query, job_config)
if not args.verbose:
display.clear_output()
result = query_job.to_dataframe(bqstorage_client=bqstorage_client)
if args.destination_var:
IPython.get_ipython().push({args.destination_var: result})
else:
return result | [
"def",
"_cell_magic",
"(",
"line",
",",
"query",
")",
":",
"args",
"=",
"magic_arguments",
".",
"parse_argstring",
"(",
"_cell_magic",
",",
"line",
")",
"params",
"=",
"[",
"]",
"if",
"args",
".",
"params",
"is",
"not",
"None",
":",
"try",
":",
"params",
"=",
"_helpers",
".",
"to_query_parameters",
"(",
"ast",
".",
"literal_eval",
"(",
"\"\"",
".",
"join",
"(",
"args",
".",
"params",
")",
")",
")",
"except",
"Exception",
":",
"raise",
"SyntaxError",
"(",
"\"--params is not a correctly formatted JSON string or a JSON \"",
"\"serializable dictionary\"",
")",
"project",
"=",
"args",
".",
"project",
"or",
"context",
".",
"project",
"client",
"=",
"bigquery",
".",
"Client",
"(",
"project",
"=",
"project",
",",
"credentials",
"=",
"context",
".",
"credentials",
")",
"bqstorage_client",
"=",
"_make_bqstorage_client",
"(",
"args",
".",
"use_bqstorage_api",
"or",
"context",
".",
"use_bqstorage_api",
",",
"context",
".",
"credentials",
")",
"job_config",
"=",
"bigquery",
".",
"job",
".",
"QueryJobConfig",
"(",
")",
"job_config",
".",
"query_parameters",
"=",
"params",
"job_config",
".",
"use_legacy_sql",
"=",
"args",
".",
"use_legacy_sql",
"query_job",
"=",
"_run_query",
"(",
"client",
",",
"query",
",",
"job_config",
")",
"if",
"not",
"args",
".",
"verbose",
":",
"display",
".",
"clear_output",
"(",
")",
"result",
"=",
"query_job",
".",
"to_dataframe",
"(",
"bqstorage_client",
"=",
"bqstorage_client",
")",
"if",
"args",
".",
"destination_var",
":",
"IPython",
".",
"get_ipython",
"(",
")",
".",
"push",
"(",
"{",
"args",
".",
"destination_var",
":",
"result",
"}",
")",
"else",
":",
"return",
"result"
] | Underlying function for bigquery cell magic
Note:
This function contains the underlying logic for the 'bigquery' cell
magic. This function is not meant to be called directly.
Args:
line (str): "%%bigquery" followed by arguments as required
query (str): SQL query to run
Returns:
pandas.DataFrame: the query results. | [
"Underlying",
"function",
"for",
"bigquery",
"cell",
"magic"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/magics.py#L336-L381 |
28,392 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py | FirestoreClient.database_root_path | def database_root_path(cls, project, database):
"""Return a fully-qualified database_root string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}",
project=project,
database=database,
) | python | def database_root_path(cls, project, database):
"""Return a fully-qualified database_root string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}",
project=project,
database=database,
) | [
"def",
"database_root_path",
"(",
"cls",
",",
"project",
",",
"database",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/databases/{database}\"",
",",
"project",
"=",
"project",
",",
"database",
"=",
"database",
",",
")"
] | Return a fully-qualified database_root string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"database_root",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L99-L105 |
28,393 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py | FirestoreClient.document_root_path | def document_root_path(cls, project, database):
"""Return a fully-qualified document_root string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents",
project=project,
database=database,
) | python | def document_root_path(cls, project, database):
"""Return a fully-qualified document_root string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents",
project=project,
database=database,
) | [
"def",
"document_root_path",
"(",
"cls",
",",
"project",
",",
"database",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/databases/{database}/documents\"",
",",
"project",
"=",
"project",
",",
"database",
"=",
"database",
",",
")"
] | Return a fully-qualified document_root string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"document_root",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L108-L114 |
28,394 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py | FirestoreClient.document_path_path | def document_path_path(cls, project, database, document_path):
"""Return a fully-qualified document_path string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents/{document_path=**}",
project=project,
database=database,
document_path=document_path,
) | python | def document_path_path(cls, project, database, document_path):
"""Return a fully-qualified document_path string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents/{document_path=**}",
project=project,
database=database,
document_path=document_path,
) | [
"def",
"document_path_path",
"(",
"cls",
",",
"project",
",",
"database",
",",
"document_path",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/databases/{database}/documents/{document_path=**}\"",
",",
"project",
"=",
"project",
",",
"database",
"=",
"database",
",",
"document_path",
"=",
"document_path",
",",
")"
] | Return a fully-qualified document_path string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"document_path",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L117-L124 |
28,395 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py | FirestoreClient.any_path_path | def any_path_path(cls, project, database, document, any_path):
"""Return a fully-qualified any_path string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents/{document}/{any_path=**}",
project=project,
database=database,
document=document,
any_path=any_path,
) | python | def any_path_path(cls, project, database, document, any_path):
"""Return a fully-qualified any_path string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents/{document}/{any_path=**}",
project=project,
database=database,
document=document,
any_path=any_path,
) | [
"def",
"any_path_path",
"(",
"cls",
",",
"project",
",",
"database",
",",
"document",
",",
"any_path",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/databases/{database}/documents/{document}/{any_path=**}\"",
",",
"project",
"=",
"project",
",",
"database",
"=",
"database",
",",
"document",
"=",
"document",
",",
"any_path",
"=",
"any_path",
",",
")"
] | Return a fully-qualified any_path string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"any_path",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L127-L135 |
28,396 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py | FirestoreClient.get_document | def get_document(
self,
name,
mask=None,
transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets a single document.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
>>> response = client.get_document(name)
Args:
name (str): The resource name of the Document to get. In the format:
``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If the document has a field that is not present in this mask, that field
will not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
transaction (bytes): Reads the document in a transaction.
read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads the version of the document at the given time.
This may not be older than 60 seconds.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.firestore_v1beta1.types.Document` 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_document" not in self._inner_api_calls:
self._inner_api_calls[
"get_document"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_document,
default_retry=self._method_configs["GetDocument"].retry,
default_timeout=self._method_configs["GetDocument"].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(
transaction=transaction, read_time=read_time
)
request = firestore_pb2.GetDocumentRequest(
name=name, mask=mask, transaction=transaction, read_time=read_time
)
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["get_document"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def get_document(
self,
name,
mask=None,
transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets a single document.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
>>> response = client.get_document(name)
Args:
name (str): The resource name of the Document to get. In the format:
``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If the document has a field that is not present in this mask, that field
will not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
transaction (bytes): Reads the document in a transaction.
read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads the version of the document at the given time.
This may not be older than 60 seconds.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.firestore_v1beta1.types.Document` 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_document" not in self._inner_api_calls:
self._inner_api_calls[
"get_document"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_document,
default_retry=self._method_configs["GetDocument"].retry,
default_timeout=self._method_configs["GetDocument"].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(
transaction=transaction, read_time=read_time
)
request = firestore_pb2.GetDocumentRequest(
name=name, mask=mask, transaction=transaction, read_time=read_time
)
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["get_document"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"get_document",
"(",
"self",
",",
"name",
",",
"mask",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"read_time",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"get_document\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"get_document\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"get_document",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"GetDocument\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"GetDocument\"",
"]",
".",
"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",
"(",
"transaction",
"=",
"transaction",
",",
"read_time",
"=",
"read_time",
")",
"request",
"=",
"firestore_pb2",
".",
"GetDocumentRequest",
"(",
"name",
"=",
"name",
",",
"mask",
"=",
"mask",
",",
"transaction",
"=",
"transaction",
",",
"read_time",
"=",
"read_time",
")",
"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",
"[",
"\"get_document\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Gets a single document.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
>>> response = client.get_document(name)
Args:
name (str): The resource name of the Document to get. In the format:
``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If the document has a field that is not present in this mask, that field
will not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
transaction (bytes): Reads the document in a transaction.
read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads the version of the document at the given time.
This may not be older than 60 seconds.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.firestore_v1beta1.types.Document` 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. | [
"Gets",
"a",
"single",
"document",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L236-L328 |
28,397 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py | FirestoreClient.list_documents | def list_documents(
self,
parent,
collection_id,
page_size=None,
order_by=None,
mask=None,
transaction=None,
read_time=None,
show_missing=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Lists documents.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
>>> # TODO: Initialize `collection_id`:
>>> collection_id = ''
>>>
>>> # Iterate over all results
>>> for element in client.list_documents(parent, collection_id):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_documents(parent, collection_id).pages:
... for element in page:
... # process element
... pass
Args:
parent (str): The parent resource name. In the format:
``projects/{project_id}/databases/{database_id}/documents`` or
``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
For example: ``projects/my-project/databases/my-database/documents`` or
``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom``
collection_id (str): The collection ID, relative to ``parent``, to list. For example:
``chatrooms`` or ``messages``.
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
order_by (str): The order to sort results by. For example: ``priority desc, name``.
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If a document has a field that is not present in this mask, that field
will not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
transaction (bytes): Reads documents in a transaction.
read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time.
This may not be older than 60 seconds.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
show_missing (bool): If the list should show missing documents. A missing document is a
document that does not exist but has sub-documents. These documents will
be returned with a key but will not have fields,
``Document.create_time``, or ``Document.update_time`` set.
Requests with ``show_missing`` may not specify ``where`` or
``order_by``.
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.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.firestore_v1beta1.types.Document` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
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_documents" not in self._inner_api_calls:
self._inner_api_calls[
"list_documents"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_documents,
default_retry=self._method_configs["ListDocuments"].retry,
default_timeout=self._method_configs["ListDocuments"].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(
transaction=transaction, read_time=read_time
)
request = firestore_pb2.ListDocumentsRequest(
parent=parent,
collection_id=collection_id,
page_size=page_size,
order_by=order_by,
mask=mask,
transaction=transaction,
read_time=read_time,
show_missing=show_missing,
)
iterator = google.api_core.page_iterator.GRPCIterator(
client=None,
method=functools.partial(
self._inner_api_calls["list_documents"],
retry=retry,
timeout=timeout,
metadata=metadata,
),
request=request,
items_field="documents",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | python | def list_documents(
self,
parent,
collection_id,
page_size=None,
order_by=None,
mask=None,
transaction=None,
read_time=None,
show_missing=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Lists documents.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
>>> # TODO: Initialize `collection_id`:
>>> collection_id = ''
>>>
>>> # Iterate over all results
>>> for element in client.list_documents(parent, collection_id):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_documents(parent, collection_id).pages:
... for element in page:
... # process element
... pass
Args:
parent (str): The parent resource name. In the format:
``projects/{project_id}/databases/{database_id}/documents`` or
``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
For example: ``projects/my-project/databases/my-database/documents`` or
``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom``
collection_id (str): The collection ID, relative to ``parent``, to list. For example:
``chatrooms`` or ``messages``.
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
order_by (str): The order to sort results by. For example: ``priority desc, name``.
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If a document has a field that is not present in this mask, that field
will not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
transaction (bytes): Reads documents in a transaction.
read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time.
This may not be older than 60 seconds.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
show_missing (bool): If the list should show missing documents. A missing document is a
document that does not exist but has sub-documents. These documents will
be returned with a key but will not have fields,
``Document.create_time``, or ``Document.update_time`` set.
Requests with ``show_missing`` may not specify ``where`` or
``order_by``.
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.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.firestore_v1beta1.types.Document` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
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_documents" not in self._inner_api_calls:
self._inner_api_calls[
"list_documents"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_documents,
default_retry=self._method_configs["ListDocuments"].retry,
default_timeout=self._method_configs["ListDocuments"].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(
transaction=transaction, read_time=read_time
)
request = firestore_pb2.ListDocumentsRequest(
parent=parent,
collection_id=collection_id,
page_size=page_size,
order_by=order_by,
mask=mask,
transaction=transaction,
read_time=read_time,
show_missing=show_missing,
)
iterator = google.api_core.page_iterator.GRPCIterator(
client=None,
method=functools.partial(
self._inner_api_calls["list_documents"],
retry=retry,
timeout=timeout,
metadata=metadata,
),
request=request,
items_field="documents",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | [
"def",
"list_documents",
"(",
"self",
",",
"parent",
",",
"collection_id",
",",
"page_size",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"read_time",
"=",
"None",
",",
"show_missing",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"list_documents\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"list_documents\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"list_documents",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"ListDocuments\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"ListDocuments\"",
"]",
".",
"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",
"(",
"transaction",
"=",
"transaction",
",",
"read_time",
"=",
"read_time",
")",
"request",
"=",
"firestore_pb2",
".",
"ListDocumentsRequest",
"(",
"parent",
"=",
"parent",
",",
"collection_id",
"=",
"collection_id",
",",
"page_size",
"=",
"page_size",
",",
"order_by",
"=",
"order_by",
",",
"mask",
"=",
"mask",
",",
"transaction",
"=",
"transaction",
",",
"read_time",
"=",
"read_time",
",",
"show_missing",
"=",
"show_missing",
",",
")",
"iterator",
"=",
"google",
".",
"api_core",
".",
"page_iterator",
".",
"GRPCIterator",
"(",
"client",
"=",
"None",
",",
"method",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_inner_api_calls",
"[",
"\"list_documents\"",
"]",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
",",
")",
",",
"request",
"=",
"request",
",",
"items_field",
"=",
"\"documents\"",
",",
"request_token_field",
"=",
"\"page_token\"",
",",
"response_token_field",
"=",
"\"next_page_token\"",
",",
")",
"return",
"iterator"
] | Lists documents.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
>>> # TODO: Initialize `collection_id`:
>>> collection_id = ''
>>>
>>> # Iterate over all results
>>> for element in client.list_documents(parent, collection_id):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_documents(parent, collection_id).pages:
... for element in page:
... # process element
... pass
Args:
parent (str): The parent resource name. In the format:
``projects/{project_id}/databases/{database_id}/documents`` or
``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
For example: ``projects/my-project/databases/my-database/documents`` or
``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom``
collection_id (str): The collection ID, relative to ``parent``, to list. For example:
``chatrooms`` or ``messages``.
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
order_by (str): The order to sort results by. For example: ``priority desc, name``.
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If a document has a field that is not present in this mask, that field
will not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
transaction (bytes): Reads documents in a transaction.
read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time.
This may not be older than 60 seconds.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
show_missing (bool): If the list should show missing documents. A missing document is a
document that does not exist but has sub-documents. These documents will
be returned with a key but will not have fields,
``Document.create_time``, or ``Document.update_time`` set.
Requests with ``show_missing`` may not specify ``where`` or
``order_by``.
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.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.firestore_v1beta1.types.Document` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
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. | [
"Lists",
"documents",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L330-L467 |
28,398 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py | FirestoreClient.update_document | def update_document(
self,
document,
update_mask,
mask=None,
current_document=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates or inserts a document.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> # TODO: Initialize `document`:
>>> document = {}
>>>
>>> # TODO: Initialize `update_mask`:
>>> update_mask = {}
>>>
>>> response = client.update_document(document, update_mask)
Args:
document (Union[dict, ~google.cloud.firestore_v1beta1.types.Document]): The updated document.
Creates the document if it does not already exist.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Document`
update_mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to update.
None of the field paths in the mask may contain a reserved name.
If the document exists on the server and has fields not referenced in the
mask, they are left unchanged.
Fields referenced in the mask, but not present in the input document, are
deleted from the document on the server.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If the document has a field that is not present in this mask, that field
will not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document.
The request will fail if this is set and not met by the target document.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Precondition`
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.firestore_v1beta1.types.Document` 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_document" not in self._inner_api_calls:
self._inner_api_calls[
"update_document"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_document,
default_retry=self._method_configs["UpdateDocument"].retry,
default_timeout=self._method_configs["UpdateDocument"].timeout,
client_info=self._client_info,
)
request = firestore_pb2.UpdateDocumentRequest(
document=document,
update_mask=update_mask,
mask=mask,
current_document=current_document,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("document.name", document.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_document"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def update_document(
self,
document,
update_mask,
mask=None,
current_document=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates or inserts a document.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> # TODO: Initialize `document`:
>>> document = {}
>>>
>>> # TODO: Initialize `update_mask`:
>>> update_mask = {}
>>>
>>> response = client.update_document(document, update_mask)
Args:
document (Union[dict, ~google.cloud.firestore_v1beta1.types.Document]): The updated document.
Creates the document if it does not already exist.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Document`
update_mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to update.
None of the field paths in the mask may contain a reserved name.
If the document exists on the server and has fields not referenced in the
mask, they are left unchanged.
Fields referenced in the mask, but not present in the input document, are
deleted from the document on the server.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If the document has a field that is not present in this mask, that field
will not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document.
The request will fail if this is set and not met by the target document.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Precondition`
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.firestore_v1beta1.types.Document` 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_document" not in self._inner_api_calls:
self._inner_api_calls[
"update_document"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_document,
default_retry=self._method_configs["UpdateDocument"].retry,
default_timeout=self._method_configs["UpdateDocument"].timeout,
client_info=self._client_info,
)
request = firestore_pb2.UpdateDocumentRequest(
document=document,
update_mask=update_mask,
mask=mask,
current_document=current_document,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("document.name", document.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_document"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"update_document",
"(",
"self",
",",
"document",
",",
"update_mask",
",",
"mask",
"=",
"None",
",",
"current_document",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"update_document\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"update_document\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"update_document",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"UpdateDocument\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"UpdateDocument\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"firestore_pb2",
".",
"UpdateDocumentRequest",
"(",
"document",
"=",
"document",
",",
"update_mask",
"=",
"update_mask",
",",
"mask",
"=",
"mask",
",",
"current_document",
"=",
"current_document",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"document.name\"",
",",
"document",
".",
"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_document\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Updates or inserts a document.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> # TODO: Initialize `document`:
>>> document = {}
>>>
>>> # TODO: Initialize `update_mask`:
>>> update_mask = {}
>>>
>>> response = client.update_document(document, update_mask)
Args:
document (Union[dict, ~google.cloud.firestore_v1beta1.types.Document]): The updated document.
Creates the document if it does not already exist.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Document`
update_mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to update.
None of the field paths in the mask may contain a reserved name.
If the document exists on the server and has fields not referenced in the
mask, they are left unchanged.
Fields referenced in the mask, but not present in the input document, are
deleted from the document on the server.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If the document has a field that is not present in this mask, that field
will not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document.
The request will fail if this is set and not met by the target document.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Precondition`
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.firestore_v1beta1.types.Document` 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. | [
"Updates",
"or",
"inserts",
"a",
"document",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L562-L667 |
28,399 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py | FirestoreClient.batch_get_documents | def batch_get_documents(
self,
database,
documents,
mask=None,
transaction=None,
new_transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets multiple documents.
Documents returned by this method are not guaranteed to be returned in the
same order that they were requested.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
>>>
>>> # TODO: Initialize `documents`:
>>> documents = []
>>>
>>> for element in client.batch_get_documents(database, documents):
... # process element
... pass
Args:
database (str): The database name. In the format:
``projects/{project_id}/databases/{database_id}``.
documents (list[str]): The names of the documents to retrieve. In the format:
``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
The request will fail if any of the document is not a child resource of
the given ``database``. Duplicate names will be elided.
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If a document has a field that is not present in this mask, that field will
not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
transaction (bytes): Reads documents in a transaction.
new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents.
Defaults to a read-only transaction.
The new transaction ID will be returned as the first response in the
stream.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions`
read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time.
This may not be older than 60 seconds.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
Iterable[~google.cloud.firestore_v1beta1.types.BatchGetDocumentsResponse].
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 "batch_get_documents" not in self._inner_api_calls:
self._inner_api_calls[
"batch_get_documents"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.batch_get_documents,
default_retry=self._method_configs["BatchGetDocuments"].retry,
default_timeout=self._method_configs["BatchGetDocuments"].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(
transaction=transaction,
new_transaction=new_transaction,
read_time=read_time,
)
request = firestore_pb2.BatchGetDocumentsRequest(
database=database,
documents=documents,
mask=mask,
transaction=transaction,
new_transaction=new_transaction,
read_time=read_time,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("database", database)]
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["batch_get_documents"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def batch_get_documents(
self,
database,
documents,
mask=None,
transaction=None,
new_transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets multiple documents.
Documents returned by this method are not guaranteed to be returned in the
same order that they were requested.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
>>>
>>> # TODO: Initialize `documents`:
>>> documents = []
>>>
>>> for element in client.batch_get_documents(database, documents):
... # process element
... pass
Args:
database (str): The database name. In the format:
``projects/{project_id}/databases/{database_id}``.
documents (list[str]): The names of the documents to retrieve. In the format:
``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
The request will fail if any of the document is not a child resource of
the given ``database``. Duplicate names will be elided.
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If a document has a field that is not present in this mask, that field will
not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
transaction (bytes): Reads documents in a transaction.
new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents.
Defaults to a read-only transaction.
The new transaction ID will be returned as the first response in the
stream.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions`
read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time.
This may not be older than 60 seconds.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
Iterable[~google.cloud.firestore_v1beta1.types.BatchGetDocumentsResponse].
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 "batch_get_documents" not in self._inner_api_calls:
self._inner_api_calls[
"batch_get_documents"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.batch_get_documents,
default_retry=self._method_configs["BatchGetDocuments"].retry,
default_timeout=self._method_configs["BatchGetDocuments"].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(
transaction=transaction,
new_transaction=new_transaction,
read_time=read_time,
)
request = firestore_pb2.BatchGetDocumentsRequest(
database=database,
documents=documents,
mask=mask,
transaction=transaction,
new_transaction=new_transaction,
read_time=read_time,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("database", database)]
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["batch_get_documents"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"batch_get_documents",
"(",
"self",
",",
"database",
",",
"documents",
",",
"mask",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"new_transaction",
"=",
"None",
",",
"read_time",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"batch_get_documents\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"batch_get_documents\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"batch_get_documents",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"BatchGetDocuments\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"BatchGetDocuments\"",
"]",
".",
"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",
"(",
"transaction",
"=",
"transaction",
",",
"new_transaction",
"=",
"new_transaction",
",",
"read_time",
"=",
"read_time",
",",
")",
"request",
"=",
"firestore_pb2",
".",
"BatchGetDocumentsRequest",
"(",
"database",
"=",
"database",
",",
"documents",
"=",
"documents",
",",
"mask",
"=",
"mask",
",",
"transaction",
"=",
"transaction",
",",
"new_transaction",
"=",
"new_transaction",
",",
"read_time",
"=",
"read_time",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"database\"",
",",
"database",
")",
"]",
"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",
"[",
"\"batch_get_documents\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Gets multiple documents.
Documents returned by this method are not guaranteed to be returned in the
same order that they were requested.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
>>>
>>> # TODO: Initialize `documents`:
>>> documents = []
>>>
>>> for element in client.batch_get_documents(database, documents):
... # process element
... pass
Args:
database (str): The database name. In the format:
``projects/{project_id}/databases/{database_id}``.
documents (list[str]): The names of the documents to retrieve. In the format:
``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
The request will fail if any of the document is not a child resource of
the given ``database``. Duplicate names will be elided.
mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.
If a document has a field that is not present in this mask, that field will
not be returned in the response.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
transaction (bytes): Reads documents in a transaction.
new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents.
Defaults to a read-only transaction.
The new transaction ID will be returned as the first response in the
stream.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions`
read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time.
This may not be older than 60 seconds.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
Iterable[~google.cloud.firestore_v1beta1.types.BatchGetDocumentsResponse].
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. | [
"Gets",
"multiple",
"documents",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L744-L864 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.