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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27,800 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/job.py | QueryJob.total_bytes_billed | def total_bytes_billed(self):
"""Return total bytes billed from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.totalBytesBilled
:rtype: int or None
:returns: total bytes processed by the job, or None if job is not
yet complete.
"""
result = self._job_statistics().get("totalBytesBilled")
if result is not None:
result = int(result)
return result | python | def total_bytes_billed(self):
"""Return total bytes billed from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.totalBytesBilled
:rtype: int or None
:returns: total bytes processed by the job, or None if job is not
yet complete.
"""
result = self._job_statistics().get("totalBytesBilled")
if result is not None:
result = int(result)
return result | [
"def",
"total_bytes_billed",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_job_statistics",
"(",
")",
".",
"get",
"(",
"\"totalBytesBilled\"",
")",
"if",
"result",
"is",
"not",
"None",
":",
"result",
"=",
"int",
"(",
"result",
")",
"return",
"result"
] | Return total bytes billed from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.totalBytesBilled
:rtype: int or None
:returns: total bytes processed by the job, or None if job is not
yet complete. | [
"Return",
"total",
"bytes",
"billed",
"from",
"job",
"statistics",
"if",
"present",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/job.py#L2593-L2606 |
27,801 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/job.py | QueryJob.num_dml_affected_rows | def num_dml_affected_rows(self):
"""Return the number of DML rows affected by the job.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.numDmlAffectedRows
:rtype: int or None
:returns: number of DML rows affected by the job, or None if job is not
yet complete.
"""
result = self._job_statistics().get("numDmlAffectedRows")
if result is not None:
result = int(result)
return result | python | def num_dml_affected_rows(self):
"""Return the number of DML rows affected by the job.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.numDmlAffectedRows
:rtype: int or None
:returns: number of DML rows affected by the job, or None if job is not
yet complete.
"""
result = self._job_statistics().get("numDmlAffectedRows")
if result is not None:
result = int(result)
return result | [
"def",
"num_dml_affected_rows",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_job_statistics",
"(",
")",
".",
"get",
"(",
"\"numDmlAffectedRows\"",
")",
"if",
"result",
"is",
"not",
"None",
":",
"result",
"=",
"int",
"(",
"result",
")",
"return",
"result"
] | Return the number of DML rows affected by the job.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.numDmlAffectedRows
:rtype: int or None
:returns: number of DML rows affected by the job, or None if job is not
yet complete. | [
"Return",
"the",
"number",
"of",
"DML",
"rows",
"affected",
"by",
"the",
"job",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/job.py#L2658-L2671 |
27,802 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/job.py | QueryJob.referenced_tables | def referenced_tables(self):
"""Return referenced tables from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.referencedTables
:rtype: list of dict
:returns: mappings describing the query plan, or an empty list
if the query has not yet completed.
"""
tables = []
datasets_by_project_name = {}
for table in self._job_statistics().get("referencedTables", ()):
t_project = table["projectId"]
ds_id = table["datasetId"]
t_dataset = datasets_by_project_name.get((t_project, ds_id))
if t_dataset is None:
t_dataset = DatasetReference(t_project, ds_id)
datasets_by_project_name[(t_project, ds_id)] = t_dataset
t_name = table["tableId"]
tables.append(t_dataset.table(t_name))
return tables | python | def referenced_tables(self):
"""Return referenced tables from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.referencedTables
:rtype: list of dict
:returns: mappings describing the query plan, or an empty list
if the query has not yet completed.
"""
tables = []
datasets_by_project_name = {}
for table in self._job_statistics().get("referencedTables", ()):
t_project = table["projectId"]
ds_id = table["datasetId"]
t_dataset = datasets_by_project_name.get((t_project, ds_id))
if t_dataset is None:
t_dataset = DatasetReference(t_project, ds_id)
datasets_by_project_name[(t_project, ds_id)] = t_dataset
t_name = table["tableId"]
tables.append(t_dataset.table(t_name))
return tables | [
"def",
"referenced_tables",
"(",
"self",
")",
":",
"tables",
"=",
"[",
"]",
"datasets_by_project_name",
"=",
"{",
"}",
"for",
"table",
"in",
"self",
".",
"_job_statistics",
"(",
")",
".",
"get",
"(",
"\"referencedTables\"",
",",
"(",
")",
")",
":",
"t_project",
"=",
"table",
"[",
"\"projectId\"",
"]",
"ds_id",
"=",
"table",
"[",
"\"datasetId\"",
"]",
"t_dataset",
"=",
"datasets_by_project_name",
".",
"get",
"(",
"(",
"t_project",
",",
"ds_id",
")",
")",
"if",
"t_dataset",
"is",
"None",
":",
"t_dataset",
"=",
"DatasetReference",
"(",
"t_project",
",",
"ds_id",
")",
"datasets_by_project_name",
"[",
"(",
"t_project",
",",
"ds_id",
")",
"]",
"=",
"t_dataset",
"t_name",
"=",
"table",
"[",
"\"tableId\"",
"]",
"tables",
".",
"append",
"(",
"t_dataset",
".",
"table",
"(",
"t_name",
")",
")",
"return",
"tables"
] | Return referenced tables from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.referencedTables
:rtype: list of dict
:returns: mappings describing the query plan, or an empty list
if the query has not yet completed. | [
"Return",
"referenced",
"tables",
"from",
"job",
"statistics",
"if",
"present",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/job.py#L2692-L2718 |
27,803 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/job.py | QueryJob.undeclared_query_parameters | def undeclared_query_parameters(self):
"""Return undeclared query parameters from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.undeclaredQueryParameters
:rtype:
list of
:class:`~google.cloud.bigquery.ArrayQueryParameter`,
:class:`~google.cloud.bigquery.ScalarQueryParameter`, or
:class:`~google.cloud.bigquery.StructQueryParameter`
:returns: undeclared parameters, or an empty list if the query has
not yet completed.
"""
parameters = []
undeclared = self._job_statistics().get("undeclaredQueryParameters", ())
for parameter in undeclared:
p_type = parameter["parameterType"]
if "arrayType" in p_type:
klass = ArrayQueryParameter
elif "structTypes" in p_type:
klass = StructQueryParameter
else:
klass = ScalarQueryParameter
parameters.append(klass.from_api_repr(parameter))
return parameters | python | def undeclared_query_parameters(self):
"""Return undeclared query parameters from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.undeclaredQueryParameters
:rtype:
list of
:class:`~google.cloud.bigquery.ArrayQueryParameter`,
:class:`~google.cloud.bigquery.ScalarQueryParameter`, or
:class:`~google.cloud.bigquery.StructQueryParameter`
:returns: undeclared parameters, or an empty list if the query has
not yet completed.
"""
parameters = []
undeclared = self._job_statistics().get("undeclaredQueryParameters", ())
for parameter in undeclared:
p_type = parameter["parameterType"]
if "arrayType" in p_type:
klass = ArrayQueryParameter
elif "structTypes" in p_type:
klass = StructQueryParameter
else:
klass = ScalarQueryParameter
parameters.append(klass.from_api_repr(parameter))
return parameters | [
"def",
"undeclared_query_parameters",
"(",
"self",
")",
":",
"parameters",
"=",
"[",
"]",
"undeclared",
"=",
"self",
".",
"_job_statistics",
"(",
")",
".",
"get",
"(",
"\"undeclaredQueryParameters\"",
",",
"(",
")",
")",
"for",
"parameter",
"in",
"undeclared",
":",
"p_type",
"=",
"parameter",
"[",
"\"parameterType\"",
"]",
"if",
"\"arrayType\"",
"in",
"p_type",
":",
"klass",
"=",
"ArrayQueryParameter",
"elif",
"\"structTypes\"",
"in",
"p_type",
":",
"klass",
"=",
"StructQueryParameter",
"else",
":",
"klass",
"=",
"ScalarQueryParameter",
"parameters",
".",
"append",
"(",
"klass",
".",
"from_api_repr",
"(",
"parameter",
")",
")",
"return",
"parameters"
] | Return undeclared query parameters from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.undeclaredQueryParameters
:rtype:
list of
:class:`~google.cloud.bigquery.ArrayQueryParameter`,
:class:`~google.cloud.bigquery.ScalarQueryParameter`, or
:class:`~google.cloud.bigquery.StructQueryParameter`
:returns: undeclared parameters, or an empty list if the query has
not yet completed. | [
"Return",
"undeclared",
"query",
"parameters",
"from",
"job",
"statistics",
"if",
"present",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/job.py#L2721-L2750 |
27,804 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/job.py | QueryJob.estimated_bytes_processed | def estimated_bytes_processed(self):
"""Return the estimated number of bytes processed by the query.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.estimatedBytesProcessed
:rtype: int or None
:returns: number of DML rows affected by the job, or None if job is not
yet complete.
"""
result = self._job_statistics().get("estimatedBytesProcessed")
if result is not None:
result = int(result)
return result | python | def estimated_bytes_processed(self):
"""Return the estimated number of bytes processed by the query.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.estimatedBytesProcessed
:rtype: int or None
:returns: number of DML rows affected by the job, or None if job is not
yet complete.
"""
result = self._job_statistics().get("estimatedBytesProcessed")
if result is not None:
result = int(result)
return result | [
"def",
"estimated_bytes_processed",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_job_statistics",
"(",
")",
".",
"get",
"(",
"\"estimatedBytesProcessed\"",
")",
"if",
"result",
"is",
"not",
"None",
":",
"result",
"=",
"int",
"(",
"result",
")",
"return",
"result"
] | Return the estimated number of bytes processed by the query.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.estimatedBytesProcessed
:rtype: int or None
:returns: number of DML rows affected by the job, or None if job is not
yet complete. | [
"Return",
"the",
"estimated",
"number",
"of",
"bytes",
"processed",
"by",
"the",
"query",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/job.py#L2753-L2766 |
27,805 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/job.py | QueryJob.to_dataframe | def to_dataframe(self, bqstorage_client=None, dtypes=None, progress_bar_type=None):
"""Return a pandas DataFrame from a QueryJob
Args:
bqstorage_client ( \
google.cloud.bigquery_storage_v1beta1.BigQueryStorageClient \
):
**Alpha Feature** Optional. A BigQuery Storage API client. If
supplied, use the faster BigQuery Storage API to fetch rows
from BigQuery. This API is a billable API.
This method requires the ``fastavro`` and
``google-cloud-bigquery-storage`` libraries.
Reading from a specific partition or snapshot is not
currently supported by this method.
**Caution**: There is a known issue reading small anonymous
query result tables with the BQ Storage API. Write your query
results to a destination table to work around this issue.
dtypes ( \
Map[str, Union[str, pandas.Series.dtype]] \
):
Optional. A dictionary of column names pandas ``dtype``s. The
provided ``dtype`` is used when constructing the series for
the column specified. Otherwise, the default pandas behavior
is used.
progress_bar_type (Optional[str]):
If set, use the `tqdm <https://tqdm.github.io/>`_ library to
display a progress bar while the data downloads. Install the
``tqdm`` package to use this feature.
See
:func:`~google.cloud.bigquery.table.RowIterator.to_dataframe`
for details.
..versionadded:: 1.11.0
Returns:
A :class:`~pandas.DataFrame` populated with row data and column
headers from the query results. The column headers are derived
from the destination table's schema.
Raises:
ValueError: If the `pandas` library cannot be imported.
"""
return self.result().to_dataframe(
bqstorage_client=bqstorage_client,
dtypes=dtypes,
progress_bar_type=progress_bar_type,
) | python | def to_dataframe(self, bqstorage_client=None, dtypes=None, progress_bar_type=None):
"""Return a pandas DataFrame from a QueryJob
Args:
bqstorage_client ( \
google.cloud.bigquery_storage_v1beta1.BigQueryStorageClient \
):
**Alpha Feature** Optional. A BigQuery Storage API client. If
supplied, use the faster BigQuery Storage API to fetch rows
from BigQuery. This API is a billable API.
This method requires the ``fastavro`` and
``google-cloud-bigquery-storage`` libraries.
Reading from a specific partition or snapshot is not
currently supported by this method.
**Caution**: There is a known issue reading small anonymous
query result tables with the BQ Storage API. Write your query
results to a destination table to work around this issue.
dtypes ( \
Map[str, Union[str, pandas.Series.dtype]] \
):
Optional. A dictionary of column names pandas ``dtype``s. The
provided ``dtype`` is used when constructing the series for
the column specified. Otherwise, the default pandas behavior
is used.
progress_bar_type (Optional[str]):
If set, use the `tqdm <https://tqdm.github.io/>`_ library to
display a progress bar while the data downloads. Install the
``tqdm`` package to use this feature.
See
:func:`~google.cloud.bigquery.table.RowIterator.to_dataframe`
for details.
..versionadded:: 1.11.0
Returns:
A :class:`~pandas.DataFrame` populated with row data and column
headers from the query results. The column headers are derived
from the destination table's schema.
Raises:
ValueError: If the `pandas` library cannot be imported.
"""
return self.result().to_dataframe(
bqstorage_client=bqstorage_client,
dtypes=dtypes,
progress_bar_type=progress_bar_type,
) | [
"def",
"to_dataframe",
"(",
"self",
",",
"bqstorage_client",
"=",
"None",
",",
"dtypes",
"=",
"None",
",",
"progress_bar_type",
"=",
"None",
")",
":",
"return",
"self",
".",
"result",
"(",
")",
".",
"to_dataframe",
"(",
"bqstorage_client",
"=",
"bqstorage_client",
",",
"dtypes",
"=",
"dtypes",
",",
"progress_bar_type",
"=",
"progress_bar_type",
",",
")"
] | Return a pandas DataFrame from a QueryJob
Args:
bqstorage_client ( \
google.cloud.bigquery_storage_v1beta1.BigQueryStorageClient \
):
**Alpha Feature** Optional. A BigQuery Storage API client. If
supplied, use the faster BigQuery Storage API to fetch rows
from BigQuery. This API is a billable API.
This method requires the ``fastavro`` and
``google-cloud-bigquery-storage`` libraries.
Reading from a specific partition or snapshot is not
currently supported by this method.
**Caution**: There is a known issue reading small anonymous
query result tables with the BQ Storage API. Write your query
results to a destination table to work around this issue.
dtypes ( \
Map[str, Union[str, pandas.Series.dtype]] \
):
Optional. A dictionary of column names pandas ``dtype``s. The
provided ``dtype`` is used when constructing the series for
the column specified. Otherwise, the default pandas behavior
is used.
progress_bar_type (Optional[str]):
If set, use the `tqdm <https://tqdm.github.io/>`_ library to
display a progress bar while the data downloads. Install the
``tqdm`` package to use this feature.
See
:func:`~google.cloud.bigquery.table.RowIterator.to_dataframe`
for details.
..versionadded:: 1.11.0
Returns:
A :class:`~pandas.DataFrame` populated with row data and column
headers from the query results. The column headers are derived
from the destination table's schema.
Raises:
ValueError: If the `pandas` library cannot be imported. | [
"Return",
"a",
"pandas",
"DataFrame",
"from",
"a",
"QueryJob"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/job.py#L2854-L2904 |
27,806 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/job.py | UnknownJob.from_api_repr | def from_api_repr(cls, resource, client):
"""Construct an UnknownJob from the JSON representation.
Args:
resource (dict): JSON representation of a job.
client (google.cloud.bigquery.client.Client):
Client connected to BigQuery API.
Returns:
UnknownJob: Job corresponding to the resource.
"""
job_ref_properties = resource.get("jobReference", {"projectId": client.project})
job_ref = _JobReference._from_api_repr(job_ref_properties)
job = cls(job_ref, client)
# Populate the job reference with the project, even if it has been
# redacted, because we know it should equal that of the request.
resource["jobReference"] = job_ref_properties
job._properties = resource
return job | python | def from_api_repr(cls, resource, client):
"""Construct an UnknownJob from the JSON representation.
Args:
resource (dict): JSON representation of a job.
client (google.cloud.bigquery.client.Client):
Client connected to BigQuery API.
Returns:
UnknownJob: Job corresponding to the resource.
"""
job_ref_properties = resource.get("jobReference", {"projectId": client.project})
job_ref = _JobReference._from_api_repr(job_ref_properties)
job = cls(job_ref, client)
# Populate the job reference with the project, even if it has been
# redacted, because we know it should equal that of the request.
resource["jobReference"] = job_ref_properties
job._properties = resource
return job | [
"def",
"from_api_repr",
"(",
"cls",
",",
"resource",
",",
"client",
")",
":",
"job_ref_properties",
"=",
"resource",
".",
"get",
"(",
"\"jobReference\"",
",",
"{",
"\"projectId\"",
":",
"client",
".",
"project",
"}",
")",
"job_ref",
"=",
"_JobReference",
".",
"_from_api_repr",
"(",
"job_ref_properties",
")",
"job",
"=",
"cls",
"(",
"job_ref",
",",
"client",
")",
"# Populate the job reference with the project, even if it has been",
"# redacted, because we know it should equal that of the request.",
"resource",
"[",
"\"jobReference\"",
"]",
"=",
"job_ref_properties",
"job",
".",
"_properties",
"=",
"resource",
"return",
"job"
] | Construct an UnknownJob from the JSON representation.
Args:
resource (dict): JSON representation of a job.
client (google.cloud.bigquery.client.Client):
Client connected to BigQuery API.
Returns:
UnknownJob: Job corresponding to the resource. | [
"Construct",
"an",
"UnknownJob",
"from",
"the",
"JSON",
"representation",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/job.py#L3244-L3262 |
27,807 | googleapis/google-cloud-python | dns/google/cloud/dns/zone.py | ManagedZone.description | def description(self, value):
"""Update description of the zone.
:type value: str
:param value: (Optional) new description
:raises: ValueError for invalid value types.
"""
if not isinstance(value, six.string_types) and value is not None:
raise ValueError("Pass a string, or None")
self._properties["description"] = value | python | def description(self, value):
"""Update description of the zone.
:type value: str
:param value: (Optional) new description
:raises: ValueError for invalid value types.
"""
if not isinstance(value, six.string_types) and value is not None:
raise ValueError("Pass a string, or None")
self._properties["description"] = value | [
"def",
"description",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
"and",
"value",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Pass a string, or None\"",
")",
"self",
".",
"_properties",
"[",
"\"description\"",
"]",
"=",
"value"
] | Update description of the zone.
:type value: str
:param value: (Optional) new description
:raises: ValueError for invalid value types. | [
"Update",
"description",
"of",
"the",
"zone",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/zone.py#L138-L148 |
27,808 | googleapis/google-cloud-python | dns/google/cloud/dns/zone.py | ManagedZone.name_server_set | def name_server_set(self, value):
"""Update named set of DNS name servers.
:type value: str
:param value: (Optional) new title
:raises: ValueError for invalid value types.
"""
if not isinstance(value, six.string_types) and value is not None:
raise ValueError("Pass a string, or None")
self._properties["nameServerSet"] = value | python | def name_server_set(self, value):
"""Update named set of DNS name servers.
:type value: str
:param value: (Optional) new title
:raises: ValueError for invalid value types.
"""
if not isinstance(value, six.string_types) and value is not None:
raise ValueError("Pass a string, or None")
self._properties["nameServerSet"] = value | [
"def",
"name_server_set",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
"and",
"value",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Pass a string, or None\"",
")",
"self",
".",
"_properties",
"[",
"\"nameServerSet\"",
"]",
"=",
"value"
] | Update named set of DNS name servers.
:type value: str
:param value: (Optional) new title
:raises: ValueError for invalid value types. | [
"Update",
"named",
"set",
"of",
"DNS",
"name",
"servers",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/zone.py#L165-L175 |
27,809 | googleapis/google-cloud-python | dns/google/cloud/dns/zone.py | ManagedZone.resource_record_set | def resource_record_set(self, name, record_type, ttl, rrdatas):
"""Construct a resource record set bound to this zone.
:type name: str
:param name: Name of the record set.
:type record_type: str
:param record_type: RR type
:type ttl: int
:param ttl: TTL for the RR, in seconds
:type rrdatas: list of string
:param rrdatas: resource data for the RR
:rtype: :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`
:returns: a new ``ResourceRecordSet`` instance
"""
return ResourceRecordSet(name, record_type, ttl, rrdatas, zone=self) | python | def resource_record_set(self, name, record_type, ttl, rrdatas):
"""Construct a resource record set bound to this zone.
:type name: str
:param name: Name of the record set.
:type record_type: str
:param record_type: RR type
:type ttl: int
:param ttl: TTL for the RR, in seconds
:type rrdatas: list of string
:param rrdatas: resource data for the RR
:rtype: :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`
:returns: a new ``ResourceRecordSet`` instance
"""
return ResourceRecordSet(name, record_type, ttl, rrdatas, zone=self) | [
"def",
"resource_record_set",
"(",
"self",
",",
"name",
",",
"record_type",
",",
"ttl",
",",
"rrdatas",
")",
":",
"return",
"ResourceRecordSet",
"(",
"name",
",",
"record_type",
",",
"ttl",
",",
"rrdatas",
",",
"zone",
"=",
"self",
")"
] | Construct a resource record set bound to this zone.
:type name: str
:param name: Name of the record set.
:type record_type: str
:param record_type: RR type
:type ttl: int
:param ttl: TTL for the RR, in seconds
:type rrdatas: list of string
:param rrdatas: resource data for the RR
:rtype: :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`
:returns: a new ``ResourceRecordSet`` instance | [
"Construct",
"a",
"resource",
"record",
"set",
"bound",
"to",
"this",
"zone",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/zone.py#L177-L195 |
27,810 | googleapis/google-cloud-python | dns/google/cloud/dns/zone.py | ManagedZone._build_resource | def _build_resource(self):
"""Generate a resource for ``create`` or ``update``."""
resource = {"name": self.name}
if self.dns_name is not None:
resource["dnsName"] = self.dns_name
if self.description is not None:
resource["description"] = self.description
if self.name_server_set is not None:
resource["nameServerSet"] = self.name_server_set
return resource | python | def _build_resource(self):
"""Generate a resource for ``create`` or ``update``."""
resource = {"name": self.name}
if self.dns_name is not None:
resource["dnsName"] = self.dns_name
if self.description is not None:
resource["description"] = self.description
if self.name_server_set is not None:
resource["nameServerSet"] = self.name_server_set
return resource | [
"def",
"_build_resource",
"(",
"self",
")",
":",
"resource",
"=",
"{",
"\"name\"",
":",
"self",
".",
"name",
"}",
"if",
"self",
".",
"dns_name",
"is",
"not",
"None",
":",
"resource",
"[",
"\"dnsName\"",
"]",
"=",
"self",
".",
"dns_name",
"if",
"self",
".",
"description",
"is",
"not",
"None",
":",
"resource",
"[",
"\"description\"",
"]",
"=",
"self",
".",
"description",
"if",
"self",
".",
"name_server_set",
"is",
"not",
"None",
":",
"resource",
"[",
"\"nameServerSet\"",
"]",
"=",
"self",
".",
"name_server_set",
"return",
"resource"
] | Generate a resource for ``create`` or ``update``. | [
"Generate",
"a",
"resource",
"for",
"create",
"or",
"update",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/zone.py#L233-L246 |
27,811 | googleapis/google-cloud-python | dns/google/cloud/dns/zone.py | ManagedZone.list_resource_record_sets | def list_resource_record_sets(self, max_results=None, page_token=None, client=None):
"""List resource record sets for this zone.
See
https://cloud.google.com/dns/api/v1/resourceRecordSets/list
:type max_results: int
:param max_results: Optional. The maximum number of resource record
sets to return. Defaults to a sensible value
set by the API.
:type page_token: str
:param page_token: Optional. If present, return the next batch of
resource record sets, using the value, which must correspond to
the ``nextPageToken`` value returned in the previous response.
Deprecated: use the ``pages`` property of the returned iterator
instead of manually passing the token.
:type client: :class:`google.cloud.dns.client.Client`
:param client:
(Optional) the client to use. If not passed, falls back to the
``client`` stored on the current zone.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of :class:`~.resource_record_set.ResourceRecordSet`
belonging to this zone.
"""
client = self._require_client(client)
path = "/projects/%s/managedZones/%s/rrsets" % (self.project, self.name)
iterator = page_iterator.HTTPIterator(
client=client,
api_request=client._connection.api_request,
path=path,
item_to_value=_item_to_resource_record_set,
items_key="rrsets",
page_token=page_token,
max_results=max_results,
)
iterator.zone = self
return iterator | python | def list_resource_record_sets(self, max_results=None, page_token=None, client=None):
"""List resource record sets for this zone.
See
https://cloud.google.com/dns/api/v1/resourceRecordSets/list
:type max_results: int
:param max_results: Optional. The maximum number of resource record
sets to return. Defaults to a sensible value
set by the API.
:type page_token: str
:param page_token: Optional. If present, return the next batch of
resource record sets, using the value, which must correspond to
the ``nextPageToken`` value returned in the previous response.
Deprecated: use the ``pages`` property of the returned iterator
instead of manually passing the token.
:type client: :class:`google.cloud.dns.client.Client`
:param client:
(Optional) the client to use. If not passed, falls back to the
``client`` stored on the current zone.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of :class:`~.resource_record_set.ResourceRecordSet`
belonging to this zone.
"""
client = self._require_client(client)
path = "/projects/%s/managedZones/%s/rrsets" % (self.project, self.name)
iterator = page_iterator.HTTPIterator(
client=client,
api_request=client._connection.api_request,
path=path,
item_to_value=_item_to_resource_record_set,
items_key="rrsets",
page_token=page_token,
max_results=max_results,
)
iterator.zone = self
return iterator | [
"def",
"list_resource_record_sets",
"(",
"self",
",",
"max_results",
"=",
"None",
",",
"page_token",
"=",
"None",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"path",
"=",
"\"/projects/%s/managedZones/%s/rrsets\"",
"%",
"(",
"self",
".",
"project",
",",
"self",
".",
"name",
")",
"iterator",
"=",
"page_iterator",
".",
"HTTPIterator",
"(",
"client",
"=",
"client",
",",
"api_request",
"=",
"client",
".",
"_connection",
".",
"api_request",
",",
"path",
"=",
"path",
",",
"item_to_value",
"=",
"_item_to_resource_record_set",
",",
"items_key",
"=",
"\"rrsets\"",
",",
"page_token",
"=",
"page_token",
",",
"max_results",
"=",
"max_results",
",",
")",
"iterator",
".",
"zone",
"=",
"self",
"return",
"iterator"
] | List resource record sets for this zone.
See
https://cloud.google.com/dns/api/v1/resourceRecordSets/list
:type max_results: int
:param max_results: Optional. The maximum number of resource record
sets to return. Defaults to a sensible value
set by the API.
:type page_token: str
:param page_token: Optional. If present, return the next batch of
resource record sets, using the value, which must correspond to
the ``nextPageToken`` value returned in the previous response.
Deprecated: use the ``pages`` property of the returned iterator
instead of manually passing the token.
:type client: :class:`google.cloud.dns.client.Client`
:param client:
(Optional) the client to use. If not passed, falls back to the
``client`` stored on the current zone.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of :class:`~.resource_record_set.ResourceRecordSet`
belonging to this zone. | [
"List",
"resource",
"record",
"sets",
"for",
"this",
"zone",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/zone.py#L319-L358 |
27,812 | googleapis/google-cloud-python | vision/google/cloud/vision_helpers/__init__.py | VisionHelpers.annotate_image | def annotate_image(self, request, retry=None, timeout=None):
"""Run image detection and annotation for an image.
Example:
>>> from google.cloud.vision_v1 import ImageAnnotatorClient
>>> client = ImageAnnotatorClient()
>>> request = {
... 'image': {
... 'source': {'image_uri': 'https://foo.com/image.jpg'},
... },
... }
>>> response = client.annotate_image(request)
Args:
request (:class:`~.vision_v1.types.AnnotateImageRequest`)
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
Returns:
:class:`~.vision_v1.types.AnnotateImageResponse` The API response.
"""
# If the image is a file handler, set the content.
image = protobuf.get(request, "image")
if hasattr(image, "read"):
img_bytes = image.read()
protobuf.set(request, "image", {})
protobuf.set(request, "image.content", img_bytes)
image = protobuf.get(request, "image")
# If a filename is provided, read the file.
filename = protobuf.get(image, "source.filename", default=None)
if filename:
with io.open(filename, "rb") as img_file:
protobuf.set(request, "image.content", img_file.read())
protobuf.set(request, "image.source", None)
# This method allows features not to be specified, and you get all
# of them.
protobuf.setdefault(request, "features", self._get_all_features())
r = self.batch_annotate_images([request], retry=retry, timeout=timeout)
return r.responses[0] | python | def annotate_image(self, request, retry=None, timeout=None):
"""Run image detection and annotation for an image.
Example:
>>> from google.cloud.vision_v1 import ImageAnnotatorClient
>>> client = ImageAnnotatorClient()
>>> request = {
... 'image': {
... 'source': {'image_uri': 'https://foo.com/image.jpg'},
... },
... }
>>> response = client.annotate_image(request)
Args:
request (:class:`~.vision_v1.types.AnnotateImageRequest`)
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
Returns:
:class:`~.vision_v1.types.AnnotateImageResponse` The API response.
"""
# If the image is a file handler, set the content.
image = protobuf.get(request, "image")
if hasattr(image, "read"):
img_bytes = image.read()
protobuf.set(request, "image", {})
protobuf.set(request, "image.content", img_bytes)
image = protobuf.get(request, "image")
# If a filename is provided, read the file.
filename = protobuf.get(image, "source.filename", default=None)
if filename:
with io.open(filename, "rb") as img_file:
protobuf.set(request, "image.content", img_file.read())
protobuf.set(request, "image.source", None)
# This method allows features not to be specified, and you get all
# of them.
protobuf.setdefault(request, "features", self._get_all_features())
r = self.batch_annotate_images([request], retry=retry, timeout=timeout)
return r.responses[0] | [
"def",
"annotate_image",
"(",
"self",
",",
"request",
",",
"retry",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"# If the image is a file handler, set the content.",
"image",
"=",
"protobuf",
".",
"get",
"(",
"request",
",",
"\"image\"",
")",
"if",
"hasattr",
"(",
"image",
",",
"\"read\"",
")",
":",
"img_bytes",
"=",
"image",
".",
"read",
"(",
")",
"protobuf",
".",
"set",
"(",
"request",
",",
"\"image\"",
",",
"{",
"}",
")",
"protobuf",
".",
"set",
"(",
"request",
",",
"\"image.content\"",
",",
"img_bytes",
")",
"image",
"=",
"protobuf",
".",
"get",
"(",
"request",
",",
"\"image\"",
")",
"# If a filename is provided, read the file.",
"filename",
"=",
"protobuf",
".",
"get",
"(",
"image",
",",
"\"source.filename\"",
",",
"default",
"=",
"None",
")",
"if",
"filename",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"img_file",
":",
"protobuf",
".",
"set",
"(",
"request",
",",
"\"image.content\"",
",",
"img_file",
".",
"read",
"(",
")",
")",
"protobuf",
".",
"set",
"(",
"request",
",",
"\"image.source\"",
",",
"None",
")",
"# This method allows features not to be specified, and you get all",
"# of them.",
"protobuf",
".",
"setdefault",
"(",
"request",
",",
"\"features\"",
",",
"self",
".",
"_get_all_features",
"(",
")",
")",
"r",
"=",
"self",
".",
"batch_annotate_images",
"(",
"[",
"request",
"]",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
")",
"return",
"r",
".",
"responses",
"[",
"0",
"]"
] | Run image detection and annotation for an image.
Example:
>>> from google.cloud.vision_v1 import ImageAnnotatorClient
>>> client = ImageAnnotatorClient()
>>> request = {
... 'image': {
... 'source': {'image_uri': 'https://foo.com/image.jpg'},
... },
... }
>>> response = client.annotate_image(request)
Args:
request (:class:`~.vision_v1.types.AnnotateImageRequest`)
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
Returns:
:class:`~.vision_v1.types.AnnotateImageResponse` The API response. | [
"Run",
"image",
"detection",
"and",
"annotation",
"for",
"an",
"image",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/vision/google/cloud/vision_helpers/__init__.py#L29-L73 |
27,813 | googleapis/google-cloud-python | talent/google/cloud/talent_v4beta1/gapic/job_service_client.py | JobServiceClient.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 new job.
Typically, the job becomes searchable within 10 seconds, but it may take
up to 5 minutes.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `job`:
>>> job = {}
>>>
>>> response = client.create_job(parent, job)
Args:
parent (str): Required.
The resource name of the project under which the job is created.
The format is "projects/{project\_id}", for example,
"projects/api-test-project".
job (Union[dict, ~google.cloud.talent_v4beta1.types.Job]): Required.
The Job to be created.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.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.talent_v4beta1.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 = job_service_pb2.CreateJobRequest(parent=parent, job=job)
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 new job.
Typically, the job becomes searchable within 10 seconds, but it may take
up to 5 minutes.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `job`:
>>> job = {}
>>>
>>> response = client.create_job(parent, job)
Args:
parent (str): Required.
The resource name of the project under which the job is created.
The format is "projects/{project\_id}", for example,
"projects/api-test-project".
job (Union[dict, ~google.cloud.talent_v4beta1.types.Job]): Required.
The Job to be created.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.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.talent_v4beta1.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 = job_service_pb2.CreateJobRequest(parent=parent, job=job)
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",
"=",
"job_service_pb2",
".",
"CreateJobRequest",
"(",
"parent",
"=",
"parent",
",",
"job",
"=",
"job",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"create_job\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Creates a new job.
Typically, the job becomes searchable within 10 seconds, but it may take
up to 5 minutes.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `job`:
>>> job = {}
>>>
>>> response = client.create_job(parent, job)
Args:
parent (str): Required.
The resource name of the project under which the job is created.
The format is "projects/{project\_id}", for example,
"projects/api-test-project".
job (Union[dict, ~google.cloud.talent_v4beta1.types.Job]): Required.
The Job to be created.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.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.talent_v4beta1.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",
"new",
"job",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/job_service_client.py#L197-L269 |
27,814 | googleapis/google-cloud-python | talent/google/cloud/talent_v4beta1/gapic/job_service_client.py | JobServiceClient.get_job | def get_job(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Retrieves the specified job, whose status is OPEN or recently EXPIRED
within the last 90 days.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> name = client.job_path('[PROJECT]', '[JOBS]')
>>>
>>> response = client.get_job(name)
Args:
name (str): Required.
The resource name of the job to retrieve.
The format is "projects/{project\_id}/jobs/{job\_id}", for example,
"projects/api-test-project/jobs/1234".
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.talent_v4beta1.types.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 "get_job" not in self._inner_api_calls:
self._inner_api_calls[
"get_job"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_job,
default_retry=self._method_configs["GetJob"].retry,
default_timeout=self._method_configs["GetJob"].timeout,
client_info=self._client_info,
)
request = job_service_pb2.GetJobRequest(name=name)
return self._inner_api_calls["get_job"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def get_job(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Retrieves the specified job, whose status is OPEN or recently EXPIRED
within the last 90 days.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> name = client.job_path('[PROJECT]', '[JOBS]')
>>>
>>> response = client.get_job(name)
Args:
name (str): Required.
The resource name of the job to retrieve.
The format is "projects/{project\_id}/jobs/{job\_id}", for example,
"projects/api-test-project/jobs/1234".
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.talent_v4beta1.types.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 "get_job" not in self._inner_api_calls:
self._inner_api_calls[
"get_job"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_job,
default_retry=self._method_configs["GetJob"].retry,
default_timeout=self._method_configs["GetJob"].timeout,
client_info=self._client_info,
)
request = job_service_pb2.GetJobRequest(name=name)
return self._inner_api_calls["get_job"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"get_job",
"(",
"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",
"\"get_job\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"get_job\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"get_job",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"GetJob\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"GetJob\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"job_service_pb2",
".",
"GetJobRequest",
"(",
"name",
"=",
"name",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"get_job\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Retrieves the specified job, whose status is OPEN or recently EXPIRED
within the last 90 days.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> name = client.job_path('[PROJECT]', '[JOBS]')
>>>
>>> response = client.get_job(name)
Args:
name (str): Required.
The resource name of the job to retrieve.
The format is "projects/{project\_id}/jobs/{job\_id}", for example,
"projects/api-test-project/jobs/1234".
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.talent_v4beta1.types.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. | [
"Retrieves",
"the",
"specified",
"job",
"whose",
"status",
"is",
"OPEN",
"or",
"recently",
"EXPIRED",
"within",
"the",
"last",
"90",
"days",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/job_service_client.py#L271-L331 |
27,815 | googleapis/google-cloud-python | talent/google/cloud/talent_v4beta1/gapic/job_service_client.py | JobServiceClient.batch_delete_jobs | def batch_delete_jobs(
self,
parent,
filter_,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a list of ``Job``\ s by filter.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `filter_`:
>>> filter_ = ''
>>>
>>> client.batch_delete_jobs(parent, filter_)
Args:
parent (str): Required.
The resource name of the project under which the job is created.
The format is "projects/{project\_id}", for example,
"projects/api-test-project".
filter_ (str): Required.
The filter string specifies the jobs to be deleted.
Supported operator: =, AND
The fields eligible for filtering are:
- ``companyName`` (Required)
- ``requisitionId`` (Required)
Sample Query: companyName = "projects/api-test-project/companies/123"
AND requisitionId = "req-1"
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.
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_delete_jobs" not in self._inner_api_calls:
self._inner_api_calls[
"batch_delete_jobs"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.batch_delete_jobs,
default_retry=self._method_configs["BatchDeleteJobs"].retry,
default_timeout=self._method_configs["BatchDeleteJobs"].timeout,
client_info=self._client_info,
)
request = job_service_pb2.BatchDeleteJobsRequest(parent=parent, filter=filter_)
self._inner_api_calls["batch_delete_jobs"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def batch_delete_jobs(
self,
parent,
filter_,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a list of ``Job``\ s by filter.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `filter_`:
>>> filter_ = ''
>>>
>>> client.batch_delete_jobs(parent, filter_)
Args:
parent (str): Required.
The resource name of the project under which the job is created.
The format is "projects/{project\_id}", for example,
"projects/api-test-project".
filter_ (str): Required.
The filter string specifies the jobs to be deleted.
Supported operator: =, AND
The fields eligible for filtering are:
- ``companyName`` (Required)
- ``requisitionId`` (Required)
Sample Query: companyName = "projects/api-test-project/companies/123"
AND requisitionId = "req-1"
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.
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_delete_jobs" not in self._inner_api_calls:
self._inner_api_calls[
"batch_delete_jobs"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.batch_delete_jobs,
default_retry=self._method_configs["BatchDeleteJobs"].retry,
default_timeout=self._method_configs["BatchDeleteJobs"].timeout,
client_info=self._client_info,
)
request = job_service_pb2.BatchDeleteJobsRequest(parent=parent, filter=filter_)
self._inner_api_calls["batch_delete_jobs"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"batch_delete_jobs",
"(",
"self",
",",
"parent",
",",
"filter_",
",",
"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_delete_jobs\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"batch_delete_jobs\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"batch_delete_jobs",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"BatchDeleteJobs\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"BatchDeleteJobs\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"job_service_pb2",
".",
"BatchDeleteJobsRequest",
"(",
"parent",
"=",
"parent",
",",
"filter",
"=",
"filter_",
")",
"self",
".",
"_inner_api_calls",
"[",
"\"batch_delete_jobs\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Deletes a list of ``Job``\ s by filter.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `filter_`:
>>> filter_ = ''
>>>
>>> client.batch_delete_jobs(parent, filter_)
Args:
parent (str): Required.
The resource name of the project under which the job is created.
The format is "projects/{project\_id}", for example,
"projects/api-test-project".
filter_ (str): Required.
The filter string specifies the jobs to be deleted.
Supported operator: =, AND
The fields eligible for filtering are:
- ``companyName`` (Required)
- ``requisitionId`` (Required)
Sample Query: companyName = "projects/api-test-project/companies/123"
AND requisitionId = "req-1"
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.
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",
"list",
"of",
"Job",
"\\",
"s",
"by",
"filter",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/job_service_client.py#L595-L668 |
27,816 | googleapis/google-cloud-python | talent/google/cloud/talent_v4beta1/gapic/job_service_client.py | JobServiceClient.search_jobs | def search_jobs(
self,
parent,
request_metadata,
search_mode=None,
job_query=None,
enable_broadening=None,
require_precise_result_size=None,
histogram_queries=None,
job_view=None,
offset=None,
page_size=None,
order_by=None,
diversification_level=None,
custom_ranking_info=None,
disable_keyword_match=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Searches for jobs using the provided ``SearchJobsRequest``.
This call constrains the ``visibility`` of jobs present in the database,
and only returns jobs that the caller has permission to search against.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `request_metadata`:
>>> request_metadata = {}
>>>
>>> # Iterate over all results
>>> for element in client.search_jobs(parent, request_metadata):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.search_jobs(parent, request_metadata).pages:
... for element in page:
... # process element
... pass
Args:
parent (str): Required.
The resource name of the project to search within.
The format is "projects/{project\_id}", for example,
"projects/api-test-project".
request_metadata (Union[dict, ~google.cloud.talent_v4beta1.types.RequestMetadata]): Required.
The meta information collected about the job searcher, used to improve
the search quality of the service.. The identifiers, (such as
``user_id``) are provided by users, and must be unique and consistent.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.RequestMetadata`
search_mode (~google.cloud.talent_v4beta1.types.SearchMode): Optional.
Mode of a search.
Defaults to ``SearchMode.JOB_SEARCH``.
job_query (Union[dict, ~google.cloud.talent_v4beta1.types.JobQuery]): Optional.
Query used to search against jobs, such as keyword, location filters, etc.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.JobQuery`
enable_broadening (bool): Optional.
Controls whether to broaden the search when it produces sparse results.
Broadened queries append results to the end of the matching results
list.
Defaults to false.
require_precise_result_size (bool): Optional.
Controls if the search job request requires the return of a precise
count of the first 300 results. Setting this to ``true`` ensures
consistency in the number of results per page. Best practice is to set
this value to true if a client allows users to jump directly to a
non-sequential search results page.
Enabling this flag may adversely impact performance.
Defaults to false.
histogram_queries (list[Union[dict, ~google.cloud.talent_v4beta1.types.HistogramQuery]]): Optional.
An expression specifies a histogram request against matching jobs.
Expression syntax is an aggregation function call with histogram facets
and other options.
Available aggregation function calls are: \*
``count(string_histogram_facet)``: Count the number of matching
entities, for each distinct attribute value. \*
``count(numeric_histogram_facet, list of buckets)``: Count the number of
matching entities within each bucket.
Data types:
- Histogram facet: facet names with format [a-zA-Z][a-zA-Z0-9\_]+.
- String: string like "any string with backslash escape for quote(")."
- Number: whole number and floating point number like 10, -1 and -0.01.
- List: list of elements with comma(,) separator surrounded by square
brackets, for example, [1, 2, 3] and ["one", "two", "three"].
Built-in constants:
- MIN (minimum number similar to java Double.MIN\_VALUE)
- MAX (maximum number similar to java Double.MAX\_VALUE)
Built-in functions:
- bucket(start, end[, label]): bucket built-in function creates a
bucket with range of \`start, end). Note that the end is exclusive,
for example, bucket(1, MAX, "positive number") or bucket(1, 10).
Job histogram facets:
- company\_id: histogram by [Job.distributor\_company\_id\`.
- company\_display\_name: histogram by ``Job.company_display_name``.
- employment\_type: histogram by ``Job.employment_types``, for example,
"FULL\_TIME", "PART\_TIME".
- company\_size: histogram by ``CompanySize``, for example, "SMALL",
"MEDIUM", "BIG".
- publish\_time\_in\_month: histogram by the ``Job.publish_time`` in
months. Must specify list of numeric buckets in spec.
- publish\_time\_in\_year: histogram by the ``Job.publish_time`` in
years. Must specify list of numeric buckets in spec.
- degree\_type: histogram by the ``Job.degree_type``, for example,
"Bachelors", "Masters".
- job\_level: histogram by the ``Job.job_level``, for example, "Entry
Level".
- country: histogram by the country code of jobs, for example, "US",
"FR".
- admin1: histogram by the admin1 code of jobs, which is a global
placeholder referring to the state, province, or the particular term
a country uses to define the geographic structure below the country
level, for example, "CA", "IL".
- city: histogram by a combination of the "city name, admin1 code". For
example, "Mountain View, CA", "New York, NY".
- admin1\_country: histogram by a combination of the "admin1 code,
country", for example, "CA, US", "IL, US".
- city\_coordinate: histogram by the city center's GPS coordinates
(latitude and longitude), for example, 37.4038522,-122.0987765. Since
the coordinates of a city center can change, customers may need to
refresh them periodically.
- locale: histogram by the ``Job.language_code``, for example, "en-US",
"fr-FR".
- language: histogram by the language subtag of the
``Job.language_code``, for example, "en", "fr".
- category: histogram by the ``JobCategory``, for example,
"COMPUTER\_AND\_IT", "HEALTHCARE".
- base\_compensation\_unit: histogram by the ``CompensationUnit`` of
base salary, for example, "WEEKLY", "MONTHLY".
- base\_compensation: histogram by the base salary. Must specify list
of numeric buckets to group results by.
- annualized\_base\_compensation: histogram by the base annualized
salary. Must specify list of numeric buckets to group results by.
- annualized\_total\_compensation: histogram by the total annualized
salary. Must specify list of numeric buckets to group results by.
- string\_custom\_attribute: histogram by string
``Job.custom_attributes``. Values can be accessed via square bracket
notations like string\_custom\_attribute["key1"].
- numeric\_custom\_attribute: histogram by numeric
``Job.custom_attributes``. Values can be accessed via square bracket
notations like numeric\_custom\_attribute["key1"]. Must specify list
of numeric buckets to group results by.
Example expressions: \* count(admin1) \* count(base\_compensation,
[bucket(1000, 10000), bucket(10000, 100000), bucket(100000, MAX)]) \*
count(string\_custom\_attribute["some-string-custom-attribute"]) \*
count(numeric\_custom\_attribute["some-numeric-custom-attribute"],
[bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative"])
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.HistogramQuery`
job_view (~google.cloud.talent_v4beta1.types.JobView): Optional.
The desired job attributes returned for jobs in the search response.
Defaults to ``JobView.SMALL`` if no value is specified.
offset (int): Optional.
An integer that specifies the current offset (that is, starting result
location, amongst the jobs deemed by the API as relevant) in search
results. This field is only considered if ``page_token`` is unset.
For example, 0 means to return results starting from the first matching
job, and 10 means to return from the 11th job. This can be used for
pagination, (for example, pageSize = 10 and offset = 10 means to return
from the second page).
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): Optional.
The criteria determining how search results are sorted. Default is
"relevance desc".
Supported options are:
- "relevance desc": By relevance descending, as determined by the API
algorithms. Relevance thresholding of query results is only available
with this ordering.
- "posting``_``\ publish\ ``_``\ time desc": By
``Job.posting_publish_time`` descending.
- "posting``_``\ update\ ``_``\ time desc": By
``Job.posting_update_time`` descending.
- "title": By ``Job.title`` ascending.
- "title desc": By ``Job.title`` descending.
- "annualized``_``\ base\ ``_``\ compensation": By job's
``CompensationInfo.annualized_base_compensation_range`` ascending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "annualized``_``\ base\ ``_``\ compensation desc": By job's
``CompensationInfo.annualized_base_compensation_range`` descending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "annualized``_``\ total\ ``_``\ compensation": By job's
``CompensationInfo.annualized_total_compensation_range`` ascending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "annualized``_``\ total\ ``_``\ compensation desc": By job's
``CompensationInfo.annualized_total_compensation_range`` descending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "custom``_``\ ranking desc": By the relevance score adjusted to the
``SearchJobsRequest.custom_ranking_info.ranking_expression`` with
weight factor assigned by
``SearchJobsRequest.custom_ranking_info.importance_level`` in
descending order.
- "location``_``\ distance": By the distance between the location on
jobs and locations specified in the
``SearchJobsRequest.job_query.location_filters``. When this order is
selected, the ``SearchJobsRequest.job_query.location_filters`` must
not be empty. When a job has multiple locations, the location closest
to one of the locations specified in the location filter will be used
to calculate location distance. Distance is calculated by the
distance between two lat/long coordinates, with a precision of 10e-4
degrees (11.3 meters). Jobs that don't have locations specified will
be ranked below jobs having locations. Diversification strategy is
still applied unless explicitly disabled in
``SearchJobsRequest.diversification_level``.
diversification_level (~google.cloud.talent_v4beta1.types.DiversificationLevel): Optional.
Controls whether highly similar jobs are returned next to each other in
the search results. Jobs are identified as highly similar based on their
titles, job categories, and locations. Highly similar results are
clustered so that only one representative job of the cluster is
displayed to the job seeker higher up in the results, with the other
jobs being displayed lower down in the results.
Defaults to ``DiversificationLevel.SIMPLE`` if no value is specified.
custom_ranking_info (Union[dict, ~google.cloud.talent_v4beta1.types.CustomRankingInfo]): Optional.
Controls over how job documents get ranked on top of existing relevance
score (determined by API algorithm).
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.CustomRankingInfo`
disable_keyword_match (bool): Optional.
Controls whether to disable exact keyword match on ``Job.job_title``,
``Job.description``, ``Job.company_display_name``, [Job.locations][0],
``Job.qualifications``. When disable keyword match is turned off, a
keyword match returns jobs that do not match given category filters when
there are matching keywords. For example, for the query "program
manager," a result is returned even if the job posting has the title
"software developer," which doesn't fall into "program manager"
ontology, but does have "program manager" appearing in its description.
For queries like "cloud" that don't contain title or location specific
ontology, jobs with "cloud" keyword matches are returned regardless of
this flag's value.
Please use ``Company.keyword_searchable_custom_fields`` or
``Company.keyword_searchable_custom_attributes`` if company specific
globally matched custom field/attribute string values is needed.
Enabling keyword match improves recall of subsequent search requests.
Defaults to false.
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.talent_v4beta1.types.MatchingJob` 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 "search_jobs" not in self._inner_api_calls:
self._inner_api_calls[
"search_jobs"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.search_jobs,
default_retry=self._method_configs["SearchJobs"].retry,
default_timeout=self._method_configs["SearchJobs"].timeout,
client_info=self._client_info,
)
request = job_service_pb2.SearchJobsRequest(
parent=parent,
request_metadata=request_metadata,
search_mode=search_mode,
job_query=job_query,
enable_broadening=enable_broadening,
require_precise_result_size=require_precise_result_size,
histogram_queries=histogram_queries,
job_view=job_view,
offset=offset,
page_size=page_size,
order_by=order_by,
diversification_level=diversification_level,
custom_ranking_info=custom_ranking_info,
disable_keyword_match=disable_keyword_match,
)
iterator = google.api_core.page_iterator.GRPCIterator(
client=None,
method=functools.partial(
self._inner_api_calls["search_jobs"],
retry=retry,
timeout=timeout,
metadata=metadata,
),
request=request,
items_field="matching_jobs",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | python | def search_jobs(
self,
parent,
request_metadata,
search_mode=None,
job_query=None,
enable_broadening=None,
require_precise_result_size=None,
histogram_queries=None,
job_view=None,
offset=None,
page_size=None,
order_by=None,
diversification_level=None,
custom_ranking_info=None,
disable_keyword_match=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Searches for jobs using the provided ``SearchJobsRequest``.
This call constrains the ``visibility`` of jobs present in the database,
and only returns jobs that the caller has permission to search against.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `request_metadata`:
>>> request_metadata = {}
>>>
>>> # Iterate over all results
>>> for element in client.search_jobs(parent, request_metadata):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.search_jobs(parent, request_metadata).pages:
... for element in page:
... # process element
... pass
Args:
parent (str): Required.
The resource name of the project to search within.
The format is "projects/{project\_id}", for example,
"projects/api-test-project".
request_metadata (Union[dict, ~google.cloud.talent_v4beta1.types.RequestMetadata]): Required.
The meta information collected about the job searcher, used to improve
the search quality of the service.. The identifiers, (such as
``user_id``) are provided by users, and must be unique and consistent.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.RequestMetadata`
search_mode (~google.cloud.talent_v4beta1.types.SearchMode): Optional.
Mode of a search.
Defaults to ``SearchMode.JOB_SEARCH``.
job_query (Union[dict, ~google.cloud.talent_v4beta1.types.JobQuery]): Optional.
Query used to search against jobs, such as keyword, location filters, etc.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.JobQuery`
enable_broadening (bool): Optional.
Controls whether to broaden the search when it produces sparse results.
Broadened queries append results to the end of the matching results
list.
Defaults to false.
require_precise_result_size (bool): Optional.
Controls if the search job request requires the return of a precise
count of the first 300 results. Setting this to ``true`` ensures
consistency in the number of results per page. Best practice is to set
this value to true if a client allows users to jump directly to a
non-sequential search results page.
Enabling this flag may adversely impact performance.
Defaults to false.
histogram_queries (list[Union[dict, ~google.cloud.talent_v4beta1.types.HistogramQuery]]): Optional.
An expression specifies a histogram request against matching jobs.
Expression syntax is an aggregation function call with histogram facets
and other options.
Available aggregation function calls are: \*
``count(string_histogram_facet)``: Count the number of matching
entities, for each distinct attribute value. \*
``count(numeric_histogram_facet, list of buckets)``: Count the number of
matching entities within each bucket.
Data types:
- Histogram facet: facet names with format [a-zA-Z][a-zA-Z0-9\_]+.
- String: string like "any string with backslash escape for quote(")."
- Number: whole number and floating point number like 10, -1 and -0.01.
- List: list of elements with comma(,) separator surrounded by square
brackets, for example, [1, 2, 3] and ["one", "two", "three"].
Built-in constants:
- MIN (minimum number similar to java Double.MIN\_VALUE)
- MAX (maximum number similar to java Double.MAX\_VALUE)
Built-in functions:
- bucket(start, end[, label]): bucket built-in function creates a
bucket with range of \`start, end). Note that the end is exclusive,
for example, bucket(1, MAX, "positive number") or bucket(1, 10).
Job histogram facets:
- company\_id: histogram by [Job.distributor\_company\_id\`.
- company\_display\_name: histogram by ``Job.company_display_name``.
- employment\_type: histogram by ``Job.employment_types``, for example,
"FULL\_TIME", "PART\_TIME".
- company\_size: histogram by ``CompanySize``, for example, "SMALL",
"MEDIUM", "BIG".
- publish\_time\_in\_month: histogram by the ``Job.publish_time`` in
months. Must specify list of numeric buckets in spec.
- publish\_time\_in\_year: histogram by the ``Job.publish_time`` in
years. Must specify list of numeric buckets in spec.
- degree\_type: histogram by the ``Job.degree_type``, for example,
"Bachelors", "Masters".
- job\_level: histogram by the ``Job.job_level``, for example, "Entry
Level".
- country: histogram by the country code of jobs, for example, "US",
"FR".
- admin1: histogram by the admin1 code of jobs, which is a global
placeholder referring to the state, province, or the particular term
a country uses to define the geographic structure below the country
level, for example, "CA", "IL".
- city: histogram by a combination of the "city name, admin1 code". For
example, "Mountain View, CA", "New York, NY".
- admin1\_country: histogram by a combination of the "admin1 code,
country", for example, "CA, US", "IL, US".
- city\_coordinate: histogram by the city center's GPS coordinates
(latitude and longitude), for example, 37.4038522,-122.0987765. Since
the coordinates of a city center can change, customers may need to
refresh them periodically.
- locale: histogram by the ``Job.language_code``, for example, "en-US",
"fr-FR".
- language: histogram by the language subtag of the
``Job.language_code``, for example, "en", "fr".
- category: histogram by the ``JobCategory``, for example,
"COMPUTER\_AND\_IT", "HEALTHCARE".
- base\_compensation\_unit: histogram by the ``CompensationUnit`` of
base salary, for example, "WEEKLY", "MONTHLY".
- base\_compensation: histogram by the base salary. Must specify list
of numeric buckets to group results by.
- annualized\_base\_compensation: histogram by the base annualized
salary. Must specify list of numeric buckets to group results by.
- annualized\_total\_compensation: histogram by the total annualized
salary. Must specify list of numeric buckets to group results by.
- string\_custom\_attribute: histogram by string
``Job.custom_attributes``. Values can be accessed via square bracket
notations like string\_custom\_attribute["key1"].
- numeric\_custom\_attribute: histogram by numeric
``Job.custom_attributes``. Values can be accessed via square bracket
notations like numeric\_custom\_attribute["key1"]. Must specify list
of numeric buckets to group results by.
Example expressions: \* count(admin1) \* count(base\_compensation,
[bucket(1000, 10000), bucket(10000, 100000), bucket(100000, MAX)]) \*
count(string\_custom\_attribute["some-string-custom-attribute"]) \*
count(numeric\_custom\_attribute["some-numeric-custom-attribute"],
[bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative"])
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.HistogramQuery`
job_view (~google.cloud.talent_v4beta1.types.JobView): Optional.
The desired job attributes returned for jobs in the search response.
Defaults to ``JobView.SMALL`` if no value is specified.
offset (int): Optional.
An integer that specifies the current offset (that is, starting result
location, amongst the jobs deemed by the API as relevant) in search
results. This field is only considered if ``page_token`` is unset.
For example, 0 means to return results starting from the first matching
job, and 10 means to return from the 11th job. This can be used for
pagination, (for example, pageSize = 10 and offset = 10 means to return
from the second page).
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): Optional.
The criteria determining how search results are sorted. Default is
"relevance desc".
Supported options are:
- "relevance desc": By relevance descending, as determined by the API
algorithms. Relevance thresholding of query results is only available
with this ordering.
- "posting``_``\ publish\ ``_``\ time desc": By
``Job.posting_publish_time`` descending.
- "posting``_``\ update\ ``_``\ time desc": By
``Job.posting_update_time`` descending.
- "title": By ``Job.title`` ascending.
- "title desc": By ``Job.title`` descending.
- "annualized``_``\ base\ ``_``\ compensation": By job's
``CompensationInfo.annualized_base_compensation_range`` ascending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "annualized``_``\ base\ ``_``\ compensation desc": By job's
``CompensationInfo.annualized_base_compensation_range`` descending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "annualized``_``\ total\ ``_``\ compensation": By job's
``CompensationInfo.annualized_total_compensation_range`` ascending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "annualized``_``\ total\ ``_``\ compensation desc": By job's
``CompensationInfo.annualized_total_compensation_range`` descending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "custom``_``\ ranking desc": By the relevance score adjusted to the
``SearchJobsRequest.custom_ranking_info.ranking_expression`` with
weight factor assigned by
``SearchJobsRequest.custom_ranking_info.importance_level`` in
descending order.
- "location``_``\ distance": By the distance between the location on
jobs and locations specified in the
``SearchJobsRequest.job_query.location_filters``. When this order is
selected, the ``SearchJobsRequest.job_query.location_filters`` must
not be empty. When a job has multiple locations, the location closest
to one of the locations specified in the location filter will be used
to calculate location distance. Distance is calculated by the
distance between two lat/long coordinates, with a precision of 10e-4
degrees (11.3 meters). Jobs that don't have locations specified will
be ranked below jobs having locations. Diversification strategy is
still applied unless explicitly disabled in
``SearchJobsRequest.diversification_level``.
diversification_level (~google.cloud.talent_v4beta1.types.DiversificationLevel): Optional.
Controls whether highly similar jobs are returned next to each other in
the search results. Jobs are identified as highly similar based on their
titles, job categories, and locations. Highly similar results are
clustered so that only one representative job of the cluster is
displayed to the job seeker higher up in the results, with the other
jobs being displayed lower down in the results.
Defaults to ``DiversificationLevel.SIMPLE`` if no value is specified.
custom_ranking_info (Union[dict, ~google.cloud.talent_v4beta1.types.CustomRankingInfo]): Optional.
Controls over how job documents get ranked on top of existing relevance
score (determined by API algorithm).
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.CustomRankingInfo`
disable_keyword_match (bool): Optional.
Controls whether to disable exact keyword match on ``Job.job_title``,
``Job.description``, ``Job.company_display_name``, [Job.locations][0],
``Job.qualifications``. When disable keyword match is turned off, a
keyword match returns jobs that do not match given category filters when
there are matching keywords. For example, for the query "program
manager," a result is returned even if the job posting has the title
"software developer," which doesn't fall into "program manager"
ontology, but does have "program manager" appearing in its description.
For queries like "cloud" that don't contain title or location specific
ontology, jobs with "cloud" keyword matches are returned regardless of
this flag's value.
Please use ``Company.keyword_searchable_custom_fields`` or
``Company.keyword_searchable_custom_attributes`` if company specific
globally matched custom field/attribute string values is needed.
Enabling keyword match improves recall of subsequent search requests.
Defaults to false.
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.talent_v4beta1.types.MatchingJob` 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 "search_jobs" not in self._inner_api_calls:
self._inner_api_calls[
"search_jobs"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.search_jobs,
default_retry=self._method_configs["SearchJobs"].retry,
default_timeout=self._method_configs["SearchJobs"].timeout,
client_info=self._client_info,
)
request = job_service_pb2.SearchJobsRequest(
parent=parent,
request_metadata=request_metadata,
search_mode=search_mode,
job_query=job_query,
enable_broadening=enable_broadening,
require_precise_result_size=require_precise_result_size,
histogram_queries=histogram_queries,
job_view=job_view,
offset=offset,
page_size=page_size,
order_by=order_by,
diversification_level=diversification_level,
custom_ranking_info=custom_ranking_info,
disable_keyword_match=disable_keyword_match,
)
iterator = google.api_core.page_iterator.GRPCIterator(
client=None,
method=functools.partial(
self._inner_api_calls["search_jobs"],
retry=retry,
timeout=timeout,
metadata=metadata,
),
request=request,
items_field="matching_jobs",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | [
"def",
"search_jobs",
"(",
"self",
",",
"parent",
",",
"request_metadata",
",",
"search_mode",
"=",
"None",
",",
"job_query",
"=",
"None",
",",
"enable_broadening",
"=",
"None",
",",
"require_precise_result_size",
"=",
"None",
",",
"histogram_queries",
"=",
"None",
",",
"job_view",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"diversification_level",
"=",
"None",
",",
"custom_ranking_info",
"=",
"None",
",",
"disable_keyword_match",
"=",
"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",
"\"search_jobs\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"search_jobs\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"search_jobs",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"SearchJobs\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"SearchJobs\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"job_service_pb2",
".",
"SearchJobsRequest",
"(",
"parent",
"=",
"parent",
",",
"request_metadata",
"=",
"request_metadata",
",",
"search_mode",
"=",
"search_mode",
",",
"job_query",
"=",
"job_query",
",",
"enable_broadening",
"=",
"enable_broadening",
",",
"require_precise_result_size",
"=",
"require_precise_result_size",
",",
"histogram_queries",
"=",
"histogram_queries",
",",
"job_view",
"=",
"job_view",
",",
"offset",
"=",
"offset",
",",
"page_size",
"=",
"page_size",
",",
"order_by",
"=",
"order_by",
",",
"diversification_level",
"=",
"diversification_level",
",",
"custom_ranking_info",
"=",
"custom_ranking_info",
",",
"disable_keyword_match",
"=",
"disable_keyword_match",
",",
")",
"iterator",
"=",
"google",
".",
"api_core",
".",
"page_iterator",
".",
"GRPCIterator",
"(",
"client",
"=",
"None",
",",
"method",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_inner_api_calls",
"[",
"\"search_jobs\"",
"]",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
",",
")",
",",
"request",
"=",
"request",
",",
"items_field",
"=",
"\"matching_jobs\"",
",",
"request_token_field",
"=",
"\"page_token\"",
",",
"response_token_field",
"=",
"\"next_page_token\"",
",",
")",
"return",
"iterator"
] | Searches for jobs using the provided ``SearchJobsRequest``.
This call constrains the ``visibility`` of jobs present in the database,
and only returns jobs that the caller has permission to search against.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `request_metadata`:
>>> request_metadata = {}
>>>
>>> # Iterate over all results
>>> for element in client.search_jobs(parent, request_metadata):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.search_jobs(parent, request_metadata).pages:
... for element in page:
... # process element
... pass
Args:
parent (str): Required.
The resource name of the project to search within.
The format is "projects/{project\_id}", for example,
"projects/api-test-project".
request_metadata (Union[dict, ~google.cloud.talent_v4beta1.types.RequestMetadata]): Required.
The meta information collected about the job searcher, used to improve
the search quality of the service.. The identifiers, (such as
``user_id``) are provided by users, and must be unique and consistent.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.RequestMetadata`
search_mode (~google.cloud.talent_v4beta1.types.SearchMode): Optional.
Mode of a search.
Defaults to ``SearchMode.JOB_SEARCH``.
job_query (Union[dict, ~google.cloud.talent_v4beta1.types.JobQuery]): Optional.
Query used to search against jobs, such as keyword, location filters, etc.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.JobQuery`
enable_broadening (bool): Optional.
Controls whether to broaden the search when it produces sparse results.
Broadened queries append results to the end of the matching results
list.
Defaults to false.
require_precise_result_size (bool): Optional.
Controls if the search job request requires the return of a precise
count of the first 300 results. Setting this to ``true`` ensures
consistency in the number of results per page. Best practice is to set
this value to true if a client allows users to jump directly to a
non-sequential search results page.
Enabling this flag may adversely impact performance.
Defaults to false.
histogram_queries (list[Union[dict, ~google.cloud.talent_v4beta1.types.HistogramQuery]]): Optional.
An expression specifies a histogram request against matching jobs.
Expression syntax is an aggregation function call with histogram facets
and other options.
Available aggregation function calls are: \*
``count(string_histogram_facet)``: Count the number of matching
entities, for each distinct attribute value. \*
``count(numeric_histogram_facet, list of buckets)``: Count the number of
matching entities within each bucket.
Data types:
- Histogram facet: facet names with format [a-zA-Z][a-zA-Z0-9\_]+.
- String: string like "any string with backslash escape for quote(")."
- Number: whole number and floating point number like 10, -1 and -0.01.
- List: list of elements with comma(,) separator surrounded by square
brackets, for example, [1, 2, 3] and ["one", "two", "three"].
Built-in constants:
- MIN (minimum number similar to java Double.MIN\_VALUE)
- MAX (maximum number similar to java Double.MAX\_VALUE)
Built-in functions:
- bucket(start, end[, label]): bucket built-in function creates a
bucket with range of \`start, end). Note that the end is exclusive,
for example, bucket(1, MAX, "positive number") or bucket(1, 10).
Job histogram facets:
- company\_id: histogram by [Job.distributor\_company\_id\`.
- company\_display\_name: histogram by ``Job.company_display_name``.
- employment\_type: histogram by ``Job.employment_types``, for example,
"FULL\_TIME", "PART\_TIME".
- company\_size: histogram by ``CompanySize``, for example, "SMALL",
"MEDIUM", "BIG".
- publish\_time\_in\_month: histogram by the ``Job.publish_time`` in
months. Must specify list of numeric buckets in spec.
- publish\_time\_in\_year: histogram by the ``Job.publish_time`` in
years. Must specify list of numeric buckets in spec.
- degree\_type: histogram by the ``Job.degree_type``, for example,
"Bachelors", "Masters".
- job\_level: histogram by the ``Job.job_level``, for example, "Entry
Level".
- country: histogram by the country code of jobs, for example, "US",
"FR".
- admin1: histogram by the admin1 code of jobs, which is a global
placeholder referring to the state, province, or the particular term
a country uses to define the geographic structure below the country
level, for example, "CA", "IL".
- city: histogram by a combination of the "city name, admin1 code". For
example, "Mountain View, CA", "New York, NY".
- admin1\_country: histogram by a combination of the "admin1 code,
country", for example, "CA, US", "IL, US".
- city\_coordinate: histogram by the city center's GPS coordinates
(latitude and longitude), for example, 37.4038522,-122.0987765. Since
the coordinates of a city center can change, customers may need to
refresh them periodically.
- locale: histogram by the ``Job.language_code``, for example, "en-US",
"fr-FR".
- language: histogram by the language subtag of the
``Job.language_code``, for example, "en", "fr".
- category: histogram by the ``JobCategory``, for example,
"COMPUTER\_AND\_IT", "HEALTHCARE".
- base\_compensation\_unit: histogram by the ``CompensationUnit`` of
base salary, for example, "WEEKLY", "MONTHLY".
- base\_compensation: histogram by the base salary. Must specify list
of numeric buckets to group results by.
- annualized\_base\_compensation: histogram by the base annualized
salary. Must specify list of numeric buckets to group results by.
- annualized\_total\_compensation: histogram by the total annualized
salary. Must specify list of numeric buckets to group results by.
- string\_custom\_attribute: histogram by string
``Job.custom_attributes``. Values can be accessed via square bracket
notations like string\_custom\_attribute["key1"].
- numeric\_custom\_attribute: histogram by numeric
``Job.custom_attributes``. Values can be accessed via square bracket
notations like numeric\_custom\_attribute["key1"]. Must specify list
of numeric buckets to group results by.
Example expressions: \* count(admin1) \* count(base\_compensation,
[bucket(1000, 10000), bucket(10000, 100000), bucket(100000, MAX)]) \*
count(string\_custom\_attribute["some-string-custom-attribute"]) \*
count(numeric\_custom\_attribute["some-numeric-custom-attribute"],
[bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative"])
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.HistogramQuery`
job_view (~google.cloud.talent_v4beta1.types.JobView): Optional.
The desired job attributes returned for jobs in the search response.
Defaults to ``JobView.SMALL`` if no value is specified.
offset (int): Optional.
An integer that specifies the current offset (that is, starting result
location, amongst the jobs deemed by the API as relevant) in search
results. This field is only considered if ``page_token`` is unset.
For example, 0 means to return results starting from the first matching
job, and 10 means to return from the 11th job. This can be used for
pagination, (for example, pageSize = 10 and offset = 10 means to return
from the second page).
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): Optional.
The criteria determining how search results are sorted. Default is
"relevance desc".
Supported options are:
- "relevance desc": By relevance descending, as determined by the API
algorithms. Relevance thresholding of query results is only available
with this ordering.
- "posting``_``\ publish\ ``_``\ time desc": By
``Job.posting_publish_time`` descending.
- "posting``_``\ update\ ``_``\ time desc": By
``Job.posting_update_time`` descending.
- "title": By ``Job.title`` ascending.
- "title desc": By ``Job.title`` descending.
- "annualized``_``\ base\ ``_``\ compensation": By job's
``CompensationInfo.annualized_base_compensation_range`` ascending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "annualized``_``\ base\ ``_``\ compensation desc": By job's
``CompensationInfo.annualized_base_compensation_range`` descending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "annualized``_``\ total\ ``_``\ compensation": By job's
``CompensationInfo.annualized_total_compensation_range`` ascending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "annualized``_``\ total\ ``_``\ compensation desc": By job's
``CompensationInfo.annualized_total_compensation_range`` descending.
Jobs whose annualized base compensation is unspecified are put at the
end of search results.
- "custom``_``\ ranking desc": By the relevance score adjusted to the
``SearchJobsRequest.custom_ranking_info.ranking_expression`` with
weight factor assigned by
``SearchJobsRequest.custom_ranking_info.importance_level`` in
descending order.
- "location``_``\ distance": By the distance between the location on
jobs and locations specified in the
``SearchJobsRequest.job_query.location_filters``. When this order is
selected, the ``SearchJobsRequest.job_query.location_filters`` must
not be empty. When a job has multiple locations, the location closest
to one of the locations specified in the location filter will be used
to calculate location distance. Distance is calculated by the
distance between two lat/long coordinates, with a precision of 10e-4
degrees (11.3 meters). Jobs that don't have locations specified will
be ranked below jobs having locations. Diversification strategy is
still applied unless explicitly disabled in
``SearchJobsRequest.diversification_level``.
diversification_level (~google.cloud.talent_v4beta1.types.DiversificationLevel): Optional.
Controls whether highly similar jobs are returned next to each other in
the search results. Jobs are identified as highly similar based on their
titles, job categories, and locations. Highly similar results are
clustered so that only one representative job of the cluster is
displayed to the job seeker higher up in the results, with the other
jobs being displayed lower down in the results.
Defaults to ``DiversificationLevel.SIMPLE`` if no value is specified.
custom_ranking_info (Union[dict, ~google.cloud.talent_v4beta1.types.CustomRankingInfo]): Optional.
Controls over how job documents get ranked on top of existing relevance
score (determined by API algorithm).
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.talent_v4beta1.types.CustomRankingInfo`
disable_keyword_match (bool): Optional.
Controls whether to disable exact keyword match on ``Job.job_title``,
``Job.description``, ``Job.company_display_name``, [Job.locations][0],
``Job.qualifications``. When disable keyword match is turned off, a
keyword match returns jobs that do not match given category filters when
there are matching keywords. For example, for the query "program
manager," a result is returned even if the job posting has the title
"software developer," which doesn't fall into "program manager"
ontology, but does have "program manager" appearing in its description.
For queries like "cloud" that don't contain title or location specific
ontology, jobs with "cloud" keyword matches are returned regardless of
this flag's value.
Please use ``Company.keyword_searchable_custom_fields`` or
``Company.keyword_searchable_custom_attributes`` if company specific
globally matched custom field/attribute string values is needed.
Enabling keyword match improves recall of subsequent search requests.
Defaults to false.
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.talent_v4beta1.types.MatchingJob` 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. | [
"Searches",
"for",
"jobs",
"using",
"the",
"provided",
"SearchJobsRequest",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/job_service_client.py#L670-L1024 |
27,817 | googleapis/google-cloud-python | core/google/cloud/operation.py | _compute_type_url | def _compute_type_url(klass, prefix=_GOOGLE_APIS_PREFIX):
"""Compute a type URL for a klass.
:type klass: type
:param klass: class to be used as a factory for the given type
:type prefix: str
:param prefix: URL prefix for the type
:rtype: str
:returns: the URL, prefixed as appropriate
"""
name = klass.DESCRIPTOR.full_name
return "%s/%s" % (prefix, name) | python | def _compute_type_url(klass, prefix=_GOOGLE_APIS_PREFIX):
"""Compute a type URL for a klass.
:type klass: type
:param klass: class to be used as a factory for the given type
:type prefix: str
:param prefix: URL prefix for the type
:rtype: str
:returns: the URL, prefixed as appropriate
"""
name = klass.DESCRIPTOR.full_name
return "%s/%s" % (prefix, name) | [
"def",
"_compute_type_url",
"(",
"klass",
",",
"prefix",
"=",
"_GOOGLE_APIS_PREFIX",
")",
":",
"name",
"=",
"klass",
".",
"DESCRIPTOR",
".",
"full_name",
"return",
"\"%s/%s\"",
"%",
"(",
"prefix",
",",
"name",
")"
] | Compute a type URL for a klass.
:type klass: type
:param klass: class to be used as a factory for the given type
:type prefix: str
:param prefix: URL prefix for the type
:rtype: str
:returns: the URL, prefixed as appropriate | [
"Compute",
"a",
"type",
"URL",
"for",
"a",
"klass",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/operation.py#L26-L39 |
27,818 | googleapis/google-cloud-python | core/google/cloud/operation.py | register_type | def register_type(klass, type_url=None):
"""Register a klass as the factory for a given type URL.
:type klass: :class:`type`
:param klass: class to be used as a factory for the given type
:type type_url: str
:param type_url: (Optional) URL naming the type. If not provided,
infers the URL from the type descriptor.
:raises ValueError: if a registration already exists for the URL.
"""
if type_url is None:
type_url = _compute_type_url(klass)
if type_url in _TYPE_URL_MAP:
if _TYPE_URL_MAP[type_url] is not klass:
raise ValueError("Conflict: %s" % (_TYPE_URL_MAP[type_url],))
_TYPE_URL_MAP[type_url] = klass | python | def register_type(klass, type_url=None):
"""Register a klass as the factory for a given type URL.
:type klass: :class:`type`
:param klass: class to be used as a factory for the given type
:type type_url: str
:param type_url: (Optional) URL naming the type. If not provided,
infers the URL from the type descriptor.
:raises ValueError: if a registration already exists for the URL.
"""
if type_url is None:
type_url = _compute_type_url(klass)
if type_url in _TYPE_URL_MAP:
if _TYPE_URL_MAP[type_url] is not klass:
raise ValueError("Conflict: %s" % (_TYPE_URL_MAP[type_url],))
_TYPE_URL_MAP[type_url] = klass | [
"def",
"register_type",
"(",
"klass",
",",
"type_url",
"=",
"None",
")",
":",
"if",
"type_url",
"is",
"None",
":",
"type_url",
"=",
"_compute_type_url",
"(",
"klass",
")",
"if",
"type_url",
"in",
"_TYPE_URL_MAP",
":",
"if",
"_TYPE_URL_MAP",
"[",
"type_url",
"]",
"is",
"not",
"klass",
":",
"raise",
"ValueError",
"(",
"\"Conflict: %s\"",
"%",
"(",
"_TYPE_URL_MAP",
"[",
"type_url",
"]",
",",
")",
")",
"_TYPE_URL_MAP",
"[",
"type_url",
"]",
"=",
"klass"
] | Register a klass as the factory for a given type URL.
:type klass: :class:`type`
:param klass: class to be used as a factory for the given type
:type type_url: str
:param type_url: (Optional) URL naming the type. If not provided,
infers the URL from the type descriptor.
:raises ValueError: if a registration already exists for the URL. | [
"Register",
"a",
"klass",
"as",
"the",
"factory",
"for",
"a",
"given",
"type",
"URL",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/operation.py#L42-L60 |
27,819 | googleapis/google-cloud-python | core/google/cloud/operation.py | _from_any | def _from_any(any_pb):
"""Convert an ``Any`` protobuf into the actual class.
Uses the type URL to do the conversion.
.. note::
This assumes that the type URL is already registered.
:type any_pb: :class:`google.protobuf.any_pb2.Any`
:param any_pb: An any object to be converted.
:rtype: object
:returns: The instance (of the correct type) stored in the any
instance.
"""
klass = _TYPE_URL_MAP[any_pb.type_url]
return klass.FromString(any_pb.value) | python | def _from_any(any_pb):
"""Convert an ``Any`` protobuf into the actual class.
Uses the type URL to do the conversion.
.. note::
This assumes that the type URL is already registered.
:type any_pb: :class:`google.protobuf.any_pb2.Any`
:param any_pb: An any object to be converted.
:rtype: object
:returns: The instance (of the correct type) stored in the any
instance.
"""
klass = _TYPE_URL_MAP[any_pb.type_url]
return klass.FromString(any_pb.value) | [
"def",
"_from_any",
"(",
"any_pb",
")",
":",
"klass",
"=",
"_TYPE_URL_MAP",
"[",
"any_pb",
".",
"type_url",
"]",
"return",
"klass",
".",
"FromString",
"(",
"any_pb",
".",
"value",
")"
] | Convert an ``Any`` protobuf into the actual class.
Uses the type URL to do the conversion.
.. note::
This assumes that the type URL is already registered.
:type any_pb: :class:`google.protobuf.any_pb2.Any`
:param any_pb: An any object to be converted.
:rtype: object
:returns: The instance (of the correct type) stored in the any
instance. | [
"Convert",
"an",
"Any",
"protobuf",
"into",
"the",
"actual",
"class",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/operation.py#L63-L80 |
27,820 | googleapis/google-cloud-python | core/google/cloud/operation.py | Operation._get_operation_rpc | def _get_operation_rpc(self):
"""Polls the status of the current operation.
Uses gRPC request to check.
:rtype: :class:`~google.longrunning.operations_pb2.Operation`
:returns: The latest status of the current operation.
"""
request_pb = operations_pb2.GetOperationRequest(name=self.name)
return self.client._operations_stub.GetOperation(request_pb) | python | def _get_operation_rpc(self):
"""Polls the status of the current operation.
Uses gRPC request to check.
:rtype: :class:`~google.longrunning.operations_pb2.Operation`
:returns: The latest status of the current operation.
"""
request_pb = operations_pb2.GetOperationRequest(name=self.name)
return self.client._operations_stub.GetOperation(request_pb) | [
"def",
"_get_operation_rpc",
"(",
"self",
")",
":",
"request_pb",
"=",
"operations_pb2",
".",
"GetOperationRequest",
"(",
"name",
"=",
"self",
".",
"name",
")",
"return",
"self",
".",
"client",
".",
"_operations_stub",
".",
"GetOperation",
"(",
"request_pb",
")"
] | Polls the status of the current operation.
Uses gRPC request to check.
:rtype: :class:`~google.longrunning.operations_pb2.Operation`
:returns: The latest status of the current operation. | [
"Polls",
"the",
"status",
"of",
"the",
"current",
"operation",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/operation.py#L199-L208 |
27,821 | googleapis/google-cloud-python | core/google/cloud/operation.py | Operation._get_operation_http | def _get_operation_http(self):
"""Checks the status of the current operation.
Uses HTTP request to check.
:rtype: :class:`~google.longrunning.operations_pb2.Operation`
:returns: The latest status of the current operation.
"""
path = "operations/%s" % (self.name,)
api_response = self.client._connection.api_request(method="GET", path=path)
return json_format.ParseDict(api_response, operations_pb2.Operation()) | python | def _get_operation_http(self):
"""Checks the status of the current operation.
Uses HTTP request to check.
:rtype: :class:`~google.longrunning.operations_pb2.Operation`
:returns: The latest status of the current operation.
"""
path = "operations/%s" % (self.name,)
api_response = self.client._connection.api_request(method="GET", path=path)
return json_format.ParseDict(api_response, operations_pb2.Operation()) | [
"def",
"_get_operation_http",
"(",
"self",
")",
":",
"path",
"=",
"\"operations/%s\"",
"%",
"(",
"self",
".",
"name",
",",
")",
"api_response",
"=",
"self",
".",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"path",
")",
"return",
"json_format",
".",
"ParseDict",
"(",
"api_response",
",",
"operations_pb2",
".",
"Operation",
"(",
")",
")"
] | Checks the status of the current operation.
Uses HTTP request to check.
:rtype: :class:`~google.longrunning.operations_pb2.Operation`
:returns: The latest status of the current operation. | [
"Checks",
"the",
"status",
"of",
"the",
"current",
"operation",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/operation.py#L210-L220 |
27,822 | googleapis/google-cloud-python | core/google/cloud/operation.py | Operation._update_state | def _update_state(self, operation_pb):
"""Update the state of the current object based on operation.
:type operation_pb:
:class:`~google.longrunning.operations_pb2.Operation`
:param operation_pb: Protobuf to be parsed.
"""
if operation_pb.done:
self._complete = True
if operation_pb.HasField("metadata"):
self.metadata = _from_any(operation_pb.metadata)
result_type = operation_pb.WhichOneof("result")
if result_type == "error":
self.error = operation_pb.error
elif result_type == "response":
self.response = _from_any(operation_pb.response) | python | def _update_state(self, operation_pb):
"""Update the state of the current object based on operation.
:type operation_pb:
:class:`~google.longrunning.operations_pb2.Operation`
:param operation_pb: Protobuf to be parsed.
"""
if operation_pb.done:
self._complete = True
if operation_pb.HasField("metadata"):
self.metadata = _from_any(operation_pb.metadata)
result_type = operation_pb.WhichOneof("result")
if result_type == "error":
self.error = operation_pb.error
elif result_type == "response":
self.response = _from_any(operation_pb.response) | [
"def",
"_update_state",
"(",
"self",
",",
"operation_pb",
")",
":",
"if",
"operation_pb",
".",
"done",
":",
"self",
".",
"_complete",
"=",
"True",
"if",
"operation_pb",
".",
"HasField",
"(",
"\"metadata\"",
")",
":",
"self",
".",
"metadata",
"=",
"_from_any",
"(",
"operation_pb",
".",
"metadata",
")",
"result_type",
"=",
"operation_pb",
".",
"WhichOneof",
"(",
"\"result\"",
")",
"if",
"result_type",
"==",
"\"error\"",
":",
"self",
".",
"error",
"=",
"operation_pb",
".",
"error",
"elif",
"result_type",
"==",
"\"response\"",
":",
"self",
".",
"response",
"=",
"_from_any",
"(",
"operation_pb",
".",
"response",
")"
] | Update the state of the current object based on operation.
:type operation_pb:
:class:`~google.longrunning.operations_pb2.Operation`
:param operation_pb: Protobuf to be parsed. | [
"Update",
"the",
"state",
"of",
"the",
"current",
"object",
"based",
"on",
"operation",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/operation.py#L233-L250 |
27,823 | googleapis/google-cloud-python | core/google/cloud/operation.py | Operation.poll | def poll(self):
"""Check if the operation has finished.
:rtype: bool
:returns: A boolean indicating if the current operation has completed.
:raises ValueError: if the operation
has already completed.
"""
if self.complete:
raise ValueError("The operation has completed.")
operation_pb = self._get_operation()
self._update_state(operation_pb)
return self.complete | python | def poll(self):
"""Check if the operation has finished.
:rtype: bool
:returns: A boolean indicating if the current operation has completed.
:raises ValueError: if the operation
has already completed.
"""
if self.complete:
raise ValueError("The operation has completed.")
operation_pb = self._get_operation()
self._update_state(operation_pb)
return self.complete | [
"def",
"poll",
"(",
"self",
")",
":",
"if",
"self",
".",
"complete",
":",
"raise",
"ValueError",
"(",
"\"The operation has completed.\"",
")",
"operation_pb",
"=",
"self",
".",
"_get_operation",
"(",
")",
"self",
".",
"_update_state",
"(",
"operation_pb",
")",
"return",
"self",
".",
"complete"
] | Check if the operation has finished.
:rtype: bool
:returns: A boolean indicating if the current operation has completed.
:raises ValueError: if the operation
has already completed. | [
"Check",
"if",
"the",
"operation",
"has",
"finished",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/operation.py#L252-L266 |
27,824 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row.py | _parse_rmw_row_response | def _parse_rmw_row_response(row_response):
"""Parses the response to a ``ReadModifyWriteRow`` request.
:type row_response: :class:`.data_v2_pb2.Row`
:param row_response: The response row (with only modified cells) from a
``ReadModifyWriteRow`` request.
:rtype: dict
:returns: The new contents of all modified cells. Returned as a
dictionary of column families, each of which holds a
dictionary of columns. Each column contains a list of cells
modified. Each cell is represented with a two-tuple with the
value (in bytes) and the timestamp for the cell. For example:
.. code:: python
{
u'col-fam-id': {
b'col-name1': [
(b'cell-val', datetime.datetime(...)),
(b'cell-val-newer', datetime.datetime(...)),
],
b'col-name2': [
(b'altcol-cell-val', datetime.datetime(...)),
],
},
u'col-fam-id2': {
b'col-name3-but-other-fam': [
(b'foo', datetime.datetime(...)),
],
},
}
"""
result = {}
for column_family in row_response.row.families:
column_family_id, curr_family = _parse_family_pb(column_family)
result[column_family_id] = curr_family
return result | python | def _parse_rmw_row_response(row_response):
"""Parses the response to a ``ReadModifyWriteRow`` request.
:type row_response: :class:`.data_v2_pb2.Row`
:param row_response: The response row (with only modified cells) from a
``ReadModifyWriteRow`` request.
:rtype: dict
:returns: The new contents of all modified cells. Returned as a
dictionary of column families, each of which holds a
dictionary of columns. Each column contains a list of cells
modified. Each cell is represented with a two-tuple with the
value (in bytes) and the timestamp for the cell. For example:
.. code:: python
{
u'col-fam-id': {
b'col-name1': [
(b'cell-val', datetime.datetime(...)),
(b'cell-val-newer', datetime.datetime(...)),
],
b'col-name2': [
(b'altcol-cell-val', datetime.datetime(...)),
],
},
u'col-fam-id2': {
b'col-name3-but-other-fam': [
(b'foo', datetime.datetime(...)),
],
},
}
"""
result = {}
for column_family in row_response.row.families:
column_family_id, curr_family = _parse_family_pb(column_family)
result[column_family_id] = curr_family
return result | [
"def",
"_parse_rmw_row_response",
"(",
"row_response",
")",
":",
"result",
"=",
"{",
"}",
"for",
"column_family",
"in",
"row_response",
".",
"row",
".",
"families",
":",
"column_family_id",
",",
"curr_family",
"=",
"_parse_family_pb",
"(",
"column_family",
")",
"result",
"[",
"column_family_id",
"]",
"=",
"curr_family",
"return",
"result"
] | Parses the response to a ``ReadModifyWriteRow`` request.
:type row_response: :class:`.data_v2_pb2.Row`
:param row_response: The response row (with only modified cells) from a
``ReadModifyWriteRow`` request.
:rtype: dict
:returns: The new contents of all modified cells. Returned as a
dictionary of column families, each of which holds a
dictionary of columns. Each column contains a list of cells
modified. Each cell is represented with a two-tuple with the
value (in bytes) and the timestamp for the cell. For example:
.. code:: python
{
u'col-fam-id': {
b'col-name1': [
(b'cell-val', datetime.datetime(...)),
(b'cell-val-newer', datetime.datetime(...)),
],
b'col-name2': [
(b'altcol-cell-val', datetime.datetime(...)),
],
},
u'col-fam-id2': {
b'col-name3-but-other-fam': [
(b'foo', datetime.datetime(...)),
],
},
} | [
"Parses",
"the",
"response",
"to",
"a",
"ReadModifyWriteRow",
"request",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L921-L958 |
27,825 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row.py | _parse_family_pb | def _parse_family_pb(family_pb):
"""Parses a Family protobuf into a dictionary.
:type family_pb: :class:`._generated.data_pb2.Family`
:param family_pb: A protobuf
:rtype: tuple
:returns: A string and dictionary. The string is the name of the
column family and the dictionary has column names (within the
family) as keys and cell lists as values. Each cell is
represented with a two-tuple with the value (in bytes) and the
timestamp for the cell. For example:
.. code:: python
{
b'col-name1': [
(b'cell-val', datetime.datetime(...)),
(b'cell-val-newer', datetime.datetime(...)),
],
b'col-name2': [
(b'altcol-cell-val', datetime.datetime(...)),
],
}
"""
result = {}
for column in family_pb.columns:
result[column.qualifier] = cells = []
for cell in column.cells:
val_pair = (cell.value, _datetime_from_microseconds(cell.timestamp_micros))
cells.append(val_pair)
return family_pb.name, result | python | def _parse_family_pb(family_pb):
"""Parses a Family protobuf into a dictionary.
:type family_pb: :class:`._generated.data_pb2.Family`
:param family_pb: A protobuf
:rtype: tuple
:returns: A string and dictionary. The string is the name of the
column family and the dictionary has column names (within the
family) as keys and cell lists as values. Each cell is
represented with a two-tuple with the value (in bytes) and the
timestamp for the cell. For example:
.. code:: python
{
b'col-name1': [
(b'cell-val', datetime.datetime(...)),
(b'cell-val-newer', datetime.datetime(...)),
],
b'col-name2': [
(b'altcol-cell-val', datetime.datetime(...)),
],
}
"""
result = {}
for column in family_pb.columns:
result[column.qualifier] = cells = []
for cell in column.cells:
val_pair = (cell.value, _datetime_from_microseconds(cell.timestamp_micros))
cells.append(val_pair)
return family_pb.name, result | [
"def",
"_parse_family_pb",
"(",
"family_pb",
")",
":",
"result",
"=",
"{",
"}",
"for",
"column",
"in",
"family_pb",
".",
"columns",
":",
"result",
"[",
"column",
".",
"qualifier",
"]",
"=",
"cells",
"=",
"[",
"]",
"for",
"cell",
"in",
"column",
".",
"cells",
":",
"val_pair",
"=",
"(",
"cell",
".",
"value",
",",
"_datetime_from_microseconds",
"(",
"cell",
".",
"timestamp_micros",
")",
")",
"cells",
".",
"append",
"(",
"val_pair",
")",
"return",
"family_pb",
".",
"name",
",",
"result"
] | Parses a Family protobuf into a dictionary.
:type family_pb: :class:`._generated.data_pb2.Family`
:param family_pb: A protobuf
:rtype: tuple
:returns: A string and dictionary. The string is the name of the
column family and the dictionary has column names (within the
family) as keys and cell lists as values. Each cell is
represented with a two-tuple with the value (in bytes) and the
timestamp for the cell. For example:
.. code:: python
{
b'col-name1': [
(b'cell-val', datetime.datetime(...)),
(b'cell-val-newer', datetime.datetime(...)),
],
b'col-name2': [
(b'altcol-cell-val', datetime.datetime(...)),
],
} | [
"Parses",
"a",
"Family",
"protobuf",
"into",
"a",
"dictionary",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L961-L993 |
27,826 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row.py | DirectRow.get_mutations_size | def get_mutations_size(self):
""" Gets the total mutations size for current row
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_get_mutations_size]
:end-before: [END bigtable_row_get_mutations_size]
"""
mutation_size = 0
for mutation in self._get_mutations():
mutation_size += mutation.ByteSize()
return mutation_size | python | def get_mutations_size(self):
""" Gets the total mutations size for current row
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_get_mutations_size]
:end-before: [END bigtable_row_get_mutations_size]
"""
mutation_size = 0
for mutation in self._get_mutations():
mutation_size += mutation.ByteSize()
return mutation_size | [
"def",
"get_mutations_size",
"(",
"self",
")",
":",
"mutation_size",
"=",
"0",
"for",
"mutation",
"in",
"self",
".",
"_get_mutations",
"(",
")",
":",
"mutation_size",
"+=",
"mutation",
".",
"ByteSize",
"(",
")",
"return",
"mutation_size"
] | Gets the total mutations size for current row
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_get_mutations_size]
:end-before: [END bigtable_row_get_mutations_size] | [
"Gets",
"the",
"total",
"mutations",
"size",
"for",
"current",
"row"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L295-L310 |
27,827 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row.py | DirectRow.set_cell | def set_cell(self, column_family_id, column, value, timestamp=None):
"""Sets a value in this row.
The cell is determined by the ``row_key`` of this :class:`DirectRow`
and the ``column``. The ``column`` must be in an existing
:class:`.ColumnFamily` (as determined by ``column_family_id``).
.. note::
This method adds a mutation to the accumulated mutations on this
row, but does not make an API request. To actually
send an API request (with the mutations) to the Google Cloud
Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_set_cell]
:end-before: [END bigtable_row_set_cell]
:type column_family_id: str
:param column_family_id: The column family that contains the column.
Must be of the form
``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family where the cell
is located.
:type value: bytes or :class:`int`
:param value: The value to set in the cell. If an integer is used,
will be interpreted as a 64-bit big-endian signed
integer (8 bytes).
:type timestamp: :class:`datetime.datetime`
:param timestamp: (Optional) The timestamp of the operation.
"""
self._set_cell(column_family_id, column, value, timestamp=timestamp, state=None) | python | def set_cell(self, column_family_id, column, value, timestamp=None):
"""Sets a value in this row.
The cell is determined by the ``row_key`` of this :class:`DirectRow`
and the ``column``. The ``column`` must be in an existing
:class:`.ColumnFamily` (as determined by ``column_family_id``).
.. note::
This method adds a mutation to the accumulated mutations on this
row, but does not make an API request. To actually
send an API request (with the mutations) to the Google Cloud
Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_set_cell]
:end-before: [END bigtable_row_set_cell]
:type column_family_id: str
:param column_family_id: The column family that contains the column.
Must be of the form
``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family where the cell
is located.
:type value: bytes or :class:`int`
:param value: The value to set in the cell. If an integer is used,
will be interpreted as a 64-bit big-endian signed
integer (8 bytes).
:type timestamp: :class:`datetime.datetime`
:param timestamp: (Optional) The timestamp of the operation.
"""
self._set_cell(column_family_id, column, value, timestamp=timestamp, state=None) | [
"def",
"set_cell",
"(",
"self",
",",
"column_family_id",
",",
"column",
",",
"value",
",",
"timestamp",
"=",
"None",
")",
":",
"self",
".",
"_set_cell",
"(",
"column_family_id",
",",
"column",
",",
"value",
",",
"timestamp",
"=",
"timestamp",
",",
"state",
"=",
"None",
")"
] | Sets a value in this row.
The cell is determined by the ``row_key`` of this :class:`DirectRow`
and the ``column``. The ``column`` must be in an existing
:class:`.ColumnFamily` (as determined by ``column_family_id``).
.. note::
This method adds a mutation to the accumulated mutations on this
row, but does not make an API request. To actually
send an API request (with the mutations) to the Google Cloud
Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_set_cell]
:end-before: [END bigtable_row_set_cell]
:type column_family_id: str
:param column_family_id: The column family that contains the column.
Must be of the form
``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family where the cell
is located.
:type value: bytes or :class:`int`
:param value: The value to set in the cell. If an integer is used,
will be interpreted as a 64-bit big-endian signed
integer (8 bytes).
:type timestamp: :class:`datetime.datetime`
:param timestamp: (Optional) The timestamp of the operation. | [
"Sets",
"a",
"value",
"in",
"this",
"row",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L312-L349 |
27,828 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row.py | DirectRow.delete_cell | def delete_cell(self, column_family_id, column, time_range=None):
"""Deletes cell in this row.
.. note::
This method adds a mutation to the accumulated mutations on this
row, but does not make an API request. To actually
send an API request (with the mutations) to the Google Cloud
Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_delete_cell]
:end-before: [END bigtable_row_delete_cell]
:type column_family_id: str
:param column_family_id: The column family that contains the column
or columns with cells being deleted. Must be
of the form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family that will have a
cell deleted.
:type time_range: :class:`TimestampRange`
:param time_range: (Optional) The range of time within which cells
should be deleted.
"""
self._delete_cells(
column_family_id, [column], time_range=time_range, state=None
) | python | def delete_cell(self, column_family_id, column, time_range=None):
"""Deletes cell in this row.
.. note::
This method adds a mutation to the accumulated mutations on this
row, but does not make an API request. To actually
send an API request (with the mutations) to the Google Cloud
Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_delete_cell]
:end-before: [END bigtable_row_delete_cell]
:type column_family_id: str
:param column_family_id: The column family that contains the column
or columns with cells being deleted. Must be
of the form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family that will have a
cell deleted.
:type time_range: :class:`TimestampRange`
:param time_range: (Optional) The range of time within which cells
should be deleted.
"""
self._delete_cells(
column_family_id, [column], time_range=time_range, state=None
) | [
"def",
"delete_cell",
"(",
"self",
",",
"column_family_id",
",",
"column",
",",
"time_range",
"=",
"None",
")",
":",
"self",
".",
"_delete_cells",
"(",
"column_family_id",
",",
"[",
"column",
"]",
",",
"time_range",
"=",
"time_range",
",",
"state",
"=",
"None",
")"
] | Deletes cell in this row.
.. note::
This method adds a mutation to the accumulated mutations on this
row, but does not make an API request. To actually
send an API request (with the mutations) to the Google Cloud
Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_delete_cell]
:end-before: [END bigtable_row_delete_cell]
:type column_family_id: str
:param column_family_id: The column family that contains the column
or columns with cells being deleted. Must be
of the form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family that will have a
cell deleted.
:type time_range: :class:`TimestampRange`
:param time_range: (Optional) The range of time within which cells
should be deleted. | [
"Deletes",
"cell",
"in",
"this",
"row",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L370-L401 |
27,829 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row.py | DirectRow.delete_cells | def delete_cells(self, column_family_id, columns, time_range=None):
"""Deletes cells in this row.
.. note::
This method adds a mutation to the accumulated mutations on this
row, but does not make an API request. To actually
send an API request (with the mutations) to the Google Cloud
Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_delete_cells]
:end-before: [END bigtable_row_delete_cells]
:type column_family_id: str
:param column_family_id: The column family that contains the column
or columns with cells being deleted. Must be
of the form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type columns: :class:`list` of :class:`str` /
:func:`unicode <unicode>`, or :class:`object`
:param columns: The columns within the column family that will have
cells deleted. If :attr:`ALL_COLUMNS` is used then
the entire column family will be deleted from the row.
:type time_range: :class:`TimestampRange`
:param time_range: (Optional) The range of time within which cells
should be deleted.
"""
self._delete_cells(column_family_id, columns, time_range=time_range, state=None) | python | def delete_cells(self, column_family_id, columns, time_range=None):
"""Deletes cells in this row.
.. note::
This method adds a mutation to the accumulated mutations on this
row, but does not make an API request. To actually
send an API request (with the mutations) to the Google Cloud
Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_delete_cells]
:end-before: [END bigtable_row_delete_cells]
:type column_family_id: str
:param column_family_id: The column family that contains the column
or columns with cells being deleted. Must be
of the form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type columns: :class:`list` of :class:`str` /
:func:`unicode <unicode>`, or :class:`object`
:param columns: The columns within the column family that will have
cells deleted. If :attr:`ALL_COLUMNS` is used then
the entire column family will be deleted from the row.
:type time_range: :class:`TimestampRange`
:param time_range: (Optional) The range of time within which cells
should be deleted.
"""
self._delete_cells(column_family_id, columns, time_range=time_range, state=None) | [
"def",
"delete_cells",
"(",
"self",
",",
"column_family_id",
",",
"columns",
",",
"time_range",
"=",
"None",
")",
":",
"self",
".",
"_delete_cells",
"(",
"column_family_id",
",",
"columns",
",",
"time_range",
"=",
"time_range",
",",
"state",
"=",
"None",
")"
] | Deletes cells in this row.
.. note::
This method adds a mutation to the accumulated mutations on this
row, but does not make an API request. To actually
send an API request (with the mutations) to the Google Cloud
Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_delete_cells]
:end-before: [END bigtable_row_delete_cells]
:type column_family_id: str
:param column_family_id: The column family that contains the column
or columns with cells being deleted. Must be
of the form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type columns: :class:`list` of :class:`str` /
:func:`unicode <unicode>`, or :class:`object`
:param columns: The columns within the column family that will have
cells deleted. If :attr:`ALL_COLUMNS` is used then
the entire column family will be deleted from the row.
:type time_range: :class:`TimestampRange`
:param time_range: (Optional) The range of time within which cells
should be deleted. | [
"Deletes",
"cells",
"in",
"this",
"row",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L403-L434 |
27,830 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row.py | ConditionalRow.commit | def commit(self):
"""Makes a ``CheckAndMutateRow`` API request.
If no mutations have been created in the row, no request is made.
The mutations will be applied conditionally, based on whether the
filter matches any cells in the :class:`ConditionalRow` or not. (Each
method which adds a mutation has a ``state`` parameter for this
purpose.)
Mutations are applied atomically and in order, meaning that earlier
mutations can be masked / negated by later ones. Cells already present
in the row are left unchanged unless explicitly changed by a mutation.
After committing the accumulated mutations, resets the local
mutations.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_commit]
:end-before: [END bigtable_row_commit]
:rtype: bool
:returns: Flag indicating if the filter was matched (which also
indicates which set of mutations were applied by the server).
:raises: :class:`ValueError <exceptions.ValueError>` if the number of
mutations exceeds the :data:`MAX_MUTATIONS`.
"""
true_mutations = self._get_mutations(state=True)
false_mutations = self._get_mutations(state=False)
num_true_mutations = len(true_mutations)
num_false_mutations = len(false_mutations)
if num_true_mutations == 0 and num_false_mutations == 0:
return
if num_true_mutations > MAX_MUTATIONS or num_false_mutations > MAX_MUTATIONS:
raise ValueError(
"Exceed the maximum allowable mutations (%d). Had %s true "
"mutations and %d false mutations."
% (MAX_MUTATIONS, num_true_mutations, num_false_mutations)
)
data_client = self._table._instance._client.table_data_client
resp = data_client.check_and_mutate_row(
table_name=self._table.name,
row_key=self._row_key,
predicate_filter=self._filter.to_pb(),
true_mutations=true_mutations,
false_mutations=false_mutations,
)
self.clear()
return resp.predicate_matched | python | def commit(self):
"""Makes a ``CheckAndMutateRow`` API request.
If no mutations have been created in the row, no request is made.
The mutations will be applied conditionally, based on whether the
filter matches any cells in the :class:`ConditionalRow` or not. (Each
method which adds a mutation has a ``state`` parameter for this
purpose.)
Mutations are applied atomically and in order, meaning that earlier
mutations can be masked / negated by later ones. Cells already present
in the row are left unchanged unless explicitly changed by a mutation.
After committing the accumulated mutations, resets the local
mutations.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_commit]
:end-before: [END bigtable_row_commit]
:rtype: bool
:returns: Flag indicating if the filter was matched (which also
indicates which set of mutations were applied by the server).
:raises: :class:`ValueError <exceptions.ValueError>` if the number of
mutations exceeds the :data:`MAX_MUTATIONS`.
"""
true_mutations = self._get_mutations(state=True)
false_mutations = self._get_mutations(state=False)
num_true_mutations = len(true_mutations)
num_false_mutations = len(false_mutations)
if num_true_mutations == 0 and num_false_mutations == 0:
return
if num_true_mutations > MAX_MUTATIONS or num_false_mutations > MAX_MUTATIONS:
raise ValueError(
"Exceed the maximum allowable mutations (%d). Had %s true "
"mutations and %d false mutations."
% (MAX_MUTATIONS, num_true_mutations, num_false_mutations)
)
data_client = self._table._instance._client.table_data_client
resp = data_client.check_and_mutate_row(
table_name=self._table.name,
row_key=self._row_key,
predicate_filter=self._filter.to_pb(),
true_mutations=true_mutations,
false_mutations=false_mutations,
)
self.clear()
return resp.predicate_matched | [
"def",
"commit",
"(",
"self",
")",
":",
"true_mutations",
"=",
"self",
".",
"_get_mutations",
"(",
"state",
"=",
"True",
")",
"false_mutations",
"=",
"self",
".",
"_get_mutations",
"(",
"state",
"=",
"False",
")",
"num_true_mutations",
"=",
"len",
"(",
"true_mutations",
")",
"num_false_mutations",
"=",
"len",
"(",
"false_mutations",
")",
"if",
"num_true_mutations",
"==",
"0",
"and",
"num_false_mutations",
"==",
"0",
":",
"return",
"if",
"num_true_mutations",
">",
"MAX_MUTATIONS",
"or",
"num_false_mutations",
">",
"MAX_MUTATIONS",
":",
"raise",
"ValueError",
"(",
"\"Exceed the maximum allowable mutations (%d). Had %s true \"",
"\"mutations and %d false mutations.\"",
"%",
"(",
"MAX_MUTATIONS",
",",
"num_true_mutations",
",",
"num_false_mutations",
")",
")",
"data_client",
"=",
"self",
".",
"_table",
".",
"_instance",
".",
"_client",
".",
"table_data_client",
"resp",
"=",
"data_client",
".",
"check_and_mutate_row",
"(",
"table_name",
"=",
"self",
".",
"_table",
".",
"name",
",",
"row_key",
"=",
"self",
".",
"_row_key",
",",
"predicate_filter",
"=",
"self",
".",
"_filter",
".",
"to_pb",
"(",
")",
",",
"true_mutations",
"=",
"true_mutations",
",",
"false_mutations",
"=",
"false_mutations",
",",
")",
"self",
".",
"clear",
"(",
")",
"return",
"resp",
".",
"predicate_matched"
] | Makes a ``CheckAndMutateRow`` API request.
If no mutations have been created in the row, no request is made.
The mutations will be applied conditionally, based on whether the
filter matches any cells in the :class:`ConditionalRow` or not. (Each
method which adds a mutation has a ``state`` parameter for this
purpose.)
Mutations are applied atomically and in order, meaning that earlier
mutations can be masked / negated by later ones. Cells already present
in the row are left unchanged unless explicitly changed by a mutation.
After committing the accumulated mutations, resets the local
mutations.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_commit]
:end-before: [END bigtable_row_commit]
:rtype: bool
:returns: Flag indicating if the filter was matched (which also
indicates which set of mutations were applied by the server).
:raises: :class:`ValueError <exceptions.ValueError>` if the number of
mutations exceeds the :data:`MAX_MUTATIONS`. | [
"Makes",
"a",
"CheckAndMutateRow",
"API",
"request",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L538-L589 |
27,831 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row.py | AppendRow.append_cell_value | def append_cell_value(self, column_family_id, column, value):
"""Appends a value to an existing cell.
.. note::
This method adds a read-modify rule protobuf to the accumulated
read-modify rules on this row, but does not make an API
request. To actually send an API request (with the rules) to the
Google Cloud Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_append_cell_value]
:end-before: [END bigtable_row_append_cell_value]
:type column_family_id: str
:param column_family_id: The column family that contains the column.
Must be of the form
``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family where the cell
is located.
:type value: bytes
:param value: The value to append to the existing value in the cell. If
the targeted cell is unset, it will be treated as
containing the empty string.
"""
column = _to_bytes(column)
value = _to_bytes(value)
rule_pb = data_v2_pb2.ReadModifyWriteRule(
family_name=column_family_id, column_qualifier=column, append_value=value
)
self._rule_pb_list.append(rule_pb) | python | def append_cell_value(self, column_family_id, column, value):
"""Appends a value to an existing cell.
.. note::
This method adds a read-modify rule protobuf to the accumulated
read-modify rules on this row, but does not make an API
request. To actually send an API request (with the rules) to the
Google Cloud Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_append_cell_value]
:end-before: [END bigtable_row_append_cell_value]
:type column_family_id: str
:param column_family_id: The column family that contains the column.
Must be of the form
``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family where the cell
is located.
:type value: bytes
:param value: The value to append to the existing value in the cell. If
the targeted cell is unset, it will be treated as
containing the empty string.
"""
column = _to_bytes(column)
value = _to_bytes(value)
rule_pb = data_v2_pb2.ReadModifyWriteRule(
family_name=column_family_id, column_qualifier=column, append_value=value
)
self._rule_pb_list.append(rule_pb) | [
"def",
"append_cell_value",
"(",
"self",
",",
"column_family_id",
",",
"column",
",",
"value",
")",
":",
"column",
"=",
"_to_bytes",
"(",
"column",
")",
"value",
"=",
"_to_bytes",
"(",
"value",
")",
"rule_pb",
"=",
"data_v2_pb2",
".",
"ReadModifyWriteRule",
"(",
"family_name",
"=",
"column_family_id",
",",
"column_qualifier",
"=",
"column",
",",
"append_value",
"=",
"value",
")",
"self",
".",
"_rule_pb_list",
".",
"append",
"(",
"rule_pb",
")"
] | Appends a value to an existing cell.
.. note::
This method adds a read-modify rule protobuf to the accumulated
read-modify rules on this row, but does not make an API
request. To actually send an API request (with the rules) to the
Google Cloud Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_append_cell_value]
:end-before: [END bigtable_row_append_cell_value]
:type column_family_id: str
:param column_family_id: The column family that contains the column.
Must be of the form
``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family where the cell
is located.
:type value: bytes
:param value: The value to append to the existing value in the cell. If
the targeted cell is unset, it will be treated as
containing the empty string. | [
"Appends",
"a",
"value",
"to",
"an",
"existing",
"cell",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L789-L824 |
27,832 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row.py | AppendRow.increment_cell_value | def increment_cell_value(self, column_family_id, column, int_value):
"""Increments a value in an existing cell.
Assumes the value in the cell is stored as a 64 bit integer
serialized to bytes.
.. note::
This method adds a read-modify rule protobuf to the accumulated
read-modify rules on this row, but does not make an API
request. To actually send an API request (with the rules) to the
Google Cloud Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_increment_cell_value]
:end-before: [END bigtable_row_increment_cell_value]
:type column_family_id: str
:param column_family_id: The column family that contains the column.
Must be of the form
``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family where the cell
is located.
:type int_value: int
:param int_value: The value to increment the existing value in the cell
by. If the targeted cell is unset, it will be treated
as containing a zero. Otherwise, the targeted cell
must contain an 8-byte value (interpreted as a 64-bit
big-endian signed integer), or the entire request
will fail.
"""
column = _to_bytes(column)
rule_pb = data_v2_pb2.ReadModifyWriteRule(
family_name=column_family_id,
column_qualifier=column,
increment_amount=int_value,
)
self._rule_pb_list.append(rule_pb) | python | def increment_cell_value(self, column_family_id, column, int_value):
"""Increments a value in an existing cell.
Assumes the value in the cell is stored as a 64 bit integer
serialized to bytes.
.. note::
This method adds a read-modify rule protobuf to the accumulated
read-modify rules on this row, but does not make an API
request. To actually send an API request (with the rules) to the
Google Cloud Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_increment_cell_value]
:end-before: [END bigtable_row_increment_cell_value]
:type column_family_id: str
:param column_family_id: The column family that contains the column.
Must be of the form
``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family where the cell
is located.
:type int_value: int
:param int_value: The value to increment the existing value in the cell
by. If the targeted cell is unset, it will be treated
as containing a zero. Otherwise, the targeted cell
must contain an 8-byte value (interpreted as a 64-bit
big-endian signed integer), or the entire request
will fail.
"""
column = _to_bytes(column)
rule_pb = data_v2_pb2.ReadModifyWriteRule(
family_name=column_family_id,
column_qualifier=column,
increment_amount=int_value,
)
self._rule_pb_list.append(rule_pb) | [
"def",
"increment_cell_value",
"(",
"self",
",",
"column_family_id",
",",
"column",
",",
"int_value",
")",
":",
"column",
"=",
"_to_bytes",
"(",
"column",
")",
"rule_pb",
"=",
"data_v2_pb2",
".",
"ReadModifyWriteRule",
"(",
"family_name",
"=",
"column_family_id",
",",
"column_qualifier",
"=",
"column",
",",
"increment_amount",
"=",
"int_value",
",",
")",
"self",
".",
"_rule_pb_list",
".",
"append",
"(",
"rule_pb",
")"
] | Increments a value in an existing cell.
Assumes the value in the cell is stored as a 64 bit integer
serialized to bytes.
.. note::
This method adds a read-modify rule protobuf to the accumulated
read-modify rules on this row, but does not make an API
request. To actually send an API request (with the rules) to the
Google Cloud Bigtable API, call :meth:`commit`.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_increment_cell_value]
:end-before: [END bigtable_row_increment_cell_value]
:type column_family_id: str
:param column_family_id: The column family that contains the column.
Must be of the form
``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
:type column: bytes
:param column: The column within the column family where the cell
is located.
:type int_value: int
:param int_value: The value to increment the existing value in the cell
by. If the targeted cell is unset, it will be treated
as containing a zero. Otherwise, the targeted cell
must contain an 8-byte value (interpreted as a 64-bit
big-endian signed integer), or the entire request
will fail. | [
"Increments",
"a",
"value",
"in",
"an",
"existing",
"cell",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L826-L868 |
27,833 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row.py | AppendRow.commit | def commit(self):
"""Makes a ``ReadModifyWriteRow`` API request.
This commits modifications made by :meth:`append_cell_value` and
:meth:`increment_cell_value`. If no modifications were made, makes
no API request and just returns ``{}``.
Modifies a row atomically, reading the latest existing
timestamp / value from the specified columns and writing a new value by
appending / incrementing. The new cell created uses either the current
server time or the highest timestamp of a cell in that column (if it
exceeds the server time).
After committing the accumulated mutations, resets the local mutations.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_commit]
:end-before: [END bigtable_row_commit]
:rtype: dict
:returns: The new contents of all modified cells. Returned as a
dictionary of column families, each of which holds a
dictionary of columns. Each column contains a list of cells
modified. Each cell is represented with a two-tuple with the
value (in bytes) and the timestamp for the cell.
:raises: :class:`ValueError <exceptions.ValueError>` if the number of
mutations exceeds the :data:`MAX_MUTATIONS`.
"""
num_mutations = len(self._rule_pb_list)
if num_mutations == 0:
return {}
if num_mutations > MAX_MUTATIONS:
raise ValueError(
"%d total append mutations exceed the maximum "
"allowable %d." % (num_mutations, MAX_MUTATIONS)
)
data_client = self._table._instance._client.table_data_client
row_response = data_client.read_modify_write_row(
table_name=self._table.name, row_key=self._row_key, rules=self._rule_pb_list
)
# Reset modifications after commit-ing request.
self.clear()
# NOTE: We expect row_response.key == self._row_key but don't check.
return _parse_rmw_row_response(row_response) | python | def commit(self):
"""Makes a ``ReadModifyWriteRow`` API request.
This commits modifications made by :meth:`append_cell_value` and
:meth:`increment_cell_value`. If no modifications were made, makes
no API request and just returns ``{}``.
Modifies a row atomically, reading the latest existing
timestamp / value from the specified columns and writing a new value by
appending / incrementing. The new cell created uses either the current
server time or the highest timestamp of a cell in that column (if it
exceeds the server time).
After committing the accumulated mutations, resets the local mutations.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_commit]
:end-before: [END bigtable_row_commit]
:rtype: dict
:returns: The new contents of all modified cells. Returned as a
dictionary of column families, each of which holds a
dictionary of columns. Each column contains a list of cells
modified. Each cell is represented with a two-tuple with the
value (in bytes) and the timestamp for the cell.
:raises: :class:`ValueError <exceptions.ValueError>` if the number of
mutations exceeds the :data:`MAX_MUTATIONS`.
"""
num_mutations = len(self._rule_pb_list)
if num_mutations == 0:
return {}
if num_mutations > MAX_MUTATIONS:
raise ValueError(
"%d total append mutations exceed the maximum "
"allowable %d." % (num_mutations, MAX_MUTATIONS)
)
data_client = self._table._instance._client.table_data_client
row_response = data_client.read_modify_write_row(
table_name=self._table.name, row_key=self._row_key, rules=self._rule_pb_list
)
# Reset modifications after commit-ing request.
self.clear()
# NOTE: We expect row_response.key == self._row_key but don't check.
return _parse_rmw_row_response(row_response) | [
"def",
"commit",
"(",
"self",
")",
":",
"num_mutations",
"=",
"len",
"(",
"self",
".",
"_rule_pb_list",
")",
"if",
"num_mutations",
"==",
"0",
":",
"return",
"{",
"}",
"if",
"num_mutations",
">",
"MAX_MUTATIONS",
":",
"raise",
"ValueError",
"(",
"\"%d total append mutations exceed the maximum \"",
"\"allowable %d.\"",
"%",
"(",
"num_mutations",
",",
"MAX_MUTATIONS",
")",
")",
"data_client",
"=",
"self",
".",
"_table",
".",
"_instance",
".",
"_client",
".",
"table_data_client",
"row_response",
"=",
"data_client",
".",
"read_modify_write_row",
"(",
"table_name",
"=",
"self",
".",
"_table",
".",
"name",
",",
"row_key",
"=",
"self",
".",
"_row_key",
",",
"rules",
"=",
"self",
".",
"_rule_pb_list",
")",
"# Reset modifications after commit-ing request.",
"self",
".",
"clear",
"(",
")",
"# NOTE: We expect row_response.key == self._row_key but don't check.",
"return",
"_parse_rmw_row_response",
"(",
"row_response",
")"
] | Makes a ``ReadModifyWriteRow`` API request.
This commits modifications made by :meth:`append_cell_value` and
:meth:`increment_cell_value`. If no modifications were made, makes
no API request and just returns ``{}``.
Modifies a row atomically, reading the latest existing
timestamp / value from the specified columns and writing a new value by
appending / incrementing. The new cell created uses either the current
server time or the highest timestamp of a cell in that column (if it
exceeds the server time).
After committing the accumulated mutations, resets the local mutations.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_commit]
:end-before: [END bigtable_row_commit]
:rtype: dict
:returns: The new contents of all modified cells. Returned as a
dictionary of column families, each of which holds a
dictionary of columns. Each column contains a list of cells
modified. Each cell is represented with a two-tuple with the
value (in bytes) and the timestamp for the cell.
:raises: :class:`ValueError <exceptions.ValueError>` if the number of
mutations exceeds the :data:`MAX_MUTATIONS`. | [
"Makes",
"a",
"ReadModifyWriteRow",
"API",
"request",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L870-L918 |
27,834 | googleapis/google-cloud-python | api_core/google/api_core/gapic_v1/config.py | _retry_from_retry_config | def _retry_from_retry_config(retry_params, retry_codes):
"""Creates a Retry object given a gapic retry configuration.
Args:
retry_params (dict): The retry parameter values, for example::
{
"initial_retry_delay_millis": 1000,
"retry_delay_multiplier": 2.5,
"max_retry_delay_millis": 120000,
"initial_rpc_timeout_millis": 120000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 120000,
"total_timeout_millis": 600000
}
retry_codes (sequence[str]): The list of retryable gRPC error code
names.
Returns:
google.api_core.retry.Retry: The default retry object for the method.
"""
exception_classes = [
_exception_class_for_grpc_status_name(code) for code in retry_codes
]
return retry.Retry(
retry.if_exception_type(*exception_classes),
initial=(retry_params["initial_retry_delay_millis"] / _MILLIS_PER_SECOND),
maximum=(retry_params["max_retry_delay_millis"] / _MILLIS_PER_SECOND),
multiplier=retry_params["retry_delay_multiplier"],
deadline=retry_params["total_timeout_millis"] / _MILLIS_PER_SECOND,
) | python | def _retry_from_retry_config(retry_params, retry_codes):
"""Creates a Retry object given a gapic retry configuration.
Args:
retry_params (dict): The retry parameter values, for example::
{
"initial_retry_delay_millis": 1000,
"retry_delay_multiplier": 2.5,
"max_retry_delay_millis": 120000,
"initial_rpc_timeout_millis": 120000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 120000,
"total_timeout_millis": 600000
}
retry_codes (sequence[str]): The list of retryable gRPC error code
names.
Returns:
google.api_core.retry.Retry: The default retry object for the method.
"""
exception_classes = [
_exception_class_for_grpc_status_name(code) for code in retry_codes
]
return retry.Retry(
retry.if_exception_type(*exception_classes),
initial=(retry_params["initial_retry_delay_millis"] / _MILLIS_PER_SECOND),
maximum=(retry_params["max_retry_delay_millis"] / _MILLIS_PER_SECOND),
multiplier=retry_params["retry_delay_multiplier"],
deadline=retry_params["total_timeout_millis"] / _MILLIS_PER_SECOND,
) | [
"def",
"_retry_from_retry_config",
"(",
"retry_params",
",",
"retry_codes",
")",
":",
"exception_classes",
"=",
"[",
"_exception_class_for_grpc_status_name",
"(",
"code",
")",
"for",
"code",
"in",
"retry_codes",
"]",
"return",
"retry",
".",
"Retry",
"(",
"retry",
".",
"if_exception_type",
"(",
"*",
"exception_classes",
")",
",",
"initial",
"=",
"(",
"retry_params",
"[",
"\"initial_retry_delay_millis\"",
"]",
"/",
"_MILLIS_PER_SECOND",
")",
",",
"maximum",
"=",
"(",
"retry_params",
"[",
"\"max_retry_delay_millis\"",
"]",
"/",
"_MILLIS_PER_SECOND",
")",
",",
"multiplier",
"=",
"retry_params",
"[",
"\"retry_delay_multiplier\"",
"]",
",",
"deadline",
"=",
"retry_params",
"[",
"\"total_timeout_millis\"",
"]",
"/",
"_MILLIS_PER_SECOND",
",",
")"
] | Creates a Retry object given a gapic retry configuration.
Args:
retry_params (dict): The retry parameter values, for example::
{
"initial_retry_delay_millis": 1000,
"retry_delay_multiplier": 2.5,
"max_retry_delay_millis": 120000,
"initial_rpc_timeout_millis": 120000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 120000,
"total_timeout_millis": 600000
}
retry_codes (sequence[str]): The list of retryable gRPC error code
names.
Returns:
google.api_core.retry.Retry: The default retry object for the method. | [
"Creates",
"a",
"Retry",
"object",
"given",
"a",
"gapic",
"retry",
"configuration",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/gapic_v1/config.py#L48-L79 |
27,835 | googleapis/google-cloud-python | api_core/google/api_core/gapic_v1/config.py | _timeout_from_retry_config | def _timeout_from_retry_config(retry_params):
"""Creates a ExponentialTimeout object given a gapic retry configuration.
Args:
retry_params (dict): The retry parameter values, for example::
{
"initial_retry_delay_millis": 1000,
"retry_delay_multiplier": 2.5,
"max_retry_delay_millis": 120000,
"initial_rpc_timeout_millis": 120000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 120000,
"total_timeout_millis": 600000
}
Returns:
google.api_core.retry.ExponentialTimeout: The default time object for
the method.
"""
return timeout.ExponentialTimeout(
initial=(retry_params["initial_rpc_timeout_millis"] / _MILLIS_PER_SECOND),
maximum=(retry_params["max_rpc_timeout_millis"] / _MILLIS_PER_SECOND),
multiplier=retry_params["rpc_timeout_multiplier"],
deadline=(retry_params["total_timeout_millis"] / _MILLIS_PER_SECOND),
) | python | def _timeout_from_retry_config(retry_params):
"""Creates a ExponentialTimeout object given a gapic retry configuration.
Args:
retry_params (dict): The retry parameter values, for example::
{
"initial_retry_delay_millis": 1000,
"retry_delay_multiplier": 2.5,
"max_retry_delay_millis": 120000,
"initial_rpc_timeout_millis": 120000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 120000,
"total_timeout_millis": 600000
}
Returns:
google.api_core.retry.ExponentialTimeout: The default time object for
the method.
"""
return timeout.ExponentialTimeout(
initial=(retry_params["initial_rpc_timeout_millis"] / _MILLIS_PER_SECOND),
maximum=(retry_params["max_rpc_timeout_millis"] / _MILLIS_PER_SECOND),
multiplier=retry_params["rpc_timeout_multiplier"],
deadline=(retry_params["total_timeout_millis"] / _MILLIS_PER_SECOND),
) | [
"def",
"_timeout_from_retry_config",
"(",
"retry_params",
")",
":",
"return",
"timeout",
".",
"ExponentialTimeout",
"(",
"initial",
"=",
"(",
"retry_params",
"[",
"\"initial_rpc_timeout_millis\"",
"]",
"/",
"_MILLIS_PER_SECOND",
")",
",",
"maximum",
"=",
"(",
"retry_params",
"[",
"\"max_rpc_timeout_millis\"",
"]",
"/",
"_MILLIS_PER_SECOND",
")",
",",
"multiplier",
"=",
"retry_params",
"[",
"\"rpc_timeout_multiplier\"",
"]",
",",
"deadline",
"=",
"(",
"retry_params",
"[",
"\"total_timeout_millis\"",
"]",
"/",
"_MILLIS_PER_SECOND",
")",
",",
")"
] | Creates a ExponentialTimeout object given a gapic retry configuration.
Args:
retry_params (dict): The retry parameter values, for example::
{
"initial_retry_delay_millis": 1000,
"retry_delay_multiplier": 2.5,
"max_retry_delay_millis": 120000,
"initial_rpc_timeout_millis": 120000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 120000,
"total_timeout_millis": 600000
}
Returns:
google.api_core.retry.ExponentialTimeout: The default time object for
the method. | [
"Creates",
"a",
"ExponentialTimeout",
"object",
"given",
"a",
"gapic",
"retry",
"configuration",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/gapic_v1/config.py#L82-L107 |
27,836 | googleapis/google-cloud-python | api_core/google/api_core/gapic_v1/config.py | parse_method_configs | def parse_method_configs(interface_config):
"""Creates default retry and timeout objects for each method in a gapic
interface config.
Args:
interface_config (Mapping): The interface config section of the full
gapic library config. For example, If the full configuration has
an interface named ``google.example.v1.ExampleService`` you would
pass in just that interface's configuration, for example
``gapic_config['interfaces']['google.example.v1.ExampleService']``.
Returns:
Mapping[str, MethodConfig]: A mapping of RPC method names to their
configuration.
"""
# Grab all the retry codes
retry_codes_map = {
name: retry_codes
for name, retry_codes in six.iteritems(interface_config.get("retry_codes", {}))
}
# Grab all of the retry params
retry_params_map = {
name: retry_params
for name, retry_params in six.iteritems(
interface_config.get("retry_params", {})
)
}
# Iterate through all the API methods and create a flat MethodConfig
# instance for each one.
method_configs = {}
for method_name, method_params in six.iteritems(
interface_config.get("methods", {})
):
retry_params_name = method_params.get("retry_params_name")
if retry_params_name is not None:
retry_params = retry_params_map[retry_params_name]
retry_ = _retry_from_retry_config(
retry_params, retry_codes_map[method_params["retry_codes_name"]]
)
timeout_ = _timeout_from_retry_config(retry_params)
# No retry config, so this is a non-retryable method.
else:
retry_ = None
timeout_ = timeout.ConstantTimeout(
method_params["timeout_millis"] / _MILLIS_PER_SECOND
)
method_configs[method_name] = MethodConfig(retry=retry_, timeout=timeout_)
return method_configs | python | def parse_method_configs(interface_config):
"""Creates default retry and timeout objects for each method in a gapic
interface config.
Args:
interface_config (Mapping): The interface config section of the full
gapic library config. For example, If the full configuration has
an interface named ``google.example.v1.ExampleService`` you would
pass in just that interface's configuration, for example
``gapic_config['interfaces']['google.example.v1.ExampleService']``.
Returns:
Mapping[str, MethodConfig]: A mapping of RPC method names to their
configuration.
"""
# Grab all the retry codes
retry_codes_map = {
name: retry_codes
for name, retry_codes in six.iteritems(interface_config.get("retry_codes", {}))
}
# Grab all of the retry params
retry_params_map = {
name: retry_params
for name, retry_params in six.iteritems(
interface_config.get("retry_params", {})
)
}
# Iterate through all the API methods and create a flat MethodConfig
# instance for each one.
method_configs = {}
for method_name, method_params in six.iteritems(
interface_config.get("methods", {})
):
retry_params_name = method_params.get("retry_params_name")
if retry_params_name is not None:
retry_params = retry_params_map[retry_params_name]
retry_ = _retry_from_retry_config(
retry_params, retry_codes_map[method_params["retry_codes_name"]]
)
timeout_ = _timeout_from_retry_config(retry_params)
# No retry config, so this is a non-retryable method.
else:
retry_ = None
timeout_ = timeout.ConstantTimeout(
method_params["timeout_millis"] / _MILLIS_PER_SECOND
)
method_configs[method_name] = MethodConfig(retry=retry_, timeout=timeout_)
return method_configs | [
"def",
"parse_method_configs",
"(",
"interface_config",
")",
":",
"# Grab all the retry codes",
"retry_codes_map",
"=",
"{",
"name",
":",
"retry_codes",
"for",
"name",
",",
"retry_codes",
"in",
"six",
".",
"iteritems",
"(",
"interface_config",
".",
"get",
"(",
"\"retry_codes\"",
",",
"{",
"}",
")",
")",
"}",
"# Grab all of the retry params",
"retry_params_map",
"=",
"{",
"name",
":",
"retry_params",
"for",
"name",
",",
"retry_params",
"in",
"six",
".",
"iteritems",
"(",
"interface_config",
".",
"get",
"(",
"\"retry_params\"",
",",
"{",
"}",
")",
")",
"}",
"# Iterate through all the API methods and create a flat MethodConfig",
"# instance for each one.",
"method_configs",
"=",
"{",
"}",
"for",
"method_name",
",",
"method_params",
"in",
"six",
".",
"iteritems",
"(",
"interface_config",
".",
"get",
"(",
"\"methods\"",
",",
"{",
"}",
")",
")",
":",
"retry_params_name",
"=",
"method_params",
".",
"get",
"(",
"\"retry_params_name\"",
")",
"if",
"retry_params_name",
"is",
"not",
"None",
":",
"retry_params",
"=",
"retry_params_map",
"[",
"retry_params_name",
"]",
"retry_",
"=",
"_retry_from_retry_config",
"(",
"retry_params",
",",
"retry_codes_map",
"[",
"method_params",
"[",
"\"retry_codes_name\"",
"]",
"]",
")",
"timeout_",
"=",
"_timeout_from_retry_config",
"(",
"retry_params",
")",
"# No retry config, so this is a non-retryable method.",
"else",
":",
"retry_",
"=",
"None",
"timeout_",
"=",
"timeout",
".",
"ConstantTimeout",
"(",
"method_params",
"[",
"\"timeout_millis\"",
"]",
"/",
"_MILLIS_PER_SECOND",
")",
"method_configs",
"[",
"method_name",
"]",
"=",
"MethodConfig",
"(",
"retry",
"=",
"retry_",
",",
"timeout",
"=",
"timeout_",
")",
"return",
"method_configs"
] | Creates default retry and timeout objects for each method in a gapic
interface config.
Args:
interface_config (Mapping): The interface config section of the full
gapic library config. For example, If the full configuration has
an interface named ``google.example.v1.ExampleService`` you would
pass in just that interface's configuration, for example
``gapic_config['interfaces']['google.example.v1.ExampleService']``.
Returns:
Mapping[str, MethodConfig]: A mapping of RPC method names to their
configuration. | [
"Creates",
"default",
"retry",
"and",
"timeout",
"objects",
"for",
"each",
"method",
"in",
"a",
"gapic",
"interface",
"config",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/gapic_v1/config.py#L113-L167 |
27,837 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/futures.py | Future.done | def done(self):
"""Return True the future is done, False otherwise.
This still returns True in failure cases; checking :meth:`result` or
:meth:`exception` is the canonical way to assess success or failure.
"""
return self._exception != self._SENTINEL or self._result != self._SENTINEL | python | def done(self):
"""Return True the future is done, False otherwise.
This still returns True in failure cases; checking :meth:`result` or
:meth:`exception` is the canonical way to assess success or failure.
"""
return self._exception != self._SENTINEL or self._result != self._SENTINEL | [
"def",
"done",
"(",
"self",
")",
":",
"return",
"self",
".",
"_exception",
"!=",
"self",
".",
"_SENTINEL",
"or",
"self",
".",
"_result",
"!=",
"self",
".",
"_SENTINEL"
] | Return True the future is done, False otherwise.
This still returns True in failure cases; checking :meth:`result` or
:meth:`exception` is the canonical way to assess success or failure. | [
"Return",
"True",
"the",
"future",
"is",
"done",
"False",
"otherwise",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/futures.py#L81-L87 |
27,838 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/futures.py | Future.exception | def exception(self, timeout=None):
"""Return the exception raised by the call, if any.
This blocks until the message has successfully been published, and
returns the exception. If the call succeeded, return None.
Args:
timeout (Union[int, float]): The number of seconds before this call
times out and raises TimeoutError.
Raises:
TimeoutError: If the request times out.
Returns:
Exception: The exception raised by the call, if any.
"""
# Wait until the future is done.
if not self._completed.wait(timeout=timeout):
raise exceptions.TimeoutError("Timed out waiting for result.")
# If the batch completed successfully, this should return None.
if self._result != self._SENTINEL:
return None
# Okay, this batch had an error; this should return it.
return self._exception | python | def exception(self, timeout=None):
"""Return the exception raised by the call, if any.
This blocks until the message has successfully been published, and
returns the exception. If the call succeeded, return None.
Args:
timeout (Union[int, float]): The number of seconds before this call
times out and raises TimeoutError.
Raises:
TimeoutError: If the request times out.
Returns:
Exception: The exception raised by the call, if any.
"""
# Wait until the future is done.
if not self._completed.wait(timeout=timeout):
raise exceptions.TimeoutError("Timed out waiting for result.")
# If the batch completed successfully, this should return None.
if self._result != self._SENTINEL:
return None
# Okay, this batch had an error; this should return it.
return self._exception | [
"def",
"exception",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"# Wait until the future is done.",
"if",
"not",
"self",
".",
"_completed",
".",
"wait",
"(",
"timeout",
"=",
"timeout",
")",
":",
"raise",
"exceptions",
".",
"TimeoutError",
"(",
"\"Timed out waiting for result.\"",
")",
"# If the batch completed successfully, this should return None.",
"if",
"self",
".",
"_result",
"!=",
"self",
".",
"_SENTINEL",
":",
"return",
"None",
"# Okay, this batch had an error; this should return it.",
"return",
"self",
".",
"_exception"
] | Return the exception raised by the call, if any.
This blocks until the message has successfully been published, and
returns the exception. If the call succeeded, return None.
Args:
timeout (Union[int, float]): The number of seconds before this call
times out and raises TimeoutError.
Raises:
TimeoutError: If the request times out.
Returns:
Exception: The exception raised by the call, if any. | [
"Return",
"the",
"exception",
"raised",
"by",
"the",
"call",
"if",
"any",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/futures.py#L115-L140 |
27,839 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/futures.py | Future.add_done_callback | def add_done_callback(self, fn):
"""Attach the provided callable to the future.
The provided function is called, with this future as its only argument,
when the future finishes running.
"""
if self.done():
return fn(self)
self._callbacks.append(fn) | python | def add_done_callback(self, fn):
"""Attach the provided callable to the future.
The provided function is called, with this future as its only argument,
when the future finishes running.
"""
if self.done():
return fn(self)
self._callbacks.append(fn) | [
"def",
"add_done_callback",
"(",
"self",
",",
"fn",
")",
":",
"if",
"self",
".",
"done",
"(",
")",
":",
"return",
"fn",
"(",
"self",
")",
"self",
".",
"_callbacks",
".",
"append",
"(",
"fn",
")"
] | Attach the provided callable to the future.
The provided function is called, with this future as its only argument,
when the future finishes running. | [
"Attach",
"the",
"provided",
"callable",
"to",
"the",
"future",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/futures.py#L142-L150 |
27,840 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/futures.py | Future.set_result | def set_result(self, result):
"""Set the result of the future to the provided result.
Args:
result (Any): The result
"""
# Sanity check: A future can only complete once.
if self.done():
raise RuntimeError("set_result can only be called once.")
# Set the result and trigger the future.
self._result = result
self._trigger() | python | def set_result(self, result):
"""Set the result of the future to the provided result.
Args:
result (Any): The result
"""
# Sanity check: A future can only complete once.
if self.done():
raise RuntimeError("set_result can only be called once.")
# Set the result and trigger the future.
self._result = result
self._trigger() | [
"def",
"set_result",
"(",
"self",
",",
"result",
")",
":",
"# Sanity check: A future can only complete once.",
"if",
"self",
".",
"done",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"set_result can only be called once.\"",
")",
"# Set the result and trigger the future.",
"self",
".",
"_result",
"=",
"result",
"self",
".",
"_trigger",
"(",
")"
] | Set the result of the future to the provided result.
Args:
result (Any): The result | [
"Set",
"the",
"result",
"of",
"the",
"future",
"to",
"the",
"provided",
"result",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/futures.py#L152-L164 |
27,841 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/futures.py | Future.set_exception | def set_exception(self, exception):
"""Set the result of the future to the given exception.
Args:
exception (:exc:`Exception`): The exception raised.
"""
# Sanity check: A future can only complete once.
if self.done():
raise RuntimeError("set_exception can only be called once.")
# Set the exception and trigger the future.
self._exception = exception
self._trigger() | python | def set_exception(self, exception):
"""Set the result of the future to the given exception.
Args:
exception (:exc:`Exception`): The exception raised.
"""
# Sanity check: A future can only complete once.
if self.done():
raise RuntimeError("set_exception can only be called once.")
# Set the exception and trigger the future.
self._exception = exception
self._trigger() | [
"def",
"set_exception",
"(",
"self",
",",
"exception",
")",
":",
"# Sanity check: A future can only complete once.",
"if",
"self",
".",
"done",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"set_exception can only be called once.\"",
")",
"# Set the exception and trigger the future.",
"self",
".",
"_exception",
"=",
"exception",
"self",
".",
"_trigger",
"(",
")"
] | Set the result of the future to the given exception.
Args:
exception (:exc:`Exception`): The exception raised. | [
"Set",
"the",
"result",
"of",
"the",
"future",
"to",
"the",
"given",
"exception",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/futures.py#L166-L178 |
27,842 | googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/futures.py | Future._trigger | def _trigger(self):
"""Trigger all callbacks registered to this Future.
This method is called internally by the batch once the batch
completes.
Args:
message_id (str): The message ID, as a string.
"""
self._completed.set()
for callback in self._callbacks:
callback(self) | python | def _trigger(self):
"""Trigger all callbacks registered to this Future.
This method is called internally by the batch once the batch
completes.
Args:
message_id (str): The message ID, as a string.
"""
self._completed.set()
for callback in self._callbacks:
callback(self) | [
"def",
"_trigger",
"(",
"self",
")",
":",
"self",
".",
"_completed",
".",
"set",
"(",
")",
"for",
"callback",
"in",
"self",
".",
"_callbacks",
":",
"callback",
"(",
"self",
")"
] | Trigger all callbacks registered to this Future.
This method is called internally by the batch once the batch
completes.
Args:
message_id (str): The message ID, as a string. | [
"Trigger",
"all",
"callbacks",
"registered",
"to",
"this",
"Future",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/futures.py#L180-L191 |
27,843 | googleapis/google-cloud-python | bigquery_storage/google/cloud/bigquery_storage_v1beta1/gapic/big_query_storage_client.py | BigQueryStorageClient.create_read_session | def create_read_session(
self,
table_reference,
parent,
table_modifiers=None,
requested_streams=None,
read_options=None,
format_=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a new read session. A read session divides the contents of a
BigQuery table into one or more streams, which can then be used to read
data from the table. The read session also specifies properties of the
data to be read, such as a list of columns or a push-down filter describing
the rows to be returned.
A particular row can be read by at most one stream. When the caller has
reached the end of each stream in the session, then all the data in the
table has been read.
Read sessions automatically expire 24 hours after they are created and do
not require manual clean-up by the caller.
Example:
>>> from google.cloud import bigquery_storage_v1beta1
>>>
>>> client = bigquery_storage_v1beta1.BigQueryStorageClient()
>>>
>>> # TODO: Initialize `table_reference`:
>>> table_reference = {}
>>>
>>> # TODO: Initialize `parent`:
>>> parent = ''
>>>
>>> response = client.create_read_session(table_reference, parent)
Args:
table_reference (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.TableReference]): Required. Reference to the table to read.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.TableReference`
parent (str): Required. String of the form ``projects/{project_id}`` indicating the
project this ReadSession is associated with. This is the project that
will be billed for usage.
table_modifiers (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.TableModifiers]): Optional. Any modifiers to the Table (e.g. snapshot timestamp).
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.TableModifiers`
requested_streams (int): Optional. Initial number of streams. If unset or 0, we will
provide a value of streams so as to produce reasonable throughput. Must be
non-negative. The number of streams may be lower than the requested number,
depending on the amount parallelism that is reasonable for the table and
the maximum amount of parallelism allowed by the system.
Streams must be read starting from offset 0.
read_options (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.TableReadOptions]): Optional. Read options for this session (e.g. column selection, filters).
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.TableReadOptions`
format_ (~google.cloud.bigquery_storage_v1beta1.types.DataFormat): Data output format. Currently default to Avro.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_storage_v1beta1.types.ReadSession` 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_read_session" not in self._inner_api_calls:
self._inner_api_calls[
"create_read_session"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_read_session,
default_retry=self._method_configs["CreateReadSession"].retry,
default_timeout=self._method_configs["CreateReadSession"].timeout,
client_info=self._client_info,
)
request = storage_pb2.CreateReadSessionRequest(
table_reference=table_reference,
parent=parent,
table_modifiers=table_modifiers,
requested_streams=requested_streams,
read_options=read_options,
format=format_,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [
("table_reference.project_id", table_reference.project_id),
("table_reference.dataset_id", table_reference.dataset_id),
]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( # pragma: no cover
routing_header
)
metadata.append(routing_metadata) # pragma: no cover
return self._inner_api_calls["create_read_session"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def create_read_session(
self,
table_reference,
parent,
table_modifiers=None,
requested_streams=None,
read_options=None,
format_=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a new read session. A read session divides the contents of a
BigQuery table into one or more streams, which can then be used to read
data from the table. The read session also specifies properties of the
data to be read, such as a list of columns or a push-down filter describing
the rows to be returned.
A particular row can be read by at most one stream. When the caller has
reached the end of each stream in the session, then all the data in the
table has been read.
Read sessions automatically expire 24 hours after they are created and do
not require manual clean-up by the caller.
Example:
>>> from google.cloud import bigquery_storage_v1beta1
>>>
>>> client = bigquery_storage_v1beta1.BigQueryStorageClient()
>>>
>>> # TODO: Initialize `table_reference`:
>>> table_reference = {}
>>>
>>> # TODO: Initialize `parent`:
>>> parent = ''
>>>
>>> response = client.create_read_session(table_reference, parent)
Args:
table_reference (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.TableReference]): Required. Reference to the table to read.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.TableReference`
parent (str): Required. String of the form ``projects/{project_id}`` indicating the
project this ReadSession is associated with. This is the project that
will be billed for usage.
table_modifiers (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.TableModifiers]): Optional. Any modifiers to the Table (e.g. snapshot timestamp).
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.TableModifiers`
requested_streams (int): Optional. Initial number of streams. If unset or 0, we will
provide a value of streams so as to produce reasonable throughput. Must be
non-negative. The number of streams may be lower than the requested number,
depending on the amount parallelism that is reasonable for the table and
the maximum amount of parallelism allowed by the system.
Streams must be read starting from offset 0.
read_options (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.TableReadOptions]): Optional. Read options for this session (e.g. column selection, filters).
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.TableReadOptions`
format_ (~google.cloud.bigquery_storage_v1beta1.types.DataFormat): Data output format. Currently default to Avro.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_storage_v1beta1.types.ReadSession` 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_read_session" not in self._inner_api_calls:
self._inner_api_calls[
"create_read_session"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_read_session,
default_retry=self._method_configs["CreateReadSession"].retry,
default_timeout=self._method_configs["CreateReadSession"].timeout,
client_info=self._client_info,
)
request = storage_pb2.CreateReadSessionRequest(
table_reference=table_reference,
parent=parent,
table_modifiers=table_modifiers,
requested_streams=requested_streams,
read_options=read_options,
format=format_,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [
("table_reference.project_id", table_reference.project_id),
("table_reference.dataset_id", table_reference.dataset_id),
]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( # pragma: no cover
routing_header
)
metadata.append(routing_metadata) # pragma: no cover
return self._inner_api_calls["create_read_session"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"create_read_session",
"(",
"self",
",",
"table_reference",
",",
"parent",
",",
"table_modifiers",
"=",
"None",
",",
"requested_streams",
"=",
"None",
",",
"read_options",
"=",
"None",
",",
"format_",
"=",
"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",
"\"create_read_session\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"create_read_session\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_read_session",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateReadSession\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateReadSession\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"storage_pb2",
".",
"CreateReadSessionRequest",
"(",
"table_reference",
"=",
"table_reference",
",",
"parent",
"=",
"parent",
",",
"table_modifiers",
"=",
"table_modifiers",
",",
"requested_streams",
"=",
"requested_streams",
",",
"read_options",
"=",
"read_options",
",",
"format",
"=",
"format_",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"table_reference.project_id\"",
",",
"table_reference",
".",
"project_id",
")",
",",
"(",
"\"table_reference.dataset_id\"",
",",
"table_reference",
".",
"dataset_id",
")",
",",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"# pragma: no cover",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"# pragma: no cover",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"create_read_session\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Creates a new read session. A read session divides the contents of a
BigQuery table into one or more streams, which can then be used to read
data from the table. The read session also specifies properties of the
data to be read, such as a list of columns or a push-down filter describing
the rows to be returned.
A particular row can be read by at most one stream. When the caller has
reached the end of each stream in the session, then all the data in the
table has been read.
Read sessions automatically expire 24 hours after they are created and do
not require manual clean-up by the caller.
Example:
>>> from google.cloud import bigquery_storage_v1beta1
>>>
>>> client = bigquery_storage_v1beta1.BigQueryStorageClient()
>>>
>>> # TODO: Initialize `table_reference`:
>>> table_reference = {}
>>>
>>> # TODO: Initialize `parent`:
>>> parent = ''
>>>
>>> response = client.create_read_session(table_reference, parent)
Args:
table_reference (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.TableReference]): Required. Reference to the table to read.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.TableReference`
parent (str): Required. String of the form ``projects/{project_id}`` indicating the
project this ReadSession is associated with. This is the project that
will be billed for usage.
table_modifiers (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.TableModifiers]): Optional. Any modifiers to the Table (e.g. snapshot timestamp).
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.TableModifiers`
requested_streams (int): Optional. Initial number of streams. If unset or 0, we will
provide a value of streams so as to produce reasonable throughput. Must be
non-negative. The number of streams may be lower than the requested number,
depending on the amount parallelism that is reasonable for the table and
the maximum amount of parallelism allowed by the system.
Streams must be read starting from offset 0.
read_options (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.TableReadOptions]): Optional. Read options for this session (e.g. column selection, filters).
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.TableReadOptions`
format_ (~google.cloud.bigquery_storage_v1beta1.types.DataFormat): Data output format. Currently default to Avro.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_storage_v1beta1.types.ReadSession` 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",
"new",
"read",
"session",
".",
"A",
"read",
"session",
"divides",
"the",
"contents",
"of",
"a",
"BigQuery",
"table",
"into",
"one",
"or",
"more",
"streams",
"which",
"can",
"then",
"be",
"used",
"to",
"read",
"data",
"from",
"the",
"table",
".",
"The",
"read",
"session",
"also",
"specifies",
"properties",
"of",
"the",
"data",
"to",
"be",
"read",
"such",
"as",
"a",
"list",
"of",
"columns",
"or",
"a",
"push",
"-",
"down",
"filter",
"describing",
"the",
"rows",
"to",
"be",
"returned",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/gapic/big_query_storage_client.py#L179-L298 |
27,844 | googleapis/google-cloud-python | bigquery_storage/google/cloud/bigquery_storage_v1beta1/gapic/big_query_storage_client.py | BigQueryStorageClient.batch_create_read_session_streams | def batch_create_read_session_streams(
self,
session,
requested_streams,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates additional streams for a ReadSession. This API can be used to
dynamically adjust the parallelism of a batch processing task upwards by
adding additional workers.
Example:
>>> from google.cloud import bigquery_storage_v1beta1
>>>
>>> client = bigquery_storage_v1beta1.BigQueryStorageClient()
>>>
>>> # TODO: Initialize `session`:
>>> session = {}
>>>
>>> # TODO: Initialize `requested_streams`:
>>> requested_streams = 0
>>>
>>> response = client.batch_create_read_session_streams(session, requested_streams)
Args:
session (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.ReadSession]): Required. Must be a non-expired session obtained from a call to
CreateReadSession. Only the name field needs to be set.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.ReadSession`
requested_streams (int): Required. Number of new streams requested. Must be positive.
Number of added streams may be less than this, see CreateReadSessionRequest
for more information.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_storage_v1beta1.types.BatchCreateReadSessionStreamsResponse` 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 "batch_create_read_session_streams" not in self._inner_api_calls:
self._inner_api_calls[
"batch_create_read_session_streams"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.batch_create_read_session_streams,
default_retry=self._method_configs[
"BatchCreateReadSessionStreams"
].retry,
default_timeout=self._method_configs[
"BatchCreateReadSessionStreams"
].timeout,
client_info=self._client_info,
)
request = storage_pb2.BatchCreateReadSessionStreamsRequest(
session=session, requested_streams=requested_streams
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session.name", session.name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( # pragma: no cover
routing_header
)
metadata.append(routing_metadata) # pragma: no cover
return self._inner_api_calls["batch_create_read_session_streams"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def batch_create_read_session_streams(
self,
session,
requested_streams,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates additional streams for a ReadSession. This API can be used to
dynamically adjust the parallelism of a batch processing task upwards by
adding additional workers.
Example:
>>> from google.cloud import bigquery_storage_v1beta1
>>>
>>> client = bigquery_storage_v1beta1.BigQueryStorageClient()
>>>
>>> # TODO: Initialize `session`:
>>> session = {}
>>>
>>> # TODO: Initialize `requested_streams`:
>>> requested_streams = 0
>>>
>>> response = client.batch_create_read_session_streams(session, requested_streams)
Args:
session (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.ReadSession]): Required. Must be a non-expired session obtained from a call to
CreateReadSession. Only the name field needs to be set.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.ReadSession`
requested_streams (int): Required. Number of new streams requested. Must be positive.
Number of added streams may be less than this, see CreateReadSessionRequest
for more information.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_storage_v1beta1.types.BatchCreateReadSessionStreamsResponse` 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 "batch_create_read_session_streams" not in self._inner_api_calls:
self._inner_api_calls[
"batch_create_read_session_streams"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.batch_create_read_session_streams,
default_retry=self._method_configs[
"BatchCreateReadSessionStreams"
].retry,
default_timeout=self._method_configs[
"BatchCreateReadSessionStreams"
].timeout,
client_info=self._client_info,
)
request = storage_pb2.BatchCreateReadSessionStreamsRequest(
session=session, requested_streams=requested_streams
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session.name", session.name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( # pragma: no cover
routing_header
)
metadata.append(routing_metadata) # pragma: no cover
return self._inner_api_calls["batch_create_read_session_streams"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"batch_create_read_session_streams",
"(",
"self",
",",
"session",
",",
"requested_streams",
",",
"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_create_read_session_streams\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"batch_create_read_session_streams\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"batch_create_read_session_streams",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"BatchCreateReadSessionStreams\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"BatchCreateReadSessionStreams\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"storage_pb2",
".",
"BatchCreateReadSessionStreamsRequest",
"(",
"session",
"=",
"session",
",",
"requested_streams",
"=",
"requested_streams",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"session.name\"",
",",
"session",
".",
"name",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"# pragma: no cover",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"# pragma: no cover",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"batch_create_read_session_streams\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Creates additional streams for a ReadSession. This API can be used to
dynamically adjust the parallelism of a batch processing task upwards by
adding additional workers.
Example:
>>> from google.cloud import bigquery_storage_v1beta1
>>>
>>> client = bigquery_storage_v1beta1.BigQueryStorageClient()
>>>
>>> # TODO: Initialize `session`:
>>> session = {}
>>>
>>> # TODO: Initialize `requested_streams`:
>>> requested_streams = 0
>>>
>>> response = client.batch_create_read_session_streams(session, requested_streams)
Args:
session (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.ReadSession]): Required. Must be a non-expired session obtained from a call to
CreateReadSession. Only the name field needs to be set.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_storage_v1beta1.types.ReadSession`
requested_streams (int): Required. Number of new streams requested. Must be positive.
Number of added streams may be less than this, see CreateReadSessionRequest
for more information.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_storage_v1beta1.types.BatchCreateReadSessionStreamsResponse` 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",
"additional",
"streams",
"for",
"a",
"ReadSession",
".",
"This",
"API",
"can",
"be",
"used",
"to",
"dynamically",
"adjust",
"the",
"parallelism",
"of",
"a",
"batch",
"processing",
"task",
"upwards",
"by",
"adding",
"additional",
"workers",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/gapic/big_query_storage_client.py#L385-L472 |
27,845 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/external_config.py | ExternalConfig.to_api_repr | def to_api_repr(self):
"""Build an API representation of this object.
Returns:
Dict[str, Any]:
A dictionary in the format used by the BigQuery API.
"""
config = copy.deepcopy(self._properties)
if self.options is not None:
r = self.options.to_api_repr()
if r != {}:
config[self.options._RESOURCE_NAME] = r
return config | python | def to_api_repr(self):
"""Build an API representation of this object.
Returns:
Dict[str, Any]:
A dictionary in the format used by the BigQuery API.
"""
config = copy.deepcopy(self._properties)
if self.options is not None:
r = self.options.to_api_repr()
if r != {}:
config[self.options._RESOURCE_NAME] = r
return config | [
"def",
"to_api_repr",
"(",
"self",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_properties",
")",
"if",
"self",
".",
"options",
"is",
"not",
"None",
":",
"r",
"=",
"self",
".",
"options",
".",
"to_api_repr",
"(",
")",
"if",
"r",
"!=",
"{",
"}",
":",
"config",
"[",
"self",
".",
"options",
".",
"_RESOURCE_NAME",
"]",
"=",
"r",
"return",
"config"
] | Build an API representation of this object.
Returns:
Dict[str, Any]:
A dictionary in the format used by the BigQuery API. | [
"Build",
"an",
"API",
"representation",
"of",
"this",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/external_config.py#L682-L694 |
27,846 | googleapis/google-cloud-python | bigquery_storage/noxfile.py | lint | def lint(session):
"""Run linters.
Returns a failure if the linters find linting errors or sufficiently
serious code quality issues.
"""
session.install('flake8', *LOCAL_DEPS)
session.install('-e', '.')
session.run(
'flake8', os.path.join('google', 'cloud', 'bigquery_storage_v1beta1'))
session.run('flake8', 'tests') | python | def lint(session):
"""Run linters.
Returns a failure if the linters find linting errors or sufficiently
serious code quality issues.
"""
session.install('flake8', *LOCAL_DEPS)
session.install('-e', '.')
session.run(
'flake8', os.path.join('google', 'cloud', 'bigquery_storage_v1beta1'))
session.run('flake8', 'tests') | [
"def",
"lint",
"(",
"session",
")",
":",
"session",
".",
"install",
"(",
"'flake8'",
",",
"*",
"LOCAL_DEPS",
")",
"session",
".",
"install",
"(",
"'-e'",
",",
"'.'",
")",
"session",
".",
"run",
"(",
"'flake8'",
",",
"os",
".",
"path",
".",
"join",
"(",
"'google'",
",",
"'cloud'",
",",
"'bigquery_storage_v1beta1'",
")",
")",
"session",
".",
"run",
"(",
"'flake8'",
",",
"'tests'",
")"
] | Run linters.
Returns a failure if the linters find linting errors or sufficiently
serious code quality issues. | [
"Run",
"linters",
".",
"Returns",
"a",
"failure",
"if",
"the",
"linters",
"find",
"linting",
"errors",
"or",
"sufficiently",
"serious",
"code",
"quality",
"issues",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/noxfile.py#L63-L73 |
27,847 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | _enum_from_op_string | def _enum_from_op_string(op_string):
"""Convert a string representation of a binary operator to an enum.
These enums come from the protobuf message definition
``StructuredQuery.FieldFilter.Operator``.
Args:
op_string (str): A comparison operation in the form of a string.
Acceptable values are ``<``, ``<=``, ``==``, ``>=``
and ``>``.
Returns:
int: The enum corresponding to ``op_string``.
Raises:
ValueError: If ``op_string`` is not a valid operator.
"""
try:
return _COMPARISON_OPERATORS[op_string]
except KeyError:
choices = ", ".join(sorted(_COMPARISON_OPERATORS.keys()))
msg = _BAD_OP_STRING.format(op_string, choices)
raise ValueError(msg) | python | def _enum_from_op_string(op_string):
"""Convert a string representation of a binary operator to an enum.
These enums come from the protobuf message definition
``StructuredQuery.FieldFilter.Operator``.
Args:
op_string (str): A comparison operation in the form of a string.
Acceptable values are ``<``, ``<=``, ``==``, ``>=``
and ``>``.
Returns:
int: The enum corresponding to ``op_string``.
Raises:
ValueError: If ``op_string`` is not a valid operator.
"""
try:
return _COMPARISON_OPERATORS[op_string]
except KeyError:
choices = ", ".join(sorted(_COMPARISON_OPERATORS.keys()))
msg = _BAD_OP_STRING.format(op_string, choices)
raise ValueError(msg) | [
"def",
"_enum_from_op_string",
"(",
"op_string",
")",
":",
"try",
":",
"return",
"_COMPARISON_OPERATORS",
"[",
"op_string",
"]",
"except",
"KeyError",
":",
"choices",
"=",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"_COMPARISON_OPERATORS",
".",
"keys",
"(",
")",
")",
")",
"msg",
"=",
"_BAD_OP_STRING",
".",
"format",
"(",
"op_string",
",",
"choices",
")",
"raise",
"ValueError",
"(",
"msg",
")"
] | Convert a string representation of a binary operator to an enum.
These enums come from the protobuf message definition
``StructuredQuery.FieldFilter.Operator``.
Args:
op_string (str): A comparison operation in the form of a string.
Acceptable values are ``<``, ``<=``, ``==``, ``>=``
and ``>``.
Returns:
int: The enum corresponding to ``op_string``.
Raises:
ValueError: If ``op_string`` is not a valid operator. | [
"Convert",
"a",
"string",
"representation",
"of",
"a",
"binary",
"operator",
"to",
"an",
"enum",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L825-L847 |
27,848 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | _enum_from_direction | def _enum_from_direction(direction):
"""Convert a string representation of a direction to an enum.
Args:
direction (str): A direction to order by. Must be one of
:attr:`~.firestore.Query.ASCENDING` or
:attr:`~.firestore.Query.DESCENDING`.
Returns:
int: The enum corresponding to ``direction``.
Raises:
ValueError: If ``direction`` is not a valid direction.
"""
if isinstance(direction, int):
return direction
if direction == Query.ASCENDING:
return enums.StructuredQuery.Direction.ASCENDING
elif direction == Query.DESCENDING:
return enums.StructuredQuery.Direction.DESCENDING
else:
msg = _BAD_DIR_STRING.format(direction, Query.ASCENDING, Query.DESCENDING)
raise ValueError(msg) | python | def _enum_from_direction(direction):
"""Convert a string representation of a direction to an enum.
Args:
direction (str): A direction to order by. Must be one of
:attr:`~.firestore.Query.ASCENDING` or
:attr:`~.firestore.Query.DESCENDING`.
Returns:
int: The enum corresponding to ``direction``.
Raises:
ValueError: If ``direction`` is not a valid direction.
"""
if isinstance(direction, int):
return direction
if direction == Query.ASCENDING:
return enums.StructuredQuery.Direction.ASCENDING
elif direction == Query.DESCENDING:
return enums.StructuredQuery.Direction.DESCENDING
else:
msg = _BAD_DIR_STRING.format(direction, Query.ASCENDING, Query.DESCENDING)
raise ValueError(msg) | [
"def",
"_enum_from_direction",
"(",
"direction",
")",
":",
"if",
"isinstance",
"(",
"direction",
",",
"int",
")",
":",
"return",
"direction",
"if",
"direction",
"==",
"Query",
".",
"ASCENDING",
":",
"return",
"enums",
".",
"StructuredQuery",
".",
"Direction",
".",
"ASCENDING",
"elif",
"direction",
"==",
"Query",
".",
"DESCENDING",
":",
"return",
"enums",
".",
"StructuredQuery",
".",
"Direction",
".",
"DESCENDING",
"else",
":",
"msg",
"=",
"_BAD_DIR_STRING",
".",
"format",
"(",
"direction",
",",
"Query",
".",
"ASCENDING",
",",
"Query",
".",
"DESCENDING",
")",
"raise",
"ValueError",
"(",
"msg",
")"
] | Convert a string representation of a direction to an enum.
Args:
direction (str): A direction to order by. Must be one of
:attr:`~.firestore.Query.ASCENDING` or
:attr:`~.firestore.Query.DESCENDING`.
Returns:
int: The enum corresponding to ``direction``.
Raises:
ValueError: If ``direction`` is not a valid direction. | [
"Convert",
"a",
"string",
"representation",
"of",
"a",
"direction",
"to",
"an",
"enum",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L868-L891 |
27,849 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | _filter_pb | def _filter_pb(field_or_unary):
"""Convert a specific protobuf filter to the generic filter type.
Args:
field_or_unary (Union[google.cloud.proto.firestore.v1beta1.\
query_pb2.StructuredQuery.FieldFilter, google.cloud.proto.\
firestore.v1beta1.query_pb2.StructuredQuery.FieldFilter]): A
field or unary filter to convert to a generic filter.
Returns:
google.cloud.firestore_v1beta1.types.\
StructuredQuery.Filter: A "generic" filter.
Raises:
ValueError: If ``field_or_unary`` is not a field or unary filter.
"""
if isinstance(field_or_unary, query_pb2.StructuredQuery.FieldFilter):
return query_pb2.StructuredQuery.Filter(field_filter=field_or_unary)
elif isinstance(field_or_unary, query_pb2.StructuredQuery.UnaryFilter):
return query_pb2.StructuredQuery.Filter(unary_filter=field_or_unary)
else:
raise ValueError("Unexpected filter type", type(field_or_unary), field_or_unary) | python | def _filter_pb(field_or_unary):
"""Convert a specific protobuf filter to the generic filter type.
Args:
field_or_unary (Union[google.cloud.proto.firestore.v1beta1.\
query_pb2.StructuredQuery.FieldFilter, google.cloud.proto.\
firestore.v1beta1.query_pb2.StructuredQuery.FieldFilter]): A
field or unary filter to convert to a generic filter.
Returns:
google.cloud.firestore_v1beta1.types.\
StructuredQuery.Filter: A "generic" filter.
Raises:
ValueError: If ``field_or_unary`` is not a field or unary filter.
"""
if isinstance(field_or_unary, query_pb2.StructuredQuery.FieldFilter):
return query_pb2.StructuredQuery.Filter(field_filter=field_or_unary)
elif isinstance(field_or_unary, query_pb2.StructuredQuery.UnaryFilter):
return query_pb2.StructuredQuery.Filter(unary_filter=field_or_unary)
else:
raise ValueError("Unexpected filter type", type(field_or_unary), field_or_unary) | [
"def",
"_filter_pb",
"(",
"field_or_unary",
")",
":",
"if",
"isinstance",
"(",
"field_or_unary",
",",
"query_pb2",
".",
"StructuredQuery",
".",
"FieldFilter",
")",
":",
"return",
"query_pb2",
".",
"StructuredQuery",
".",
"Filter",
"(",
"field_filter",
"=",
"field_or_unary",
")",
"elif",
"isinstance",
"(",
"field_or_unary",
",",
"query_pb2",
".",
"StructuredQuery",
".",
"UnaryFilter",
")",
":",
"return",
"query_pb2",
".",
"StructuredQuery",
".",
"Filter",
"(",
"unary_filter",
"=",
"field_or_unary",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unexpected filter type\"",
",",
"type",
"(",
"field_or_unary",
")",
",",
"field_or_unary",
")"
] | Convert a specific protobuf filter to the generic filter type.
Args:
field_or_unary (Union[google.cloud.proto.firestore.v1beta1.\
query_pb2.StructuredQuery.FieldFilter, google.cloud.proto.\
firestore.v1beta1.query_pb2.StructuredQuery.FieldFilter]): A
field or unary filter to convert to a generic filter.
Returns:
google.cloud.firestore_v1beta1.types.\
StructuredQuery.Filter: A "generic" filter.
Raises:
ValueError: If ``field_or_unary`` is not a field or unary filter. | [
"Convert",
"a",
"specific",
"protobuf",
"filter",
"to",
"the",
"generic",
"filter",
"type",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L894-L915 |
27,850 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | _cursor_pb | def _cursor_pb(cursor_pair):
"""Convert a cursor pair to a protobuf.
If ``cursor_pair`` is :data:`None`, just returns :data:`None`.
Args:
cursor_pair (Optional[Tuple[list, bool]]): Two-tuple of
* a list of field values.
* a ``before`` flag
Returns:
Optional[google.cloud.firestore_v1beta1.types.Cursor]: A
protobuf cursor corresponding to the values.
"""
if cursor_pair is not None:
data, before = cursor_pair
value_pbs = [_helpers.encode_value(value) for value in data]
return query_pb2.Cursor(values=value_pbs, before=before) | python | def _cursor_pb(cursor_pair):
"""Convert a cursor pair to a protobuf.
If ``cursor_pair`` is :data:`None`, just returns :data:`None`.
Args:
cursor_pair (Optional[Tuple[list, bool]]): Two-tuple of
* a list of field values.
* a ``before`` flag
Returns:
Optional[google.cloud.firestore_v1beta1.types.Cursor]: A
protobuf cursor corresponding to the values.
"""
if cursor_pair is not None:
data, before = cursor_pair
value_pbs = [_helpers.encode_value(value) for value in data]
return query_pb2.Cursor(values=value_pbs, before=before) | [
"def",
"_cursor_pb",
"(",
"cursor_pair",
")",
":",
"if",
"cursor_pair",
"is",
"not",
"None",
":",
"data",
",",
"before",
"=",
"cursor_pair",
"value_pbs",
"=",
"[",
"_helpers",
".",
"encode_value",
"(",
"value",
")",
"for",
"value",
"in",
"data",
"]",
"return",
"query_pb2",
".",
"Cursor",
"(",
"values",
"=",
"value_pbs",
",",
"before",
"=",
"before",
")"
] | Convert a cursor pair to a protobuf.
If ``cursor_pair`` is :data:`None`, just returns :data:`None`.
Args:
cursor_pair (Optional[Tuple[list, bool]]): Two-tuple of
* a list of field values.
* a ``before`` flag
Returns:
Optional[google.cloud.firestore_v1beta1.types.Cursor]: A
protobuf cursor corresponding to the values. | [
"Convert",
"a",
"cursor",
"pair",
"to",
"a",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L918-L936 |
27,851 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | _query_response_to_snapshot | def _query_response_to_snapshot(response_pb, collection, expected_prefix):
"""Parse a query response protobuf to a document snapshot.
Args:
response_pb (google.cloud.proto.firestore.v1beta1.\
firestore_pb2.RunQueryResponse): A
collection (~.firestore_v1beta1.collection.CollectionReference): A
reference to the collection that initiated the query.
expected_prefix (str): The expected prefix for fully-qualified
document names returned in the query results. This can be computed
directly from ``collection`` via :meth:`_parent_info`.
Returns:
Optional[~.firestore.document.DocumentSnapshot]: A
snapshot of the data returned in the query. If ``response_pb.document``
is not set, the snapshot will be :data:`None`.
"""
if not response_pb.HasField("document"):
return None
document_id = _helpers.get_doc_id(response_pb.document, expected_prefix)
reference = collection.document(document_id)
data = _helpers.decode_dict(response_pb.document.fields, collection._client)
snapshot = document.DocumentSnapshot(
reference,
data,
exists=True,
read_time=response_pb.read_time,
create_time=response_pb.document.create_time,
update_time=response_pb.document.update_time,
)
return snapshot | python | def _query_response_to_snapshot(response_pb, collection, expected_prefix):
"""Parse a query response protobuf to a document snapshot.
Args:
response_pb (google.cloud.proto.firestore.v1beta1.\
firestore_pb2.RunQueryResponse): A
collection (~.firestore_v1beta1.collection.CollectionReference): A
reference to the collection that initiated the query.
expected_prefix (str): The expected prefix for fully-qualified
document names returned in the query results. This can be computed
directly from ``collection`` via :meth:`_parent_info`.
Returns:
Optional[~.firestore.document.DocumentSnapshot]: A
snapshot of the data returned in the query. If ``response_pb.document``
is not set, the snapshot will be :data:`None`.
"""
if not response_pb.HasField("document"):
return None
document_id = _helpers.get_doc_id(response_pb.document, expected_prefix)
reference = collection.document(document_id)
data = _helpers.decode_dict(response_pb.document.fields, collection._client)
snapshot = document.DocumentSnapshot(
reference,
data,
exists=True,
read_time=response_pb.read_time,
create_time=response_pb.document.create_time,
update_time=response_pb.document.update_time,
)
return snapshot | [
"def",
"_query_response_to_snapshot",
"(",
"response_pb",
",",
"collection",
",",
"expected_prefix",
")",
":",
"if",
"not",
"response_pb",
".",
"HasField",
"(",
"\"document\"",
")",
":",
"return",
"None",
"document_id",
"=",
"_helpers",
".",
"get_doc_id",
"(",
"response_pb",
".",
"document",
",",
"expected_prefix",
")",
"reference",
"=",
"collection",
".",
"document",
"(",
"document_id",
")",
"data",
"=",
"_helpers",
".",
"decode_dict",
"(",
"response_pb",
".",
"document",
".",
"fields",
",",
"collection",
".",
"_client",
")",
"snapshot",
"=",
"document",
".",
"DocumentSnapshot",
"(",
"reference",
",",
"data",
",",
"exists",
"=",
"True",
",",
"read_time",
"=",
"response_pb",
".",
"read_time",
",",
"create_time",
"=",
"response_pb",
".",
"document",
".",
"create_time",
",",
"update_time",
"=",
"response_pb",
".",
"document",
".",
"update_time",
",",
")",
"return",
"snapshot"
] | Parse a query response protobuf to a document snapshot.
Args:
response_pb (google.cloud.proto.firestore.v1beta1.\
firestore_pb2.RunQueryResponse): A
collection (~.firestore_v1beta1.collection.CollectionReference): A
reference to the collection that initiated the query.
expected_prefix (str): The expected prefix for fully-qualified
document names returned in the query results. This can be computed
directly from ``collection`` via :meth:`_parent_info`.
Returns:
Optional[~.firestore.document.DocumentSnapshot]: A
snapshot of the data returned in the query. If ``response_pb.document``
is not set, the snapshot will be :data:`None`. | [
"Parse",
"a",
"query",
"response",
"protobuf",
"to",
"a",
"document",
"snapshot",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L939-L970 |
27,852 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query.select | def select(self, field_paths):
"""Project documents matching query to a limited set of fields.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
If the current query already has a projection set (i.e. has already
called :meth:`~.firestore_v1beta1.query.Query.select`), this
will overwrite it.
Args:
field_paths (Iterable[str, ...]): An iterable of field paths
(``.``-delimited list of field names) to use as a projection
of document fields in the query results.
Returns:
~.firestore_v1beta1.query.Query: A "projected" query. Acts as
a copy of the current query, modified with the newly added
projection.
Raises:
ValueError: If any ``field_path`` is invalid.
"""
field_paths = list(field_paths)
for field_path in field_paths:
field_path_module.split_field_path(field_path) # raises
new_projection = query_pb2.StructuredQuery.Projection(
fields=[
query_pb2.StructuredQuery.FieldReference(field_path=field_path)
for field_path in field_paths
]
)
return self.__class__(
self._parent,
projection=new_projection,
field_filters=self._field_filters,
orders=self._orders,
limit=self._limit,
offset=self._offset,
start_at=self._start_at,
end_at=self._end_at,
) | python | def select(self, field_paths):
"""Project documents matching query to a limited set of fields.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
If the current query already has a projection set (i.e. has already
called :meth:`~.firestore_v1beta1.query.Query.select`), this
will overwrite it.
Args:
field_paths (Iterable[str, ...]): An iterable of field paths
(``.``-delimited list of field names) to use as a projection
of document fields in the query results.
Returns:
~.firestore_v1beta1.query.Query: A "projected" query. Acts as
a copy of the current query, modified with the newly added
projection.
Raises:
ValueError: If any ``field_path`` is invalid.
"""
field_paths = list(field_paths)
for field_path in field_paths:
field_path_module.split_field_path(field_path) # raises
new_projection = query_pb2.StructuredQuery.Projection(
fields=[
query_pb2.StructuredQuery.FieldReference(field_path=field_path)
for field_path in field_paths
]
)
return self.__class__(
self._parent,
projection=new_projection,
field_filters=self._field_filters,
orders=self._orders,
limit=self._limit,
offset=self._offset,
start_at=self._start_at,
end_at=self._end_at,
) | [
"def",
"select",
"(",
"self",
",",
"field_paths",
")",
":",
"field_paths",
"=",
"list",
"(",
"field_paths",
")",
"for",
"field_path",
"in",
"field_paths",
":",
"field_path_module",
".",
"split_field_path",
"(",
"field_path",
")",
"# raises",
"new_projection",
"=",
"query_pb2",
".",
"StructuredQuery",
".",
"Projection",
"(",
"fields",
"=",
"[",
"query_pb2",
".",
"StructuredQuery",
".",
"FieldReference",
"(",
"field_path",
"=",
"field_path",
")",
"for",
"field_path",
"in",
"field_paths",
"]",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"_parent",
",",
"projection",
"=",
"new_projection",
",",
"field_filters",
"=",
"self",
".",
"_field_filters",
",",
"orders",
"=",
"self",
".",
"_orders",
",",
"limit",
"=",
"self",
".",
"_limit",
",",
"offset",
"=",
"self",
".",
"_offset",
",",
"start_at",
"=",
"self",
".",
"_start_at",
",",
"end_at",
"=",
"self",
".",
"_end_at",
",",
")"
] | Project documents matching query to a limited set of fields.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
If the current query already has a projection set (i.e. has already
called :meth:`~.firestore_v1beta1.query.Query.select`), this
will overwrite it.
Args:
field_paths (Iterable[str, ...]): An iterable of field paths
(``.``-delimited list of field names) to use as a projection
of document fields in the query results.
Returns:
~.firestore_v1beta1.query.Query: A "projected" query. Acts as
a copy of the current query, modified with the newly added
projection.
Raises:
ValueError: If any ``field_path`` is invalid. | [
"Project",
"documents",
"matching",
"query",
"to",
"a",
"limited",
"set",
"of",
"fields",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L165-L206 |
27,853 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query.where | def where(self, field_path, op_string, value):
"""Filter the query on a field.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
Returns a new :class:`~.firestore_v1beta1.query.Query` that
filters on a specific field path, according to an operation (e.g.
``==`` or "equals") and a particular value to be paired with that
operation.
Args:
field_path (str): A field path (``.``-delimited list of
field names) for the field to filter on.
op_string (str): A comparison operation in the form of a string.
Acceptable values are ``<``, ``<=``, ``==``, ``>=``
and ``>``.
value (Any): The value to compare the field against in the filter.
If ``value`` is :data:`None` or a NaN, then ``==`` is the only
allowed operation.
Returns:
~.firestore_v1beta1.query.Query: A filtered query. Acts as a
copy of the current query, modified with the newly added filter.
Raises:
ValueError: If ``field_path`` is invalid.
ValueError: If ``value`` is a NaN or :data:`None` and
``op_string`` is not ``==``.
"""
field_path_module.split_field_path(field_path) # raises
if value is None:
if op_string != _EQ_OP:
raise ValueError(_BAD_OP_NAN_NULL)
filter_pb = query_pb2.StructuredQuery.UnaryFilter(
field=query_pb2.StructuredQuery.FieldReference(field_path=field_path),
op=enums.StructuredQuery.UnaryFilter.Operator.IS_NULL,
)
elif _isnan(value):
if op_string != _EQ_OP:
raise ValueError(_BAD_OP_NAN_NULL)
filter_pb = query_pb2.StructuredQuery.UnaryFilter(
field=query_pb2.StructuredQuery.FieldReference(field_path=field_path),
op=enums.StructuredQuery.UnaryFilter.Operator.IS_NAN,
)
elif isinstance(value, (transforms.Sentinel, transforms._ValueList)):
raise ValueError(_INVALID_WHERE_TRANSFORM)
else:
filter_pb = query_pb2.StructuredQuery.FieldFilter(
field=query_pb2.StructuredQuery.FieldReference(field_path=field_path),
op=_enum_from_op_string(op_string),
value=_helpers.encode_value(value),
)
new_filters = self._field_filters + (filter_pb,)
return self.__class__(
self._parent,
projection=self._projection,
field_filters=new_filters,
orders=self._orders,
limit=self._limit,
offset=self._offset,
start_at=self._start_at,
end_at=self._end_at,
) | python | def where(self, field_path, op_string, value):
"""Filter the query on a field.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
Returns a new :class:`~.firestore_v1beta1.query.Query` that
filters on a specific field path, according to an operation (e.g.
``==`` or "equals") and a particular value to be paired with that
operation.
Args:
field_path (str): A field path (``.``-delimited list of
field names) for the field to filter on.
op_string (str): A comparison operation in the form of a string.
Acceptable values are ``<``, ``<=``, ``==``, ``>=``
and ``>``.
value (Any): The value to compare the field against in the filter.
If ``value`` is :data:`None` or a NaN, then ``==`` is the only
allowed operation.
Returns:
~.firestore_v1beta1.query.Query: A filtered query. Acts as a
copy of the current query, modified with the newly added filter.
Raises:
ValueError: If ``field_path`` is invalid.
ValueError: If ``value`` is a NaN or :data:`None` and
``op_string`` is not ``==``.
"""
field_path_module.split_field_path(field_path) # raises
if value is None:
if op_string != _EQ_OP:
raise ValueError(_BAD_OP_NAN_NULL)
filter_pb = query_pb2.StructuredQuery.UnaryFilter(
field=query_pb2.StructuredQuery.FieldReference(field_path=field_path),
op=enums.StructuredQuery.UnaryFilter.Operator.IS_NULL,
)
elif _isnan(value):
if op_string != _EQ_OP:
raise ValueError(_BAD_OP_NAN_NULL)
filter_pb = query_pb2.StructuredQuery.UnaryFilter(
field=query_pb2.StructuredQuery.FieldReference(field_path=field_path),
op=enums.StructuredQuery.UnaryFilter.Operator.IS_NAN,
)
elif isinstance(value, (transforms.Sentinel, transforms._ValueList)):
raise ValueError(_INVALID_WHERE_TRANSFORM)
else:
filter_pb = query_pb2.StructuredQuery.FieldFilter(
field=query_pb2.StructuredQuery.FieldReference(field_path=field_path),
op=_enum_from_op_string(op_string),
value=_helpers.encode_value(value),
)
new_filters = self._field_filters + (filter_pb,)
return self.__class__(
self._parent,
projection=self._projection,
field_filters=new_filters,
orders=self._orders,
limit=self._limit,
offset=self._offset,
start_at=self._start_at,
end_at=self._end_at,
) | [
"def",
"where",
"(",
"self",
",",
"field_path",
",",
"op_string",
",",
"value",
")",
":",
"field_path_module",
".",
"split_field_path",
"(",
"field_path",
")",
"# raises",
"if",
"value",
"is",
"None",
":",
"if",
"op_string",
"!=",
"_EQ_OP",
":",
"raise",
"ValueError",
"(",
"_BAD_OP_NAN_NULL",
")",
"filter_pb",
"=",
"query_pb2",
".",
"StructuredQuery",
".",
"UnaryFilter",
"(",
"field",
"=",
"query_pb2",
".",
"StructuredQuery",
".",
"FieldReference",
"(",
"field_path",
"=",
"field_path",
")",
",",
"op",
"=",
"enums",
".",
"StructuredQuery",
".",
"UnaryFilter",
".",
"Operator",
".",
"IS_NULL",
",",
")",
"elif",
"_isnan",
"(",
"value",
")",
":",
"if",
"op_string",
"!=",
"_EQ_OP",
":",
"raise",
"ValueError",
"(",
"_BAD_OP_NAN_NULL",
")",
"filter_pb",
"=",
"query_pb2",
".",
"StructuredQuery",
".",
"UnaryFilter",
"(",
"field",
"=",
"query_pb2",
".",
"StructuredQuery",
".",
"FieldReference",
"(",
"field_path",
"=",
"field_path",
")",
",",
"op",
"=",
"enums",
".",
"StructuredQuery",
".",
"UnaryFilter",
".",
"Operator",
".",
"IS_NAN",
",",
")",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"transforms",
".",
"Sentinel",
",",
"transforms",
".",
"_ValueList",
")",
")",
":",
"raise",
"ValueError",
"(",
"_INVALID_WHERE_TRANSFORM",
")",
"else",
":",
"filter_pb",
"=",
"query_pb2",
".",
"StructuredQuery",
".",
"FieldFilter",
"(",
"field",
"=",
"query_pb2",
".",
"StructuredQuery",
".",
"FieldReference",
"(",
"field_path",
"=",
"field_path",
")",
",",
"op",
"=",
"_enum_from_op_string",
"(",
"op_string",
")",
",",
"value",
"=",
"_helpers",
".",
"encode_value",
"(",
"value",
")",
",",
")",
"new_filters",
"=",
"self",
".",
"_field_filters",
"+",
"(",
"filter_pb",
",",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"_parent",
",",
"projection",
"=",
"self",
".",
"_projection",
",",
"field_filters",
"=",
"new_filters",
",",
"orders",
"=",
"self",
".",
"_orders",
",",
"limit",
"=",
"self",
".",
"_limit",
",",
"offset",
"=",
"self",
".",
"_offset",
",",
"start_at",
"=",
"self",
".",
"_start_at",
",",
"end_at",
"=",
"self",
".",
"_end_at",
",",
")"
] | Filter the query on a field.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
Returns a new :class:`~.firestore_v1beta1.query.Query` that
filters on a specific field path, according to an operation (e.g.
``==`` or "equals") and a particular value to be paired with that
operation.
Args:
field_path (str): A field path (``.``-delimited list of
field names) for the field to filter on.
op_string (str): A comparison operation in the form of a string.
Acceptable values are ``<``, ``<=``, ``==``, ``>=``
and ``>``.
value (Any): The value to compare the field against in the filter.
If ``value`` is :data:`None` or a NaN, then ``==`` is the only
allowed operation.
Returns:
~.firestore_v1beta1.query.Query: A filtered query. Acts as a
copy of the current query, modified with the newly added filter.
Raises:
ValueError: If ``field_path`` is invalid.
ValueError: If ``value`` is a NaN or :data:`None` and
``op_string`` is not ``==``. | [
"Filter",
"the",
"query",
"on",
"a",
"field",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L208-L273 |
27,854 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query.order_by | def order_by(self, field_path, direction=ASCENDING):
"""Modify the query to add an order clause on a specific field.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
Successive :meth:`~.firestore_v1beta1.query.Query.order_by` calls
will further refine the ordering of results returned by the query
(i.e. the new "order by" fields will be added to existing ones).
Args:
field_path (str): A field path (``.``-delimited list of
field names) on which to order the query results.
direction (Optional[str]): The direction to order by. Must be one
of :attr:`ASCENDING` or :attr:`DESCENDING`, defaults to
:attr:`ASCENDING`.
Returns:
~.firestore_v1beta1.query.Query: An ordered query. Acts as a
copy of the current query, modified with the newly added
"order by" constraint.
Raises:
ValueError: If ``field_path`` is invalid.
ValueError: If ``direction`` is not one of :attr:`ASCENDING` or
:attr:`DESCENDING`.
"""
field_path_module.split_field_path(field_path) # raises
order_pb = self._make_order(field_path, direction)
new_orders = self._orders + (order_pb,)
return self.__class__(
self._parent,
projection=self._projection,
field_filters=self._field_filters,
orders=new_orders,
limit=self._limit,
offset=self._offset,
start_at=self._start_at,
end_at=self._end_at,
) | python | def order_by(self, field_path, direction=ASCENDING):
"""Modify the query to add an order clause on a specific field.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
Successive :meth:`~.firestore_v1beta1.query.Query.order_by` calls
will further refine the ordering of results returned by the query
(i.e. the new "order by" fields will be added to existing ones).
Args:
field_path (str): A field path (``.``-delimited list of
field names) on which to order the query results.
direction (Optional[str]): The direction to order by. Must be one
of :attr:`ASCENDING` or :attr:`DESCENDING`, defaults to
:attr:`ASCENDING`.
Returns:
~.firestore_v1beta1.query.Query: An ordered query. Acts as a
copy of the current query, modified with the newly added
"order by" constraint.
Raises:
ValueError: If ``field_path`` is invalid.
ValueError: If ``direction`` is not one of :attr:`ASCENDING` or
:attr:`DESCENDING`.
"""
field_path_module.split_field_path(field_path) # raises
order_pb = self._make_order(field_path, direction)
new_orders = self._orders + (order_pb,)
return self.__class__(
self._parent,
projection=self._projection,
field_filters=self._field_filters,
orders=new_orders,
limit=self._limit,
offset=self._offset,
start_at=self._start_at,
end_at=self._end_at,
) | [
"def",
"order_by",
"(",
"self",
",",
"field_path",
",",
"direction",
"=",
"ASCENDING",
")",
":",
"field_path_module",
".",
"split_field_path",
"(",
"field_path",
")",
"# raises",
"order_pb",
"=",
"self",
".",
"_make_order",
"(",
"field_path",
",",
"direction",
")",
"new_orders",
"=",
"self",
".",
"_orders",
"+",
"(",
"order_pb",
",",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"_parent",
",",
"projection",
"=",
"self",
".",
"_projection",
",",
"field_filters",
"=",
"self",
".",
"_field_filters",
",",
"orders",
"=",
"new_orders",
",",
"limit",
"=",
"self",
".",
"_limit",
",",
"offset",
"=",
"self",
".",
"_offset",
",",
"start_at",
"=",
"self",
".",
"_start_at",
",",
"end_at",
"=",
"self",
".",
"_end_at",
",",
")"
] | Modify the query to add an order clause on a specific field.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
Successive :meth:`~.firestore_v1beta1.query.Query.order_by` calls
will further refine the ordering of results returned by the query
(i.e. the new "order by" fields will be added to existing ones).
Args:
field_path (str): A field path (``.``-delimited list of
field names) on which to order the query results.
direction (Optional[str]): The direction to order by. Must be one
of :attr:`ASCENDING` or :attr:`DESCENDING`, defaults to
:attr:`ASCENDING`.
Returns:
~.firestore_v1beta1.query.Query: An ordered query. Acts as a
copy of the current query, modified with the newly added
"order by" constraint.
Raises:
ValueError: If ``field_path`` is invalid.
ValueError: If ``direction`` is not one of :attr:`ASCENDING` or
:attr:`DESCENDING`. | [
"Modify",
"the",
"query",
"to",
"add",
"an",
"order",
"clause",
"on",
"a",
"specific",
"field",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L283-L324 |
27,855 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query.limit | def limit(self, count):
"""Limit a query to return a fixed number of results.
If the current query already has a limit set, this will overwrite it.
Args:
count (int): Maximum number of documents to return that match
the query.
Returns:
~.firestore_v1beta1.query.Query: A limited query. Acts as a
copy of the current query, modified with the newly added
"limit" filter.
"""
return self.__class__(
self._parent,
projection=self._projection,
field_filters=self._field_filters,
orders=self._orders,
limit=count,
offset=self._offset,
start_at=self._start_at,
end_at=self._end_at,
) | python | def limit(self, count):
"""Limit a query to return a fixed number of results.
If the current query already has a limit set, this will overwrite it.
Args:
count (int): Maximum number of documents to return that match
the query.
Returns:
~.firestore_v1beta1.query.Query: A limited query. Acts as a
copy of the current query, modified with the newly added
"limit" filter.
"""
return self.__class__(
self._parent,
projection=self._projection,
field_filters=self._field_filters,
orders=self._orders,
limit=count,
offset=self._offset,
start_at=self._start_at,
end_at=self._end_at,
) | [
"def",
"limit",
"(",
"self",
",",
"count",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"_parent",
",",
"projection",
"=",
"self",
".",
"_projection",
",",
"field_filters",
"=",
"self",
".",
"_field_filters",
",",
"orders",
"=",
"self",
".",
"_orders",
",",
"limit",
"=",
"count",
",",
"offset",
"=",
"self",
".",
"_offset",
",",
"start_at",
"=",
"self",
".",
"_start_at",
",",
"end_at",
"=",
"self",
".",
"_end_at",
",",
")"
] | Limit a query to return a fixed number of results.
If the current query already has a limit set, this will overwrite it.
Args:
count (int): Maximum number of documents to return that match
the query.
Returns:
~.firestore_v1beta1.query.Query: A limited query. Acts as a
copy of the current query, modified with the newly added
"limit" filter. | [
"Limit",
"a",
"query",
"to",
"return",
"a",
"fixed",
"number",
"of",
"results",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L326-L349 |
27,856 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query.offset | def offset(self, num_to_skip):
"""Skip to an offset in a query.
If the current query already has specified an offset, this will
overwrite it.
Args:
num_to_skip (int): The number of results to skip at the beginning
of query results. (Must be non-negative.)
Returns:
~.firestore_v1beta1.query.Query: An offset query. Acts as a
copy of the current query, modified with the newly added
"offset" field.
"""
return self.__class__(
self._parent,
projection=self._projection,
field_filters=self._field_filters,
orders=self._orders,
limit=self._limit,
offset=num_to_skip,
start_at=self._start_at,
end_at=self._end_at,
) | python | def offset(self, num_to_skip):
"""Skip to an offset in a query.
If the current query already has specified an offset, this will
overwrite it.
Args:
num_to_skip (int): The number of results to skip at the beginning
of query results. (Must be non-negative.)
Returns:
~.firestore_v1beta1.query.Query: An offset query. Acts as a
copy of the current query, modified with the newly added
"offset" field.
"""
return self.__class__(
self._parent,
projection=self._projection,
field_filters=self._field_filters,
orders=self._orders,
limit=self._limit,
offset=num_to_skip,
start_at=self._start_at,
end_at=self._end_at,
) | [
"def",
"offset",
"(",
"self",
",",
"num_to_skip",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"_parent",
",",
"projection",
"=",
"self",
".",
"_projection",
",",
"field_filters",
"=",
"self",
".",
"_field_filters",
",",
"orders",
"=",
"self",
".",
"_orders",
",",
"limit",
"=",
"self",
".",
"_limit",
",",
"offset",
"=",
"num_to_skip",
",",
"start_at",
"=",
"self",
".",
"_start_at",
",",
"end_at",
"=",
"self",
".",
"_end_at",
",",
")"
] | Skip to an offset in a query.
If the current query already has specified an offset, this will
overwrite it.
Args:
num_to_skip (int): The number of results to skip at the beginning
of query results. (Must be non-negative.)
Returns:
~.firestore_v1beta1.query.Query: An offset query. Acts as a
copy of the current query, modified with the newly added
"offset" field. | [
"Skip",
"to",
"an",
"offset",
"in",
"a",
"query",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L351-L375 |
27,857 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query._cursor_helper | def _cursor_helper(self, document_fields, before, start):
"""Set values to be used for a ``start_at`` or ``end_at`` cursor.
The values will later be used in a query protobuf.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
before (bool): Flag indicating if the document in
``document_fields`` should (:data:`False`) or
shouldn't (:data:`True`) be included in the result set.
start (Optional[bool]): determines if the cursor is a ``start_at``
cursor (:data:`True`) or an ``end_at`` cursor (:data:`False`).
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"start at" cursor.
"""
if isinstance(document_fields, tuple):
document_fields = list(document_fields)
elif isinstance(document_fields, document.DocumentSnapshot):
if document_fields.reference._path[:-1] != self._parent._path:
raise ValueError(
"Cannot use snapshot from another collection as a cursor."
)
else:
# NOTE: We copy so that the caller can't modify after calling.
document_fields = copy.deepcopy(document_fields)
cursor_pair = document_fields, before
query_kwargs = {
"projection": self._projection,
"field_filters": self._field_filters,
"orders": self._orders,
"limit": self._limit,
"offset": self._offset,
}
if start:
query_kwargs["start_at"] = cursor_pair
query_kwargs["end_at"] = self._end_at
else:
query_kwargs["start_at"] = self._start_at
query_kwargs["end_at"] = cursor_pair
return self.__class__(self._parent, **query_kwargs) | python | def _cursor_helper(self, document_fields, before, start):
"""Set values to be used for a ``start_at`` or ``end_at`` cursor.
The values will later be used in a query protobuf.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
before (bool): Flag indicating if the document in
``document_fields`` should (:data:`False`) or
shouldn't (:data:`True`) be included in the result set.
start (Optional[bool]): determines if the cursor is a ``start_at``
cursor (:data:`True`) or an ``end_at`` cursor (:data:`False`).
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"start at" cursor.
"""
if isinstance(document_fields, tuple):
document_fields = list(document_fields)
elif isinstance(document_fields, document.DocumentSnapshot):
if document_fields.reference._path[:-1] != self._parent._path:
raise ValueError(
"Cannot use snapshot from another collection as a cursor."
)
else:
# NOTE: We copy so that the caller can't modify after calling.
document_fields = copy.deepcopy(document_fields)
cursor_pair = document_fields, before
query_kwargs = {
"projection": self._projection,
"field_filters": self._field_filters,
"orders": self._orders,
"limit": self._limit,
"offset": self._offset,
}
if start:
query_kwargs["start_at"] = cursor_pair
query_kwargs["end_at"] = self._end_at
else:
query_kwargs["start_at"] = self._start_at
query_kwargs["end_at"] = cursor_pair
return self.__class__(self._parent, **query_kwargs) | [
"def",
"_cursor_helper",
"(",
"self",
",",
"document_fields",
",",
"before",
",",
"start",
")",
":",
"if",
"isinstance",
"(",
"document_fields",
",",
"tuple",
")",
":",
"document_fields",
"=",
"list",
"(",
"document_fields",
")",
"elif",
"isinstance",
"(",
"document_fields",
",",
"document",
".",
"DocumentSnapshot",
")",
":",
"if",
"document_fields",
".",
"reference",
".",
"_path",
"[",
":",
"-",
"1",
"]",
"!=",
"self",
".",
"_parent",
".",
"_path",
":",
"raise",
"ValueError",
"(",
"\"Cannot use snapshot from another collection as a cursor.\"",
")",
"else",
":",
"# NOTE: We copy so that the caller can't modify after calling.",
"document_fields",
"=",
"copy",
".",
"deepcopy",
"(",
"document_fields",
")",
"cursor_pair",
"=",
"document_fields",
",",
"before",
"query_kwargs",
"=",
"{",
"\"projection\"",
":",
"self",
".",
"_projection",
",",
"\"field_filters\"",
":",
"self",
".",
"_field_filters",
",",
"\"orders\"",
":",
"self",
".",
"_orders",
",",
"\"limit\"",
":",
"self",
".",
"_limit",
",",
"\"offset\"",
":",
"self",
".",
"_offset",
",",
"}",
"if",
"start",
":",
"query_kwargs",
"[",
"\"start_at\"",
"]",
"=",
"cursor_pair",
"query_kwargs",
"[",
"\"end_at\"",
"]",
"=",
"self",
".",
"_end_at",
"else",
":",
"query_kwargs",
"[",
"\"start_at\"",
"]",
"=",
"self",
".",
"_start_at",
"query_kwargs",
"[",
"\"end_at\"",
"]",
"=",
"cursor_pair",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"_parent",
",",
"*",
"*",
"query_kwargs",
")"
] | Set values to be used for a ``start_at`` or ``end_at`` cursor.
The values will later be used in a query protobuf.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
before (bool): Flag indicating if the document in
``document_fields`` should (:data:`False`) or
shouldn't (:data:`True`) be included in the result set.
start (Optional[bool]): determines if the cursor is a ``start_at``
cursor (:data:`True`) or an ``end_at`` cursor (:data:`False`).
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"start at" cursor. | [
"Set",
"values",
"to",
"be",
"used",
"for",
"a",
"start_at",
"or",
"end_at",
"cursor",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L377-L429 |
27,858 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query.start_at | def start_at(self, document_fields):
"""Start query results at a particular document value.
The result set will **include** the document specified by
``document_fields``.
If the current query already has specified a start cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.start_after` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"start at" cursor.
"""
return self._cursor_helper(document_fields, before=True, start=True) | python | def start_at(self, document_fields):
"""Start query results at a particular document value.
The result set will **include** the document specified by
``document_fields``.
If the current query already has specified a start cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.start_after` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"start at" cursor.
"""
return self._cursor_helper(document_fields, before=True, start=True) | [
"def",
"start_at",
"(",
"self",
",",
"document_fields",
")",
":",
"return",
"self",
".",
"_cursor_helper",
"(",
"document_fields",
",",
"before",
"=",
"True",
",",
"start",
"=",
"True",
")"
] | Start query results at a particular document value.
The result set will **include** the document specified by
``document_fields``.
If the current query already has specified a start cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.start_after` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"start at" cursor. | [
"Start",
"query",
"results",
"at",
"a",
"particular",
"document",
"value",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L431-L458 |
27,859 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query.start_after | def start_after(self, document_fields):
"""Start query results after a particular document value.
The result set will **exclude** the document specified by
``document_fields``.
If the current query already has specified a start cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.start_at` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"start after" cursor.
"""
return self._cursor_helper(document_fields, before=False, start=True) | python | def start_after(self, document_fields):
"""Start query results after a particular document value.
The result set will **exclude** the document specified by
``document_fields``.
If the current query already has specified a start cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.start_at` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"start after" cursor.
"""
return self._cursor_helper(document_fields, before=False, start=True) | [
"def",
"start_after",
"(",
"self",
",",
"document_fields",
")",
":",
"return",
"self",
".",
"_cursor_helper",
"(",
"document_fields",
",",
"before",
"=",
"False",
",",
"start",
"=",
"True",
")"
] | Start query results after a particular document value.
The result set will **exclude** the document specified by
``document_fields``.
If the current query already has specified a start cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.start_at` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"start after" cursor. | [
"Start",
"query",
"results",
"after",
"a",
"particular",
"document",
"value",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L460-L487 |
27,860 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query.end_before | def end_before(self, document_fields):
"""End query results before a particular document value.
The result set will **exclude** the document specified by
``document_fields``.
If the current query already has specified an end cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.end_at` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"end before" cursor.
"""
return self._cursor_helper(document_fields, before=True, start=False) | python | def end_before(self, document_fields):
"""End query results before a particular document value.
The result set will **exclude** the document specified by
``document_fields``.
If the current query already has specified an end cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.end_at` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"end before" cursor.
"""
return self._cursor_helper(document_fields, before=True, start=False) | [
"def",
"end_before",
"(",
"self",
",",
"document_fields",
")",
":",
"return",
"self",
".",
"_cursor_helper",
"(",
"document_fields",
",",
"before",
"=",
"True",
",",
"start",
"=",
"False",
")"
] | End query results before a particular document value.
The result set will **exclude** the document specified by
``document_fields``.
If the current query already has specified an end cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.end_at` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"end before" cursor. | [
"End",
"query",
"results",
"before",
"a",
"particular",
"document",
"value",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L489-L516 |
27,861 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query.end_at | def end_at(self, document_fields):
"""End query results at a particular document value.
The result set will **include** the document specified by
``document_fields``.
If the current query already has specified an end cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.end_before` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"end at" cursor.
"""
return self._cursor_helper(document_fields, before=False, start=False) | python | def end_at(self, document_fields):
"""End query results at a particular document value.
The result set will **include** the document specified by
``document_fields``.
If the current query already has specified an end cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.end_before` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"end at" cursor.
"""
return self._cursor_helper(document_fields, before=False, start=False) | [
"def",
"end_at",
"(",
"self",
",",
"document_fields",
")",
":",
"return",
"self",
".",
"_cursor_helper",
"(",
"document_fields",
",",
"before",
"=",
"False",
",",
"start",
"=",
"False",
")"
] | End query results at a particular document value.
The result set will **include** the document specified by
``document_fields``.
If the current query already has specified an end cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.end_before` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~.firestore_v1beta1.query.Query.order_by`.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
snapshot or a dictionary/list/tuple of fields representing a
query results cursor. A cursor is a collection of values that
represent a position in a query result set.
Returns:
~.firestore_v1beta1.query.Query: A query with cursor. Acts as
a copy of the current query, modified with the newly added
"end at" cursor. | [
"End",
"query",
"results",
"at",
"a",
"particular",
"document",
"value",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L518-L545 |
27,862 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query._filters_pb | def _filters_pb(self):
"""Convert all the filters into a single generic Filter protobuf.
This may be a lone field filter or unary filter, may be a composite
filter or may be :data:`None`.
Returns:
google.cloud.firestore_v1beta1.types.\
StructuredQuery.Filter: A "generic" filter representing the
current query's filters.
"""
num_filters = len(self._field_filters)
if num_filters == 0:
return None
elif num_filters == 1:
return _filter_pb(self._field_filters[0])
else:
composite_filter = query_pb2.StructuredQuery.CompositeFilter(
op=enums.StructuredQuery.CompositeFilter.Operator.AND,
filters=[_filter_pb(filter_) for filter_ in self._field_filters],
)
return query_pb2.StructuredQuery.Filter(composite_filter=composite_filter) | python | def _filters_pb(self):
"""Convert all the filters into a single generic Filter protobuf.
This may be a lone field filter or unary filter, may be a composite
filter or may be :data:`None`.
Returns:
google.cloud.firestore_v1beta1.types.\
StructuredQuery.Filter: A "generic" filter representing the
current query's filters.
"""
num_filters = len(self._field_filters)
if num_filters == 0:
return None
elif num_filters == 1:
return _filter_pb(self._field_filters[0])
else:
composite_filter = query_pb2.StructuredQuery.CompositeFilter(
op=enums.StructuredQuery.CompositeFilter.Operator.AND,
filters=[_filter_pb(filter_) for filter_ in self._field_filters],
)
return query_pb2.StructuredQuery.Filter(composite_filter=composite_filter) | [
"def",
"_filters_pb",
"(",
"self",
")",
":",
"num_filters",
"=",
"len",
"(",
"self",
".",
"_field_filters",
")",
"if",
"num_filters",
"==",
"0",
":",
"return",
"None",
"elif",
"num_filters",
"==",
"1",
":",
"return",
"_filter_pb",
"(",
"self",
".",
"_field_filters",
"[",
"0",
"]",
")",
"else",
":",
"composite_filter",
"=",
"query_pb2",
".",
"StructuredQuery",
".",
"CompositeFilter",
"(",
"op",
"=",
"enums",
".",
"StructuredQuery",
".",
"CompositeFilter",
".",
"Operator",
".",
"AND",
",",
"filters",
"=",
"[",
"_filter_pb",
"(",
"filter_",
")",
"for",
"filter_",
"in",
"self",
".",
"_field_filters",
"]",
",",
")",
"return",
"query_pb2",
".",
"StructuredQuery",
".",
"Filter",
"(",
"composite_filter",
"=",
"composite_filter",
")"
] | Convert all the filters into a single generic Filter protobuf.
This may be a lone field filter or unary filter, may be a composite
filter or may be :data:`None`.
Returns:
google.cloud.firestore_v1beta1.types.\
StructuredQuery.Filter: A "generic" filter representing the
current query's filters. | [
"Convert",
"all",
"the",
"filters",
"into",
"a",
"single",
"generic",
"Filter",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L547-L568 |
27,863 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query._to_protobuf | def _to_protobuf(self):
"""Convert the current query into the equivalent protobuf.
Returns:
google.cloud.firestore_v1beta1.types.StructuredQuery: The
query protobuf.
"""
projection = self._normalize_projection(self._projection)
orders = self._normalize_orders()
start_at = self._normalize_cursor(self._start_at, orders)
end_at = self._normalize_cursor(self._end_at, orders)
query_kwargs = {
"select": projection,
"from": [
query_pb2.StructuredQuery.CollectionSelector(
collection_id=self._parent.id
)
],
"where": self._filters_pb(),
"order_by": orders,
"start_at": _cursor_pb(start_at),
"end_at": _cursor_pb(end_at),
}
if self._offset is not None:
query_kwargs["offset"] = self._offset
if self._limit is not None:
query_kwargs["limit"] = wrappers_pb2.Int32Value(value=self._limit)
return query_pb2.StructuredQuery(**query_kwargs) | python | def _to_protobuf(self):
"""Convert the current query into the equivalent protobuf.
Returns:
google.cloud.firestore_v1beta1.types.StructuredQuery: The
query protobuf.
"""
projection = self._normalize_projection(self._projection)
orders = self._normalize_orders()
start_at = self._normalize_cursor(self._start_at, orders)
end_at = self._normalize_cursor(self._end_at, orders)
query_kwargs = {
"select": projection,
"from": [
query_pb2.StructuredQuery.CollectionSelector(
collection_id=self._parent.id
)
],
"where": self._filters_pb(),
"order_by": orders,
"start_at": _cursor_pb(start_at),
"end_at": _cursor_pb(end_at),
}
if self._offset is not None:
query_kwargs["offset"] = self._offset
if self._limit is not None:
query_kwargs["limit"] = wrappers_pb2.Int32Value(value=self._limit)
return query_pb2.StructuredQuery(**query_kwargs) | [
"def",
"_to_protobuf",
"(",
"self",
")",
":",
"projection",
"=",
"self",
".",
"_normalize_projection",
"(",
"self",
".",
"_projection",
")",
"orders",
"=",
"self",
".",
"_normalize_orders",
"(",
")",
"start_at",
"=",
"self",
".",
"_normalize_cursor",
"(",
"self",
".",
"_start_at",
",",
"orders",
")",
"end_at",
"=",
"self",
".",
"_normalize_cursor",
"(",
"self",
".",
"_end_at",
",",
"orders",
")",
"query_kwargs",
"=",
"{",
"\"select\"",
":",
"projection",
",",
"\"from\"",
":",
"[",
"query_pb2",
".",
"StructuredQuery",
".",
"CollectionSelector",
"(",
"collection_id",
"=",
"self",
".",
"_parent",
".",
"id",
")",
"]",
",",
"\"where\"",
":",
"self",
".",
"_filters_pb",
"(",
")",
",",
"\"order_by\"",
":",
"orders",
",",
"\"start_at\"",
":",
"_cursor_pb",
"(",
"start_at",
")",
",",
"\"end_at\"",
":",
"_cursor_pb",
"(",
"end_at",
")",
",",
"}",
"if",
"self",
".",
"_offset",
"is",
"not",
"None",
":",
"query_kwargs",
"[",
"\"offset\"",
"]",
"=",
"self",
".",
"_offset",
"if",
"self",
".",
"_limit",
"is",
"not",
"None",
":",
"query_kwargs",
"[",
"\"limit\"",
"]",
"=",
"wrappers_pb2",
".",
"Int32Value",
"(",
"value",
"=",
"self",
".",
"_limit",
")",
"return",
"query_pb2",
".",
"StructuredQuery",
"(",
"*",
"*",
"query_kwargs",
")"
] | Convert the current query into the equivalent protobuf.
Returns:
google.cloud.firestore_v1beta1.types.StructuredQuery: The
query protobuf. | [
"Convert",
"the",
"current",
"query",
"into",
"the",
"equivalent",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L666-L695 |
27,864 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query.stream | def stream(self, transaction=None):
"""Read the documents in the collection that match this query.
This sends a ``RunQuery`` RPC and then returns an iterator which
consumes each document returned in the stream of ``RunQueryResponse``
messages.
.. note::
The underlying stream of responses will time out after
the ``max_rpc_timeout_millis`` value set in the GAPIC
client configuration for the ``RunQuery`` API. Snapshots
not consumed from the iterator before that point will be lost.
If a ``transaction`` is used and it already has write operations
added, this method cannot be used (i.e. read-after-write is not
allowed).
Args:
transaction (Optional[~.firestore_v1beta1.transaction.\
Transaction]): An existing transaction that this query will
run in.
Yields:
~.firestore_v1beta1.document.DocumentSnapshot: The next
document that fulfills the query.
"""
parent_path, expected_prefix = self._parent._parent_info()
response_iterator = self._client._firestore_api.run_query(
parent_path,
self._to_protobuf(),
transaction=_helpers.get_transaction_id(transaction),
metadata=self._client._rpc_metadata,
)
for response in response_iterator:
snapshot = _query_response_to_snapshot(
response, self._parent, expected_prefix
)
if snapshot is not None:
yield snapshot | python | def stream(self, transaction=None):
"""Read the documents in the collection that match this query.
This sends a ``RunQuery`` RPC and then returns an iterator which
consumes each document returned in the stream of ``RunQueryResponse``
messages.
.. note::
The underlying stream of responses will time out after
the ``max_rpc_timeout_millis`` value set in the GAPIC
client configuration for the ``RunQuery`` API. Snapshots
not consumed from the iterator before that point will be lost.
If a ``transaction`` is used and it already has write operations
added, this method cannot be used (i.e. read-after-write is not
allowed).
Args:
transaction (Optional[~.firestore_v1beta1.transaction.\
Transaction]): An existing transaction that this query will
run in.
Yields:
~.firestore_v1beta1.document.DocumentSnapshot: The next
document that fulfills the query.
"""
parent_path, expected_prefix = self._parent._parent_info()
response_iterator = self._client._firestore_api.run_query(
parent_path,
self._to_protobuf(),
transaction=_helpers.get_transaction_id(transaction),
metadata=self._client._rpc_metadata,
)
for response in response_iterator:
snapshot = _query_response_to_snapshot(
response, self._parent, expected_prefix
)
if snapshot is not None:
yield snapshot | [
"def",
"stream",
"(",
"self",
",",
"transaction",
"=",
"None",
")",
":",
"parent_path",
",",
"expected_prefix",
"=",
"self",
".",
"_parent",
".",
"_parent_info",
"(",
")",
"response_iterator",
"=",
"self",
".",
"_client",
".",
"_firestore_api",
".",
"run_query",
"(",
"parent_path",
",",
"self",
".",
"_to_protobuf",
"(",
")",
",",
"transaction",
"=",
"_helpers",
".",
"get_transaction_id",
"(",
"transaction",
")",
",",
"metadata",
"=",
"self",
".",
"_client",
".",
"_rpc_metadata",
",",
")",
"for",
"response",
"in",
"response_iterator",
":",
"snapshot",
"=",
"_query_response_to_snapshot",
"(",
"response",
",",
"self",
".",
"_parent",
",",
"expected_prefix",
")",
"if",
"snapshot",
"is",
"not",
"None",
":",
"yield",
"snapshot"
] | Read the documents in the collection that match this query.
This sends a ``RunQuery`` RPC and then returns an iterator which
consumes each document returned in the stream of ``RunQueryResponse``
messages.
.. note::
The underlying stream of responses will time out after
the ``max_rpc_timeout_millis`` value set in the GAPIC
client configuration for the ``RunQuery`` API. Snapshots
not consumed from the iterator before that point will be lost.
If a ``transaction`` is used and it already has write operations
added, this method cannot be used (i.e. read-after-write is not
allowed).
Args:
transaction (Optional[~.firestore_v1beta1.transaction.\
Transaction]): An existing transaction that this query will
run in.
Yields:
~.firestore_v1beta1.document.DocumentSnapshot: The next
document that fulfills the query. | [
"Read",
"the",
"documents",
"in",
"the",
"collection",
"that",
"match",
"this",
"query",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L706-L746 |
27,865 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | Query.on_snapshot | def on_snapshot(self, callback):
"""Monitor the documents in this collection that match this query.
This starts a watch on this query using a background thread. The
provided callback is run on the snapshot of the documents.
Args:
callback(~.firestore.query.QuerySnapshot): a callback to run when
a change occurs.
Example:
from google.cloud import firestore_v1beta1
db = firestore_v1beta1.Client()
query_ref = db.collection(u'users').where("user", "==", u'Ada')
def on_snapshot(docs, changes, read_time):
for doc in docs:
print(u'{} => {}'.format(doc.id, doc.to_dict()))
# Watch this query
query_watch = query_ref.on_snapshot(on_snapshot)
# Terminate this watch
query_watch.unsubscribe()
"""
return Watch.for_query(
self, callback, document.DocumentSnapshot, document.DocumentReference
) | python | def on_snapshot(self, callback):
"""Monitor the documents in this collection that match this query.
This starts a watch on this query using a background thread. The
provided callback is run on the snapshot of the documents.
Args:
callback(~.firestore.query.QuerySnapshot): a callback to run when
a change occurs.
Example:
from google.cloud import firestore_v1beta1
db = firestore_v1beta1.Client()
query_ref = db.collection(u'users').where("user", "==", u'Ada')
def on_snapshot(docs, changes, read_time):
for doc in docs:
print(u'{} => {}'.format(doc.id, doc.to_dict()))
# Watch this query
query_watch = query_ref.on_snapshot(on_snapshot)
# Terminate this watch
query_watch.unsubscribe()
"""
return Watch.for_query(
self, callback, document.DocumentSnapshot, document.DocumentReference
) | [
"def",
"on_snapshot",
"(",
"self",
",",
"callback",
")",
":",
"return",
"Watch",
".",
"for_query",
"(",
"self",
",",
"callback",
",",
"document",
".",
"DocumentSnapshot",
",",
"document",
".",
"DocumentReference",
")"
] | Monitor the documents in this collection that match this query.
This starts a watch on this query using a background thread. The
provided callback is run on the snapshot of the documents.
Args:
callback(~.firestore.query.QuerySnapshot): a callback to run when
a change occurs.
Example:
from google.cloud import firestore_v1beta1
db = firestore_v1beta1.Client()
query_ref = db.collection(u'users').where("user", "==", u'Ada')
def on_snapshot(docs, changes, read_time):
for doc in docs:
print(u'{} => {}'.format(doc.id, doc.to_dict()))
# Watch this query
query_watch = query_ref.on_snapshot(on_snapshot)
# Terminate this watch
query_watch.unsubscribe() | [
"Monitor",
"the",
"documents",
"in",
"this",
"collection",
"that",
"match",
"this",
"query",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L748-L776 |
27,866 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/dataset.py | _get_model_reference | def _get_model_reference(self, model_id):
"""Constructs a ModelReference.
Args:
model_id (str): the ID of the model.
Returns:
google.cloud.bigquery.model.ModelReference:
A ModelReference for a model in this dataset.
"""
return ModelReference.from_api_repr(
{"projectId": self.project, "datasetId": self.dataset_id, "modelId": model_id}
) | python | def _get_model_reference(self, model_id):
"""Constructs a ModelReference.
Args:
model_id (str): the ID of the model.
Returns:
google.cloud.bigquery.model.ModelReference:
A ModelReference for a model in this dataset.
"""
return ModelReference.from_api_repr(
{"projectId": self.project, "datasetId": self.dataset_id, "modelId": model_id}
) | [
"def",
"_get_model_reference",
"(",
"self",
",",
"model_id",
")",
":",
"return",
"ModelReference",
".",
"from_api_repr",
"(",
"{",
"\"projectId\"",
":",
"self",
".",
"project",
",",
"\"datasetId\"",
":",
"self",
".",
"dataset_id",
",",
"\"modelId\"",
":",
"model_id",
"}",
")"
] | Constructs a ModelReference.
Args:
model_id (str): the ID of the model.
Returns:
google.cloud.bigquery.model.ModelReference:
A ModelReference for a model in this dataset. | [
"Constructs",
"a",
"ModelReference",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/dataset.py#L41-L53 |
27,867 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/dataset.py | AccessEntry.to_api_repr | def to_api_repr(self):
"""Construct the API resource representation of this access entry
Returns:
Dict[str, object]: Access entry represented as an API resource
"""
resource = {self.entity_type: self.entity_id}
if self.role is not None:
resource["role"] = self.role
return resource | python | def to_api_repr(self):
"""Construct the API resource representation of this access entry
Returns:
Dict[str, object]: Access entry represented as an API resource
"""
resource = {self.entity_type: self.entity_id}
if self.role is not None:
resource["role"] = self.role
return resource | [
"def",
"to_api_repr",
"(",
"self",
")",
":",
"resource",
"=",
"{",
"self",
".",
"entity_type",
":",
"self",
".",
"entity_id",
"}",
"if",
"self",
".",
"role",
"is",
"not",
"None",
":",
"resource",
"[",
"\"role\"",
"]",
"=",
"self",
".",
"role",
"return",
"resource"
] | Construct the API resource representation of this access entry
Returns:
Dict[str, object]: Access entry represented as an API resource | [
"Construct",
"the",
"API",
"resource",
"representation",
"of",
"this",
"access",
"entry"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/dataset.py#L150-L159 |
27,868 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/dataset.py | DatasetReference.from_string | def from_string(cls, dataset_id, default_project=None):
"""Construct a dataset reference from dataset ID string.
Args:
dataset_id (str):
A dataset ID in standard SQL format. If ``default_project``
is not specified, this must included both the project ID and
the dataset ID, separated by ``.``.
default_project (str):
Optional. The project ID to use when ``dataset_id`` does not
include a project ID.
Returns:
DatasetReference:
Dataset reference parsed from ``dataset_id``.
Examples:
>>> DatasetReference.from_string('my-project-id.some_dataset')
DatasetReference('my-project-id', 'some_dataset')
Raises:
ValueError:
If ``dataset_id`` is not a fully-qualified dataset ID in
standard SQL format.
"""
output_dataset_id = dataset_id
output_project_id = default_project
parts = dataset_id.split(".")
if len(parts) == 1 and not default_project:
raise ValueError(
"When default_project is not set, dataset_id must be a "
"fully-qualified dataset ID in standard SQL format. "
'e.g. "project.dataset_id", got {}'.format(dataset_id)
)
elif len(parts) == 2:
output_project_id, output_dataset_id = parts
elif len(parts) > 2:
raise ValueError(
"Too many parts in dataset_id. Expected a fully-qualified "
"dataset ID in standard SQL format. e.g. "
'"project.dataset_id", got {}'.format(dataset_id)
)
return cls(output_project_id, output_dataset_id) | python | def from_string(cls, dataset_id, default_project=None):
"""Construct a dataset reference from dataset ID string.
Args:
dataset_id (str):
A dataset ID in standard SQL format. If ``default_project``
is not specified, this must included both the project ID and
the dataset ID, separated by ``.``.
default_project (str):
Optional. The project ID to use when ``dataset_id`` does not
include a project ID.
Returns:
DatasetReference:
Dataset reference parsed from ``dataset_id``.
Examples:
>>> DatasetReference.from_string('my-project-id.some_dataset')
DatasetReference('my-project-id', 'some_dataset')
Raises:
ValueError:
If ``dataset_id`` is not a fully-qualified dataset ID in
standard SQL format.
"""
output_dataset_id = dataset_id
output_project_id = default_project
parts = dataset_id.split(".")
if len(parts) == 1 and not default_project:
raise ValueError(
"When default_project is not set, dataset_id must be a "
"fully-qualified dataset ID in standard SQL format. "
'e.g. "project.dataset_id", got {}'.format(dataset_id)
)
elif len(parts) == 2:
output_project_id, output_dataset_id = parts
elif len(parts) > 2:
raise ValueError(
"Too many parts in dataset_id. Expected a fully-qualified "
"dataset ID in standard SQL format. e.g. "
'"project.dataset_id", got {}'.format(dataset_id)
)
return cls(output_project_id, output_dataset_id) | [
"def",
"from_string",
"(",
"cls",
",",
"dataset_id",
",",
"default_project",
"=",
"None",
")",
":",
"output_dataset_id",
"=",
"dataset_id",
"output_project_id",
"=",
"default_project",
"parts",
"=",
"dataset_id",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
"and",
"not",
"default_project",
":",
"raise",
"ValueError",
"(",
"\"When default_project is not set, dataset_id must be a \"",
"\"fully-qualified dataset ID in standard SQL format. \"",
"'e.g. \"project.dataset_id\", got {}'",
".",
"format",
"(",
"dataset_id",
")",
")",
"elif",
"len",
"(",
"parts",
")",
"==",
"2",
":",
"output_project_id",
",",
"output_dataset_id",
"=",
"parts",
"elif",
"len",
"(",
"parts",
")",
">",
"2",
":",
"raise",
"ValueError",
"(",
"\"Too many parts in dataset_id. Expected a fully-qualified \"",
"\"dataset ID in standard SQL format. e.g. \"",
"'\"project.dataset_id\", got {}'",
".",
"format",
"(",
"dataset_id",
")",
")",
"return",
"cls",
"(",
"output_project_id",
",",
"output_dataset_id",
")"
] | Construct a dataset reference from dataset ID string.
Args:
dataset_id (str):
A dataset ID in standard SQL format. If ``default_project``
is not specified, this must included both the project ID and
the dataset ID, separated by ``.``.
default_project (str):
Optional. The project ID to use when ``dataset_id`` does not
include a project ID.
Returns:
DatasetReference:
Dataset reference parsed from ``dataset_id``.
Examples:
>>> DatasetReference.from_string('my-project-id.some_dataset')
DatasetReference('my-project-id', 'some_dataset')
Raises:
ValueError:
If ``dataset_id`` is not a fully-qualified dataset ID in
standard SQL format. | [
"Construct",
"a",
"dataset",
"reference",
"from",
"dataset",
"ID",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/dataset.py#L244-L288 |
27,869 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | _item_to_blob | def _item_to_blob(iterator, item):
"""Convert a JSON blob to the native object.
.. note::
This assumes that the ``bucket`` attribute has been
added to the iterator after being created.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that has retrieved the item.
:type item: dict
:param item: An item to be converted to a blob.
:rtype: :class:`.Blob`
:returns: The next blob in the page.
"""
name = item.get("name")
blob = Blob(name, bucket=iterator.bucket)
blob._set_properties(item)
return blob | python | def _item_to_blob(iterator, item):
"""Convert a JSON blob to the native object.
.. note::
This assumes that the ``bucket`` attribute has been
added to the iterator after being created.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that has retrieved the item.
:type item: dict
:param item: An item to be converted to a blob.
:rtype: :class:`.Blob`
:returns: The next blob in the page.
"""
name = item.get("name")
blob = Blob(name, bucket=iterator.bucket)
blob._set_properties(item)
return blob | [
"def",
"_item_to_blob",
"(",
"iterator",
",",
"item",
")",
":",
"name",
"=",
"item",
".",
"get",
"(",
"\"name\"",
")",
"blob",
"=",
"Blob",
"(",
"name",
",",
"bucket",
"=",
"iterator",
".",
"bucket",
")",
"blob",
".",
"_set_properties",
"(",
"item",
")",
"return",
"blob"
] | Convert a JSON blob to the native object.
.. note::
This assumes that the ``bucket`` attribute has been
added to the iterator after being created.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that has retrieved the item.
:type item: dict
:param item: An item to be converted to a blob.
:rtype: :class:`.Blob`
:returns: The next blob in the page. | [
"Convert",
"a",
"JSON",
"blob",
"to",
"the",
"native",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L69-L89 |
27,870 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket._set_properties | def _set_properties(self, value):
"""Set the properties for the current object.
:type value: dict or :class:`google.cloud.storage.batch._FutureDict`
:param value: The properties to be set.
"""
self._label_removals.clear()
return super(Bucket, self)._set_properties(value) | python | def _set_properties(self, value):
"""Set the properties for the current object.
:type value: dict or :class:`google.cloud.storage.batch._FutureDict`
:param value: The properties to be set.
"""
self._label_removals.clear()
return super(Bucket, self)._set_properties(value) | [
"def",
"_set_properties",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_label_removals",
".",
"clear",
"(",
")",
"return",
"super",
"(",
"Bucket",
",",
"self",
")",
".",
"_set_properties",
"(",
"value",
")"
] | Set the properties for the current object.
:type value: dict or :class:`google.cloud.storage.batch._FutureDict`
:param value: The properties to be set. | [
"Set",
"the",
"properties",
"for",
"the",
"current",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L421-L428 |
27,871 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.blob | def blob(
self,
blob_name,
chunk_size=None,
encryption_key=None,
kms_key_name=None,
generation=None,
):
"""Factory constructor for blob object.
.. note::
This will not make an HTTP request; it simply instantiates
a blob object owned by this bucket.
:type blob_name: str
:param blob_name: The name of the blob to be instantiated.
:type chunk_size: int
:param chunk_size: The size of a chunk of data whenever iterating
(in bytes). This must be a multiple of 256 KB per
the API specification.
:type encryption_key: bytes
:param encryption_key:
Optional 32 byte encryption key for customer-supplied encryption.
:type kms_key_name: str
:param kms_key_name:
Optional resource name of KMS key used to encrypt blob's content.
:type generation: long
:param generation: Optional. If present, selects a specific revision of
this object.
:rtype: :class:`google.cloud.storage.blob.Blob`
:returns: The blob object created.
"""
return Blob(
name=blob_name,
bucket=self,
chunk_size=chunk_size,
encryption_key=encryption_key,
kms_key_name=kms_key_name,
generation=generation,
) | python | def blob(
self,
blob_name,
chunk_size=None,
encryption_key=None,
kms_key_name=None,
generation=None,
):
"""Factory constructor for blob object.
.. note::
This will not make an HTTP request; it simply instantiates
a blob object owned by this bucket.
:type blob_name: str
:param blob_name: The name of the blob to be instantiated.
:type chunk_size: int
:param chunk_size: The size of a chunk of data whenever iterating
(in bytes). This must be a multiple of 256 KB per
the API specification.
:type encryption_key: bytes
:param encryption_key:
Optional 32 byte encryption key for customer-supplied encryption.
:type kms_key_name: str
:param kms_key_name:
Optional resource name of KMS key used to encrypt blob's content.
:type generation: long
:param generation: Optional. If present, selects a specific revision of
this object.
:rtype: :class:`google.cloud.storage.blob.Blob`
:returns: The blob object created.
"""
return Blob(
name=blob_name,
bucket=self,
chunk_size=chunk_size,
encryption_key=encryption_key,
kms_key_name=kms_key_name,
generation=generation,
) | [
"def",
"blob",
"(",
"self",
",",
"blob_name",
",",
"chunk_size",
"=",
"None",
",",
"encryption_key",
"=",
"None",
",",
"kms_key_name",
"=",
"None",
",",
"generation",
"=",
"None",
",",
")",
":",
"return",
"Blob",
"(",
"name",
"=",
"blob_name",
",",
"bucket",
"=",
"self",
",",
"chunk_size",
"=",
"chunk_size",
",",
"encryption_key",
"=",
"encryption_key",
",",
"kms_key_name",
"=",
"kms_key_name",
",",
"generation",
"=",
"generation",
",",
")"
] | Factory constructor for blob object.
.. note::
This will not make an HTTP request; it simply instantiates
a blob object owned by this bucket.
:type blob_name: str
:param blob_name: The name of the blob to be instantiated.
:type chunk_size: int
:param chunk_size: The size of a chunk of data whenever iterating
(in bytes). This must be a multiple of 256 KB per
the API specification.
:type encryption_key: bytes
:param encryption_key:
Optional 32 byte encryption key for customer-supplied encryption.
:type kms_key_name: str
:param kms_key_name:
Optional resource name of KMS key used to encrypt blob's content.
:type generation: long
:param generation: Optional. If present, selects a specific revision of
this object.
:rtype: :class:`google.cloud.storage.blob.Blob`
:returns: The blob object created. | [
"Factory",
"constructor",
"for",
"blob",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L440-L484 |
27,872 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.create | def create(self, client=None, project=None, location=None):
"""Creates current bucket.
If the bucket already exists, will raise
:class:`google.cloud.exceptions.Conflict`.
This implements "storage.buckets.insert".
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type project: str
:param project: Optional. The project under which the bucket is to
be created. If not passed, uses the project set on
the client.
:raises ValueError: if :attr:`user_project` is set.
:raises ValueError: if ``project`` is None and client's
:attr:`project` is also None.
:type location: str
:param location: Optional. The location of the bucket. If not passed,
the default location, US, will be used. See
https://cloud.google.com/storage/docs/bucket-locations
"""
if self.user_project is not None:
raise ValueError("Cannot create bucket with 'user_project' set.")
client = self._require_client(client)
if project is None:
project = client.project
if project is None:
raise ValueError("Client project not set: pass an explicit project.")
query_params = {"project": project}
properties = {key: self._properties[key] for key in self._changes}
properties["name"] = self.name
if location is not None:
properties["location"] = location
api_response = client._connection.api_request(
method="POST",
path="/b",
query_params=query_params,
data=properties,
_target_object=self,
)
self._set_properties(api_response) | python | def create(self, client=None, project=None, location=None):
"""Creates current bucket.
If the bucket already exists, will raise
:class:`google.cloud.exceptions.Conflict`.
This implements "storage.buckets.insert".
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type project: str
:param project: Optional. The project under which the bucket is to
be created. If not passed, uses the project set on
the client.
:raises ValueError: if :attr:`user_project` is set.
:raises ValueError: if ``project`` is None and client's
:attr:`project` is also None.
:type location: str
:param location: Optional. The location of the bucket. If not passed,
the default location, US, will be used. See
https://cloud.google.com/storage/docs/bucket-locations
"""
if self.user_project is not None:
raise ValueError("Cannot create bucket with 'user_project' set.")
client = self._require_client(client)
if project is None:
project = client.project
if project is None:
raise ValueError("Client project not set: pass an explicit project.")
query_params = {"project": project}
properties = {key: self._properties[key] for key in self._changes}
properties["name"] = self.name
if location is not None:
properties["location"] = location
api_response = client._connection.api_request(
method="POST",
path="/b",
query_params=query_params,
data=properties,
_target_object=self,
)
self._set_properties(api_response) | [
"def",
"create",
"(",
"self",
",",
"client",
"=",
"None",
",",
"project",
"=",
"None",
",",
"location",
"=",
"None",
")",
":",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot create bucket with 'user_project' set.\"",
")",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"client",
".",
"project",
"if",
"project",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Client project not set: pass an explicit project.\"",
")",
"query_params",
"=",
"{",
"\"project\"",
":",
"project",
"}",
"properties",
"=",
"{",
"key",
":",
"self",
".",
"_properties",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
".",
"_changes",
"}",
"properties",
"[",
"\"name\"",
"]",
"=",
"self",
".",
"name",
"if",
"location",
"is",
"not",
"None",
":",
"properties",
"[",
"\"location\"",
"]",
"=",
"location",
"api_response",
"=",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"\"/b\"",
",",
"query_params",
"=",
"query_params",
",",
"data",
"=",
"properties",
",",
"_target_object",
"=",
"self",
",",
")",
"self",
".",
"_set_properties",
"(",
"api_response",
")"
] | Creates current bucket.
If the bucket already exists, will raise
:class:`google.cloud.exceptions.Conflict`.
This implements "storage.buckets.insert".
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type project: str
:param project: Optional. The project under which the bucket is to
be created. If not passed, uses the project set on
the client.
:raises ValueError: if :attr:`user_project` is set.
:raises ValueError: if ``project`` is None and client's
:attr:`project` is also None.
:type location: str
:param location: Optional. The location of the bucket. If not passed,
the default location, US, will be used. See
https://cloud.google.com/storage/docs/bucket-locations | [
"Creates",
"current",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L548-L601 |
27,873 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.get_blob | def get_blob(
self, blob_name, client=None, encryption_key=None, generation=None, **kwargs
):
"""Get a blob object by name.
This will return None if the blob doesn't exist:
.. literalinclude:: snippets.py
:start-after: [START get_blob]
:end-before: [END get_blob]
If :attr:`user_project` is set, bills the API request to that project.
:type blob_name: str
:param blob_name: The name of the blob to retrieve.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type encryption_key: bytes
:param encryption_key:
Optional 32 byte encryption key for customer-supplied encryption.
See
https://cloud.google.com/storage/docs/encryption#customer-supplied.
:type generation: long
:param generation: Optional. If present, selects a specific revision of
this object.
:type kwargs: dict
:param kwargs: Keyword arguments to pass to the
:class:`~google.cloud.storage.blob.Blob` constructor.
:rtype: :class:`google.cloud.storage.blob.Blob` or None
:returns: The blob object if it exists, otherwise None.
"""
blob = Blob(
bucket=self,
name=blob_name,
encryption_key=encryption_key,
generation=generation,
**kwargs
)
try:
# NOTE: This will not fail immediately in a batch. However, when
# Batch.finish() is called, the resulting `NotFound` will be
# raised.
blob.reload(client=client)
except NotFound:
return None
else:
return blob | python | def get_blob(
self, blob_name, client=None, encryption_key=None, generation=None, **kwargs
):
"""Get a blob object by name.
This will return None if the blob doesn't exist:
.. literalinclude:: snippets.py
:start-after: [START get_blob]
:end-before: [END get_blob]
If :attr:`user_project` is set, bills the API request to that project.
:type blob_name: str
:param blob_name: The name of the blob to retrieve.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type encryption_key: bytes
:param encryption_key:
Optional 32 byte encryption key for customer-supplied encryption.
See
https://cloud.google.com/storage/docs/encryption#customer-supplied.
:type generation: long
:param generation: Optional. If present, selects a specific revision of
this object.
:type kwargs: dict
:param kwargs: Keyword arguments to pass to the
:class:`~google.cloud.storage.blob.Blob` constructor.
:rtype: :class:`google.cloud.storage.blob.Blob` or None
:returns: The blob object if it exists, otherwise None.
"""
blob = Blob(
bucket=self,
name=blob_name,
encryption_key=encryption_key,
generation=generation,
**kwargs
)
try:
# NOTE: This will not fail immediately in a batch. However, when
# Batch.finish() is called, the resulting `NotFound` will be
# raised.
blob.reload(client=client)
except NotFound:
return None
else:
return blob | [
"def",
"get_blob",
"(",
"self",
",",
"blob_name",
",",
"client",
"=",
"None",
",",
"encryption_key",
"=",
"None",
",",
"generation",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"blob",
"=",
"Blob",
"(",
"bucket",
"=",
"self",
",",
"name",
"=",
"blob_name",
",",
"encryption_key",
"=",
"encryption_key",
",",
"generation",
"=",
"generation",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"# NOTE: This will not fail immediately in a batch. However, when",
"# Batch.finish() is called, the resulting `NotFound` will be",
"# raised.",
"blob",
".",
"reload",
"(",
"client",
"=",
"client",
")",
"except",
"NotFound",
":",
"return",
"None",
"else",
":",
"return",
"blob"
] | Get a blob object by name.
This will return None if the blob doesn't exist:
.. literalinclude:: snippets.py
:start-after: [START get_blob]
:end-before: [END get_blob]
If :attr:`user_project` is set, bills the API request to that project.
:type blob_name: str
:param blob_name: The name of the blob to retrieve.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type encryption_key: bytes
:param encryption_key:
Optional 32 byte encryption key for customer-supplied encryption.
See
https://cloud.google.com/storage/docs/encryption#customer-supplied.
:type generation: long
:param generation: Optional. If present, selects a specific revision of
this object.
:type kwargs: dict
:param kwargs: Keyword arguments to pass to the
:class:`~google.cloud.storage.blob.Blob` constructor.
:rtype: :class:`google.cloud.storage.blob.Blob` or None
:returns: The blob object if it exists, otherwise None. | [
"Get",
"a",
"blob",
"object",
"by",
"name",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L656-L709 |
27,874 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.list_blobs | def list_blobs(
self,
max_results=None,
page_token=None,
prefix=None,
delimiter=None,
versions=None,
projection="noAcl",
fields=None,
client=None,
):
"""Return an iterator used to find blobs in the bucket.
If :attr:`user_project` is set, bills the API request to that project.
:type max_results: int
:param max_results:
(Optional) The maximum number of blobs in each page of results
from this request. Non-positive values are ignored. Defaults to
a sensible value set by the API.
:type page_token: str
:param page_token:
(Optional) If present, return the next batch of blobs, using the
value, which must correspond to the ``nextPageToken`` value
returned in the previous response. Deprecated: use the ``pages``
property of the returned iterator instead of manually passing the
token.
:type prefix: str
:param prefix: (Optional) prefix used to filter blobs.
:type delimiter: str
:param delimiter: (Optional) Delimiter, used with ``prefix`` to
emulate hierarchy.
:type versions: bool
:param versions: (Optional) Whether object versions should be returned
as separate blobs.
:type projection: str
:param projection: (Optional) If used, must be 'full' or 'noAcl'.
Defaults to ``'noAcl'``. Specifies the set of
properties to return.
:type fields: str
:param fields: (Optional) Selector specifying which fields to include
in a partial response. Must be a list of fields. For
example to get a partial response with just the next
page token and the language of each blob returned:
``'items/contentLanguage,nextPageToken'``.
:type client: :class:`~google.cloud.storage.client.Client`
:param client: (Optional) The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of all :class:`~google.cloud.storage.blob.Blob`
in this bucket matching the arguments.
"""
extra_params = {"projection": projection}
if prefix is not None:
extra_params["prefix"] = prefix
if delimiter is not None:
extra_params["delimiter"] = delimiter
if versions is not None:
extra_params["versions"] = versions
if fields is not None:
extra_params["fields"] = fields
if self.user_project is not None:
extra_params["userProject"] = self.user_project
client = self._require_client(client)
path = self.path + "/o"
iterator = page_iterator.HTTPIterator(
client=client,
api_request=client._connection.api_request,
path=path,
item_to_value=_item_to_blob,
page_token=page_token,
max_results=max_results,
extra_params=extra_params,
page_start=_blobs_page_start,
)
iterator.bucket = self
iterator.prefixes = set()
return iterator | python | def list_blobs(
self,
max_results=None,
page_token=None,
prefix=None,
delimiter=None,
versions=None,
projection="noAcl",
fields=None,
client=None,
):
"""Return an iterator used to find blobs in the bucket.
If :attr:`user_project` is set, bills the API request to that project.
:type max_results: int
:param max_results:
(Optional) The maximum number of blobs in each page of results
from this request. Non-positive values are ignored. Defaults to
a sensible value set by the API.
:type page_token: str
:param page_token:
(Optional) If present, return the next batch of blobs, using the
value, which must correspond to the ``nextPageToken`` value
returned in the previous response. Deprecated: use the ``pages``
property of the returned iterator instead of manually passing the
token.
:type prefix: str
:param prefix: (Optional) prefix used to filter blobs.
:type delimiter: str
:param delimiter: (Optional) Delimiter, used with ``prefix`` to
emulate hierarchy.
:type versions: bool
:param versions: (Optional) Whether object versions should be returned
as separate blobs.
:type projection: str
:param projection: (Optional) If used, must be 'full' or 'noAcl'.
Defaults to ``'noAcl'``. Specifies the set of
properties to return.
:type fields: str
:param fields: (Optional) Selector specifying which fields to include
in a partial response. Must be a list of fields. For
example to get a partial response with just the next
page token and the language of each blob returned:
``'items/contentLanguage,nextPageToken'``.
:type client: :class:`~google.cloud.storage.client.Client`
:param client: (Optional) The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of all :class:`~google.cloud.storage.blob.Blob`
in this bucket matching the arguments.
"""
extra_params = {"projection": projection}
if prefix is not None:
extra_params["prefix"] = prefix
if delimiter is not None:
extra_params["delimiter"] = delimiter
if versions is not None:
extra_params["versions"] = versions
if fields is not None:
extra_params["fields"] = fields
if self.user_project is not None:
extra_params["userProject"] = self.user_project
client = self._require_client(client)
path = self.path + "/o"
iterator = page_iterator.HTTPIterator(
client=client,
api_request=client._connection.api_request,
path=path,
item_to_value=_item_to_blob,
page_token=page_token,
max_results=max_results,
extra_params=extra_params,
page_start=_blobs_page_start,
)
iterator.bucket = self
iterator.prefixes = set()
return iterator | [
"def",
"list_blobs",
"(",
"self",
",",
"max_results",
"=",
"None",
",",
"page_token",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"delimiter",
"=",
"None",
",",
"versions",
"=",
"None",
",",
"projection",
"=",
"\"noAcl\"",
",",
"fields",
"=",
"None",
",",
"client",
"=",
"None",
",",
")",
":",
"extra_params",
"=",
"{",
"\"projection\"",
":",
"projection",
"}",
"if",
"prefix",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"prefix\"",
"]",
"=",
"prefix",
"if",
"delimiter",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"delimiter\"",
"]",
"=",
"delimiter",
"if",
"versions",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"versions\"",
"]",
"=",
"versions",
"if",
"fields",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"fields\"",
"]",
"=",
"fields",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"userProject\"",
"]",
"=",
"self",
".",
"user_project",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"path",
"=",
"self",
".",
"path",
"+",
"\"/o\"",
"iterator",
"=",
"page_iterator",
".",
"HTTPIterator",
"(",
"client",
"=",
"client",
",",
"api_request",
"=",
"client",
".",
"_connection",
".",
"api_request",
",",
"path",
"=",
"path",
",",
"item_to_value",
"=",
"_item_to_blob",
",",
"page_token",
"=",
"page_token",
",",
"max_results",
"=",
"max_results",
",",
"extra_params",
"=",
"extra_params",
",",
"page_start",
"=",
"_blobs_page_start",
",",
")",
"iterator",
".",
"bucket",
"=",
"self",
"iterator",
".",
"prefixes",
"=",
"set",
"(",
")",
"return",
"iterator"
] | Return an iterator used to find blobs in the bucket.
If :attr:`user_project` is set, bills the API request to that project.
:type max_results: int
:param max_results:
(Optional) The maximum number of blobs in each page of results
from this request. Non-positive values are ignored. Defaults to
a sensible value set by the API.
:type page_token: str
:param page_token:
(Optional) If present, return the next batch of blobs, using the
value, which must correspond to the ``nextPageToken`` value
returned in the previous response. Deprecated: use the ``pages``
property of the returned iterator instead of manually passing the
token.
:type prefix: str
:param prefix: (Optional) prefix used to filter blobs.
:type delimiter: str
:param delimiter: (Optional) Delimiter, used with ``prefix`` to
emulate hierarchy.
:type versions: bool
:param versions: (Optional) Whether object versions should be returned
as separate blobs.
:type projection: str
:param projection: (Optional) If used, must be 'full' or 'noAcl'.
Defaults to ``'noAcl'``. Specifies the set of
properties to return.
:type fields: str
:param fields: (Optional) Selector specifying which fields to include
in a partial response. Must be a list of fields. For
example to get a partial response with just the next
page token and the language of each blob returned:
``'items/contentLanguage,nextPageToken'``.
:type client: :class:`~google.cloud.storage.client.Client`
:param client: (Optional) The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of all :class:`~google.cloud.storage.blob.Blob`
in this bucket matching the arguments. | [
"Return",
"an",
"iterator",
"used",
"to",
"find",
"blobs",
"in",
"the",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L711-L802 |
27,875 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.delete | def delete(self, force=False, client=None):
"""Delete this bucket.
The bucket **must** be empty in order to submit a delete request. If
``force=True`` is passed, this will first attempt to delete all the
objects / blobs in the bucket (i.e. try to empty the bucket).
If the bucket doesn't exist, this will raise
:class:`google.cloud.exceptions.NotFound`. If the bucket is not empty
(and ``force=False``), will raise
:class:`google.cloud.exceptions.Conflict`.
If ``force=True`` and the bucket contains more than 256 objects / blobs
this will cowardly refuse to delete the objects (or the bucket). This
is to prevent accidental bucket deletion and to prevent extremely long
runtime of this method.
If :attr:`user_project` is set, bills the API request to that project.
:type force: bool
:param force: If True, empties the bucket's objects then deletes it.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:raises: :class:`ValueError` if ``force`` is ``True`` and the bucket
contains more than 256 objects / blobs.
"""
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
if force:
blobs = list(
self.list_blobs(
max_results=self._MAX_OBJECTS_FOR_ITERATION + 1, client=client
)
)
if len(blobs) > self._MAX_OBJECTS_FOR_ITERATION:
message = (
"Refusing to delete bucket with more than "
"%d objects. If you actually want to delete "
"this bucket, please delete the objects "
"yourself before calling Bucket.delete()."
) % (self._MAX_OBJECTS_FOR_ITERATION,)
raise ValueError(message)
# Ignore 404 errors on delete.
self.delete_blobs(blobs, on_error=lambda blob: None, client=client)
# We intentionally pass `_target_object=None` since a DELETE
# request has no response value (whether in a standard request or
# in a batch request).
client._connection.api_request(
method="DELETE",
path=self.path,
query_params=query_params,
_target_object=None,
) | python | def delete(self, force=False, client=None):
"""Delete this bucket.
The bucket **must** be empty in order to submit a delete request. If
``force=True`` is passed, this will first attempt to delete all the
objects / blobs in the bucket (i.e. try to empty the bucket).
If the bucket doesn't exist, this will raise
:class:`google.cloud.exceptions.NotFound`. If the bucket is not empty
(and ``force=False``), will raise
:class:`google.cloud.exceptions.Conflict`.
If ``force=True`` and the bucket contains more than 256 objects / blobs
this will cowardly refuse to delete the objects (or the bucket). This
is to prevent accidental bucket deletion and to prevent extremely long
runtime of this method.
If :attr:`user_project` is set, bills the API request to that project.
:type force: bool
:param force: If True, empties the bucket's objects then deletes it.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:raises: :class:`ValueError` if ``force`` is ``True`` and the bucket
contains more than 256 objects / blobs.
"""
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
if force:
blobs = list(
self.list_blobs(
max_results=self._MAX_OBJECTS_FOR_ITERATION + 1, client=client
)
)
if len(blobs) > self._MAX_OBJECTS_FOR_ITERATION:
message = (
"Refusing to delete bucket with more than "
"%d objects. If you actually want to delete "
"this bucket, please delete the objects "
"yourself before calling Bucket.delete()."
) % (self._MAX_OBJECTS_FOR_ITERATION,)
raise ValueError(message)
# Ignore 404 errors on delete.
self.delete_blobs(blobs, on_error=lambda blob: None, client=client)
# We intentionally pass `_target_object=None` since a DELETE
# request has no response value (whether in a standard request or
# in a batch request).
client._connection.api_request(
method="DELETE",
path=self.path,
query_params=query_params,
_target_object=None,
) | [
"def",
"delete",
"(",
"self",
",",
"force",
"=",
"False",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"query_params",
"=",
"{",
"}",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"query_params",
"[",
"\"userProject\"",
"]",
"=",
"self",
".",
"user_project",
"if",
"force",
":",
"blobs",
"=",
"list",
"(",
"self",
".",
"list_blobs",
"(",
"max_results",
"=",
"self",
".",
"_MAX_OBJECTS_FOR_ITERATION",
"+",
"1",
",",
"client",
"=",
"client",
")",
")",
"if",
"len",
"(",
"blobs",
")",
">",
"self",
".",
"_MAX_OBJECTS_FOR_ITERATION",
":",
"message",
"=",
"(",
"\"Refusing to delete bucket with more than \"",
"\"%d objects. If you actually want to delete \"",
"\"this bucket, please delete the objects \"",
"\"yourself before calling Bucket.delete().\"",
")",
"%",
"(",
"self",
".",
"_MAX_OBJECTS_FOR_ITERATION",
",",
")",
"raise",
"ValueError",
"(",
"message",
")",
"# Ignore 404 errors on delete.",
"self",
".",
"delete_blobs",
"(",
"blobs",
",",
"on_error",
"=",
"lambda",
"blob",
":",
"None",
",",
"client",
"=",
"client",
")",
"# We intentionally pass `_target_object=None` since a DELETE",
"# request has no response value (whether in a standard request or",
"# in a batch request).",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"DELETE\"",
",",
"path",
"=",
"self",
".",
"path",
",",
"query_params",
"=",
"query_params",
",",
"_target_object",
"=",
"None",
",",
")"
] | Delete this bucket.
The bucket **must** be empty in order to submit a delete request. If
``force=True`` is passed, this will first attempt to delete all the
objects / blobs in the bucket (i.e. try to empty the bucket).
If the bucket doesn't exist, this will raise
:class:`google.cloud.exceptions.NotFound`. If the bucket is not empty
(and ``force=False``), will raise
:class:`google.cloud.exceptions.Conflict`.
If ``force=True`` and the bucket contains more than 256 objects / blobs
this will cowardly refuse to delete the objects (or the bucket). This
is to prevent accidental bucket deletion and to prevent extremely long
runtime of this method.
If :attr:`user_project` is set, bills the API request to that project.
:type force: bool
:param force: If True, empties the bucket's objects then deletes it.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:raises: :class:`ValueError` if ``force`` is ``True`` and the bucket
contains more than 256 objects / blobs. | [
"Delete",
"this",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L831-L893 |
27,876 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.delete_blob | def delete_blob(self, blob_name, client=None, generation=None):
"""Deletes a blob from the current bucket.
If the blob isn't found (backend 404), raises a
:class:`google.cloud.exceptions.NotFound`.
For example:
.. literalinclude:: snippets.py
:start-after: [START delete_blob]
:end-before: [END delete_blob]
If :attr:`user_project` is set, bills the API request to that project.
:type blob_name: str
:param blob_name: A blob name to delete.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type generation: long
:param generation: Optional. If present, permanently deletes a specific
revision of this object.
:raises: :class:`google.cloud.exceptions.NotFound` (to suppress
the exception, call ``delete_blobs``, passing a no-op
``on_error`` callback, e.g.:
.. literalinclude:: snippets.py
:start-after: [START delete_blobs]
:end-before: [END delete_blobs]
"""
client = self._require_client(client)
blob = Blob(blob_name, bucket=self, generation=generation)
# We intentionally pass `_target_object=None` since a DELETE
# request has no response value (whether in a standard request or
# in a batch request).
client._connection.api_request(
method="DELETE",
path=blob.path,
query_params=blob._query_params,
_target_object=None,
) | python | def delete_blob(self, blob_name, client=None, generation=None):
"""Deletes a blob from the current bucket.
If the blob isn't found (backend 404), raises a
:class:`google.cloud.exceptions.NotFound`.
For example:
.. literalinclude:: snippets.py
:start-after: [START delete_blob]
:end-before: [END delete_blob]
If :attr:`user_project` is set, bills the API request to that project.
:type blob_name: str
:param blob_name: A blob name to delete.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type generation: long
:param generation: Optional. If present, permanently deletes a specific
revision of this object.
:raises: :class:`google.cloud.exceptions.NotFound` (to suppress
the exception, call ``delete_blobs``, passing a no-op
``on_error`` callback, e.g.:
.. literalinclude:: snippets.py
:start-after: [START delete_blobs]
:end-before: [END delete_blobs]
"""
client = self._require_client(client)
blob = Blob(blob_name, bucket=self, generation=generation)
# We intentionally pass `_target_object=None` since a DELETE
# request has no response value (whether in a standard request or
# in a batch request).
client._connection.api_request(
method="DELETE",
path=blob.path,
query_params=blob._query_params,
_target_object=None,
) | [
"def",
"delete_blob",
"(",
"self",
",",
"blob_name",
",",
"client",
"=",
"None",
",",
"generation",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"blob",
"=",
"Blob",
"(",
"blob_name",
",",
"bucket",
"=",
"self",
",",
"generation",
"=",
"generation",
")",
"# We intentionally pass `_target_object=None` since a DELETE",
"# request has no response value (whether in a standard request or",
"# in a batch request).",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"DELETE\"",
",",
"path",
"=",
"blob",
".",
"path",
",",
"query_params",
"=",
"blob",
".",
"_query_params",
",",
"_target_object",
"=",
"None",
",",
")"
] | Deletes a blob from the current bucket.
If the blob isn't found (backend 404), raises a
:class:`google.cloud.exceptions.NotFound`.
For example:
.. literalinclude:: snippets.py
:start-after: [START delete_blob]
:end-before: [END delete_blob]
If :attr:`user_project` is set, bills the API request to that project.
:type blob_name: str
:param blob_name: A blob name to delete.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type generation: long
:param generation: Optional. If present, permanently deletes a specific
revision of this object.
:raises: :class:`google.cloud.exceptions.NotFound` (to suppress
the exception, call ``delete_blobs``, passing a no-op
``on_error`` callback, e.g.:
.. literalinclude:: snippets.py
:start-after: [START delete_blobs]
:end-before: [END delete_blobs] | [
"Deletes",
"a",
"blob",
"from",
"the",
"current",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L895-L941 |
27,877 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.delete_blobs | def delete_blobs(self, blobs, on_error=None, client=None):
"""Deletes a list of blobs from the current bucket.
Uses :meth:`delete_blob` to delete each individual blob.
If :attr:`user_project` is set, bills the API request to that project.
:type blobs: list
:param blobs: A list of :class:`~google.cloud.storage.blob.Blob`-s or
blob names to delete.
:type on_error: callable
:param on_error: (Optional) Takes single argument: ``blob``. Called
called once for each blob raising
:class:`~google.cloud.exceptions.NotFound`;
otherwise, the exception is propagated.
:type client: :class:`~google.cloud.storage.client.Client`
:param client: (Optional) The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:raises: :class:`~google.cloud.exceptions.NotFound` (if
`on_error` is not passed).
"""
for blob in blobs:
try:
blob_name = blob
if not isinstance(blob_name, six.string_types):
blob_name = blob.name
self.delete_blob(blob_name, client=client)
except NotFound:
if on_error is not None:
on_error(blob)
else:
raise | python | def delete_blobs(self, blobs, on_error=None, client=None):
"""Deletes a list of blobs from the current bucket.
Uses :meth:`delete_blob` to delete each individual blob.
If :attr:`user_project` is set, bills the API request to that project.
:type blobs: list
:param blobs: A list of :class:`~google.cloud.storage.blob.Blob`-s or
blob names to delete.
:type on_error: callable
:param on_error: (Optional) Takes single argument: ``blob``. Called
called once for each blob raising
:class:`~google.cloud.exceptions.NotFound`;
otherwise, the exception is propagated.
:type client: :class:`~google.cloud.storage.client.Client`
:param client: (Optional) The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:raises: :class:`~google.cloud.exceptions.NotFound` (if
`on_error` is not passed).
"""
for blob in blobs:
try:
blob_name = blob
if not isinstance(blob_name, six.string_types):
blob_name = blob.name
self.delete_blob(blob_name, client=client)
except NotFound:
if on_error is not None:
on_error(blob)
else:
raise | [
"def",
"delete_blobs",
"(",
"self",
",",
"blobs",
",",
"on_error",
"=",
"None",
",",
"client",
"=",
"None",
")",
":",
"for",
"blob",
"in",
"blobs",
":",
"try",
":",
"blob_name",
"=",
"blob",
"if",
"not",
"isinstance",
"(",
"blob_name",
",",
"six",
".",
"string_types",
")",
":",
"blob_name",
"=",
"blob",
".",
"name",
"self",
".",
"delete_blob",
"(",
"blob_name",
",",
"client",
"=",
"client",
")",
"except",
"NotFound",
":",
"if",
"on_error",
"is",
"not",
"None",
":",
"on_error",
"(",
"blob",
")",
"else",
":",
"raise"
] | Deletes a list of blobs from the current bucket.
Uses :meth:`delete_blob` to delete each individual blob.
If :attr:`user_project` is set, bills the API request to that project.
:type blobs: list
:param blobs: A list of :class:`~google.cloud.storage.blob.Blob`-s or
blob names to delete.
:type on_error: callable
:param on_error: (Optional) Takes single argument: ``blob``. Called
called once for each blob raising
:class:`~google.cloud.exceptions.NotFound`;
otherwise, the exception is propagated.
:type client: :class:`~google.cloud.storage.client.Client`
:param client: (Optional) The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:raises: :class:`~google.cloud.exceptions.NotFound` (if
`on_error` is not passed). | [
"Deletes",
"a",
"list",
"of",
"blobs",
"from",
"the",
"current",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L943-L977 |
27,878 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.copy_blob | def copy_blob(
self,
blob,
destination_bucket,
new_name=None,
client=None,
preserve_acl=True,
source_generation=None,
):
"""Copy the given blob to the given bucket, optionally with a new name.
If :attr:`user_project` is set, bills the API request to that project.
:type blob: :class:`google.cloud.storage.blob.Blob`
:param blob: The blob to be copied.
:type destination_bucket: :class:`google.cloud.storage.bucket.Bucket`
:param destination_bucket: The bucket into which the blob should be
copied.
:type new_name: str
:param new_name: (optional) the new name for the copied file.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type preserve_acl: bool
:param preserve_acl: Optional. Copies ACL from old blob to new blob.
Default: True.
:type source_generation: long
:param source_generation: Optional. The generation of the blob to be
copied.
:rtype: :class:`google.cloud.storage.blob.Blob`
:returns: The new Blob.
"""
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
if source_generation is not None:
query_params["sourceGeneration"] = source_generation
if new_name is None:
new_name = blob.name
new_blob = Blob(bucket=destination_bucket, name=new_name)
api_path = blob.path + "/copyTo" + new_blob.path
copy_result = client._connection.api_request(
method="POST",
path=api_path,
query_params=query_params,
_target_object=new_blob,
)
if not preserve_acl:
new_blob.acl.save(acl={}, client=client)
new_blob._set_properties(copy_result)
return new_blob | python | def copy_blob(
self,
blob,
destination_bucket,
new_name=None,
client=None,
preserve_acl=True,
source_generation=None,
):
"""Copy the given blob to the given bucket, optionally with a new name.
If :attr:`user_project` is set, bills the API request to that project.
:type blob: :class:`google.cloud.storage.blob.Blob`
:param blob: The blob to be copied.
:type destination_bucket: :class:`google.cloud.storage.bucket.Bucket`
:param destination_bucket: The bucket into which the blob should be
copied.
:type new_name: str
:param new_name: (optional) the new name for the copied file.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type preserve_acl: bool
:param preserve_acl: Optional. Copies ACL from old blob to new blob.
Default: True.
:type source_generation: long
:param source_generation: Optional. The generation of the blob to be
copied.
:rtype: :class:`google.cloud.storage.blob.Blob`
:returns: The new Blob.
"""
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
if source_generation is not None:
query_params["sourceGeneration"] = source_generation
if new_name is None:
new_name = blob.name
new_blob = Blob(bucket=destination_bucket, name=new_name)
api_path = blob.path + "/copyTo" + new_blob.path
copy_result = client._connection.api_request(
method="POST",
path=api_path,
query_params=query_params,
_target_object=new_blob,
)
if not preserve_acl:
new_blob.acl.save(acl={}, client=client)
new_blob._set_properties(copy_result)
return new_blob | [
"def",
"copy_blob",
"(",
"self",
",",
"blob",
",",
"destination_bucket",
",",
"new_name",
"=",
"None",
",",
"client",
"=",
"None",
",",
"preserve_acl",
"=",
"True",
",",
"source_generation",
"=",
"None",
",",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"query_params",
"=",
"{",
"}",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"query_params",
"[",
"\"userProject\"",
"]",
"=",
"self",
".",
"user_project",
"if",
"source_generation",
"is",
"not",
"None",
":",
"query_params",
"[",
"\"sourceGeneration\"",
"]",
"=",
"source_generation",
"if",
"new_name",
"is",
"None",
":",
"new_name",
"=",
"blob",
".",
"name",
"new_blob",
"=",
"Blob",
"(",
"bucket",
"=",
"destination_bucket",
",",
"name",
"=",
"new_name",
")",
"api_path",
"=",
"blob",
".",
"path",
"+",
"\"/copyTo\"",
"+",
"new_blob",
".",
"path",
"copy_result",
"=",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"api_path",
",",
"query_params",
"=",
"query_params",
",",
"_target_object",
"=",
"new_blob",
",",
")",
"if",
"not",
"preserve_acl",
":",
"new_blob",
".",
"acl",
".",
"save",
"(",
"acl",
"=",
"{",
"}",
",",
"client",
"=",
"client",
")",
"new_blob",
".",
"_set_properties",
"(",
"copy_result",
")",
"return",
"new_blob"
] | Copy the given blob to the given bucket, optionally with a new name.
If :attr:`user_project` is set, bills the API request to that project.
:type blob: :class:`google.cloud.storage.blob.Blob`
:param blob: The blob to be copied.
:type destination_bucket: :class:`google.cloud.storage.bucket.Bucket`
:param destination_bucket: The bucket into which the blob should be
copied.
:type new_name: str
:param new_name: (optional) the new name for the copied file.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:type preserve_acl: bool
:param preserve_acl: Optional. Copies ACL from old blob to new blob.
Default: True.
:type source_generation: long
:param source_generation: Optional. The generation of the blob to be
copied.
:rtype: :class:`google.cloud.storage.blob.Blob`
:returns: The new Blob. | [
"Copy",
"the",
"given",
"blob",
"to",
"the",
"given",
"bucket",
"optionally",
"with",
"a",
"new",
"name",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L979-L1043 |
27,879 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.rename_blob | def rename_blob(self, blob, new_name, client=None):
"""Rename the given blob using copy and delete operations.
If :attr:`user_project` is set, bills the API request to that project.
Effectively, copies blob to the same bucket with a new name, then
deletes the blob.
.. warning::
This method will first duplicate the data and then delete the
old blob. This means that with very large objects renaming
could be a very (temporarily) costly or a very slow operation.
:type blob: :class:`google.cloud.storage.blob.Blob`
:param blob: The blob to be renamed.
:type new_name: str
:param new_name: The new name for this blob.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`Blob`
:returns: The newly-renamed blob.
"""
same_name = blob.name == new_name
new_blob = self.copy_blob(blob, self, new_name, client=client)
if not same_name:
blob.delete(client=client)
return new_blob | python | def rename_blob(self, blob, new_name, client=None):
"""Rename the given blob using copy and delete operations.
If :attr:`user_project` is set, bills the API request to that project.
Effectively, copies blob to the same bucket with a new name, then
deletes the blob.
.. warning::
This method will first duplicate the data and then delete the
old blob. This means that with very large objects renaming
could be a very (temporarily) costly or a very slow operation.
:type blob: :class:`google.cloud.storage.blob.Blob`
:param blob: The blob to be renamed.
:type new_name: str
:param new_name: The new name for this blob.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`Blob`
:returns: The newly-renamed blob.
"""
same_name = blob.name == new_name
new_blob = self.copy_blob(blob, self, new_name, client=client)
if not same_name:
blob.delete(client=client)
return new_blob | [
"def",
"rename_blob",
"(",
"self",
",",
"blob",
",",
"new_name",
",",
"client",
"=",
"None",
")",
":",
"same_name",
"=",
"blob",
".",
"name",
"==",
"new_name",
"new_blob",
"=",
"self",
".",
"copy_blob",
"(",
"blob",
",",
"self",
",",
"new_name",
",",
"client",
"=",
"client",
")",
"if",
"not",
"same_name",
":",
"blob",
".",
"delete",
"(",
"client",
"=",
"client",
")",
"return",
"new_blob"
] | Rename the given blob using copy and delete operations.
If :attr:`user_project` is set, bills the API request to that project.
Effectively, copies blob to the same bucket with a new name, then
deletes the blob.
.. warning::
This method will first duplicate the data and then delete the
old blob. This means that with very large objects renaming
could be a very (temporarily) costly or a very slow operation.
:type blob: :class:`google.cloud.storage.blob.Blob`
:param blob: The blob to be renamed.
:type new_name: str
:param new_name: The new name for this blob.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`Blob`
:returns: The newly-renamed blob. | [
"Rename",
"the",
"given",
"blob",
"using",
"copy",
"and",
"delete",
"operations",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1045-L1080 |
27,880 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.default_kms_key_name | def default_kms_key_name(self, value):
"""Set default KMS encryption key for objects in the bucket.
:type value: str or None
:param value: new KMS key name (None to clear any existing key).
"""
encryption_config = self._properties.get("encryption", {})
encryption_config["defaultKmsKeyName"] = value
self._patch_property("encryption", encryption_config) | python | def default_kms_key_name(self, value):
"""Set default KMS encryption key for objects in the bucket.
:type value: str or None
:param value: new KMS key name (None to clear any existing key).
"""
encryption_config = self._properties.get("encryption", {})
encryption_config["defaultKmsKeyName"] = value
self._patch_property("encryption", encryption_config) | [
"def",
"default_kms_key_name",
"(",
"self",
",",
"value",
")",
":",
"encryption_config",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"\"encryption\"",
",",
"{",
"}",
")",
"encryption_config",
"[",
"\"defaultKmsKeyName\"",
"]",
"=",
"value",
"self",
".",
"_patch_property",
"(",
"\"encryption\"",
",",
"encryption_config",
")"
] | Set default KMS encryption key for objects in the bucket.
:type value: str or None
:param value: new KMS key name (None to clear any existing key). | [
"Set",
"default",
"KMS",
"encryption",
"key",
"for",
"objects",
"in",
"the",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1154-L1162 |
27,881 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.labels | def labels(self):
"""Retrieve or set labels assigned to this bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets#labels
.. note::
The getter for this property returns a dict which is a *copy*
of the bucket's labels. Mutating that dict has no effect unless
you then re-assign the dict via the setter. E.g.:
>>> labels = bucket.labels
>>> labels['new_key'] = 'some-label'
>>> del labels['old_key']
>>> bucket.labels = labels
>>> bucket.update()
:setter: Set labels for this bucket.
:getter: Gets the labels for this bucket.
:rtype: :class:`dict`
:returns: Name-value pairs (string->string) labelling the bucket.
"""
labels = self._properties.get("labels")
if labels is None:
return {}
return copy.deepcopy(labels) | python | def labels(self):
"""Retrieve or set labels assigned to this bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets#labels
.. note::
The getter for this property returns a dict which is a *copy*
of the bucket's labels. Mutating that dict has no effect unless
you then re-assign the dict via the setter. E.g.:
>>> labels = bucket.labels
>>> labels['new_key'] = 'some-label'
>>> del labels['old_key']
>>> bucket.labels = labels
>>> bucket.update()
:setter: Set labels for this bucket.
:getter: Gets the labels for this bucket.
:rtype: :class:`dict`
:returns: Name-value pairs (string->string) labelling the bucket.
"""
labels = self._properties.get("labels")
if labels is None:
return {}
return copy.deepcopy(labels) | [
"def",
"labels",
"(",
"self",
")",
":",
"labels",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"\"labels\"",
")",
"if",
"labels",
"is",
"None",
":",
"return",
"{",
"}",
"return",
"copy",
".",
"deepcopy",
"(",
"labels",
")"
] | Retrieve or set labels assigned to this bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets#labels
.. note::
The getter for this property returns a dict which is a *copy*
of the bucket's labels. Mutating that dict has no effect unless
you then re-assign the dict via the setter. E.g.:
>>> labels = bucket.labels
>>> labels['new_key'] = 'some-label'
>>> del labels['old_key']
>>> bucket.labels = labels
>>> bucket.update()
:setter: Set labels for this bucket.
:getter: Gets the labels for this bucket.
:rtype: :class:`dict`
:returns: Name-value pairs (string->string) labelling the bucket. | [
"Retrieve",
"or",
"set",
"labels",
"assigned",
"to",
"this",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1165-L1192 |
27,882 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.labels | def labels(self, mapping):
"""Set labels assigned to this bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets#labels
:type mapping: :class:`dict`
:param mapping: Name-value pairs (string->string) labelling the bucket.
"""
# If any labels have been expressly removed, we need to track this
# so that a future .patch() call can do the correct thing.
existing = set([k for k in self.labels.keys()])
incoming = set([k for k in mapping.keys()])
self._label_removals = self._label_removals.union(existing.difference(incoming))
# Actually update the labels on the object.
self._patch_property("labels", copy.deepcopy(mapping)) | python | def labels(self, mapping):
"""Set labels assigned to this bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets#labels
:type mapping: :class:`dict`
:param mapping: Name-value pairs (string->string) labelling the bucket.
"""
# If any labels have been expressly removed, we need to track this
# so that a future .patch() call can do the correct thing.
existing = set([k for k in self.labels.keys()])
incoming = set([k for k in mapping.keys()])
self._label_removals = self._label_removals.union(existing.difference(incoming))
# Actually update the labels on the object.
self._patch_property("labels", copy.deepcopy(mapping)) | [
"def",
"labels",
"(",
"self",
",",
"mapping",
")",
":",
"# If any labels have been expressly removed, we need to track this",
"# so that a future .patch() call can do the correct thing.",
"existing",
"=",
"set",
"(",
"[",
"k",
"for",
"k",
"in",
"self",
".",
"labels",
".",
"keys",
"(",
")",
"]",
")",
"incoming",
"=",
"set",
"(",
"[",
"k",
"for",
"k",
"in",
"mapping",
".",
"keys",
"(",
")",
"]",
")",
"self",
".",
"_label_removals",
"=",
"self",
".",
"_label_removals",
".",
"union",
"(",
"existing",
".",
"difference",
"(",
"incoming",
")",
")",
"# Actually update the labels on the object.",
"self",
".",
"_patch_property",
"(",
"\"labels\"",
",",
"copy",
".",
"deepcopy",
"(",
"mapping",
")",
")"
] | Set labels assigned to this bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets#labels
:type mapping: :class:`dict`
:param mapping: Name-value pairs (string->string) labelling the bucket. | [
"Set",
"labels",
"assigned",
"to",
"this",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1195-L1211 |
27,883 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.iam_configuration | def iam_configuration(self):
"""Retrieve IAM configuration for this bucket.
:rtype: :class:`IAMConfiguration`
:returns: an instance for managing the bucket's IAM configuration.
"""
info = self._properties.get("iamConfiguration", {})
return IAMConfiguration.from_api_repr(info, self) | python | def iam_configuration(self):
"""Retrieve IAM configuration for this bucket.
:rtype: :class:`IAMConfiguration`
:returns: an instance for managing the bucket's IAM configuration.
"""
info = self._properties.get("iamConfiguration", {})
return IAMConfiguration.from_api_repr(info, self) | [
"def",
"iam_configuration",
"(",
"self",
")",
":",
"info",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"\"iamConfiguration\"",
",",
"{",
"}",
")",
"return",
"IAMConfiguration",
".",
"from_api_repr",
"(",
"info",
",",
"self",
")"
] | Retrieve IAM configuration for this bucket.
:rtype: :class:`IAMConfiguration`
:returns: an instance for managing the bucket's IAM configuration. | [
"Retrieve",
"IAM",
"configuration",
"for",
"this",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1239-L1246 |
27,884 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.lifecycle_rules | def lifecycle_rules(self):
"""Retrieve or set lifecycle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
.. note::
The getter for this property returns a list which contains
*copies* of the bucket's lifecycle rules mappings. Mutating the
list or one of its dicts has no effect unless you then re-assign
the dict via the setter. E.g.:
>>> rules = bucket.lifecycle_rules
>>> rules.append({'origin': '/foo', ...})
>>> rules[1]['rule']['action']['type'] = 'Delete'
>>> del rules[0]
>>> bucket.lifecycle_rules = rules
>>> bucket.update()
:setter: Set lifestyle rules for this bucket.
:getter: Gets the lifestyle rules for this bucket.
:rtype: generator(dict)
:returns: A sequence of mappings describing each lifecycle rule.
"""
info = self._properties.get("lifecycle", {})
for rule in info.get("rule", ()):
action_type = rule["action"]["type"]
if action_type == "Delete":
yield LifecycleRuleDelete.from_api_repr(rule)
elif action_type == "SetStorageClass":
yield LifecycleRuleSetStorageClass.from_api_repr(rule)
else:
raise ValueError("Unknown lifecycle rule: {}".format(rule)) | python | def lifecycle_rules(self):
"""Retrieve or set lifecycle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
.. note::
The getter for this property returns a list which contains
*copies* of the bucket's lifecycle rules mappings. Mutating the
list or one of its dicts has no effect unless you then re-assign
the dict via the setter. E.g.:
>>> rules = bucket.lifecycle_rules
>>> rules.append({'origin': '/foo', ...})
>>> rules[1]['rule']['action']['type'] = 'Delete'
>>> del rules[0]
>>> bucket.lifecycle_rules = rules
>>> bucket.update()
:setter: Set lifestyle rules for this bucket.
:getter: Gets the lifestyle rules for this bucket.
:rtype: generator(dict)
:returns: A sequence of mappings describing each lifecycle rule.
"""
info = self._properties.get("lifecycle", {})
for rule in info.get("rule", ()):
action_type = rule["action"]["type"]
if action_type == "Delete":
yield LifecycleRuleDelete.from_api_repr(rule)
elif action_type == "SetStorageClass":
yield LifecycleRuleSetStorageClass.from_api_repr(rule)
else:
raise ValueError("Unknown lifecycle rule: {}".format(rule)) | [
"def",
"lifecycle_rules",
"(",
"self",
")",
":",
"info",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"\"lifecycle\"",
",",
"{",
"}",
")",
"for",
"rule",
"in",
"info",
".",
"get",
"(",
"\"rule\"",
",",
"(",
")",
")",
":",
"action_type",
"=",
"rule",
"[",
"\"action\"",
"]",
"[",
"\"type\"",
"]",
"if",
"action_type",
"==",
"\"Delete\"",
":",
"yield",
"LifecycleRuleDelete",
".",
"from_api_repr",
"(",
"rule",
")",
"elif",
"action_type",
"==",
"\"SetStorageClass\"",
":",
"yield",
"LifecycleRuleSetStorageClass",
".",
"from_api_repr",
"(",
"rule",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown lifecycle rule: {}\"",
".",
"format",
"(",
"rule",
")",
")"
] | Retrieve or set lifecycle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
.. note::
The getter for this property returns a list which contains
*copies* of the bucket's lifecycle rules mappings. Mutating the
list or one of its dicts has no effect unless you then re-assign
the dict via the setter. E.g.:
>>> rules = bucket.lifecycle_rules
>>> rules.append({'origin': '/foo', ...})
>>> rules[1]['rule']['action']['type'] = 'Delete'
>>> del rules[0]
>>> bucket.lifecycle_rules = rules
>>> bucket.update()
:setter: Set lifestyle rules for this bucket.
:getter: Gets the lifestyle rules for this bucket.
:rtype: generator(dict)
:returns: A sequence of mappings describing each lifecycle rule. | [
"Retrieve",
"or",
"set",
"lifecycle",
"rules",
"configured",
"for",
"this",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1249-L1283 |
27,885 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.lifecycle_rules | def lifecycle_rules(self, rules):
"""Set lifestyle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
:type entries: list of dictionaries
:param entries: A sequence of mappings describing each lifecycle rule.
"""
rules = [dict(rule) for rule in rules] # Convert helpers if needed
self._patch_property("lifecycle", {"rule": rules}) | python | def lifecycle_rules(self, rules):
"""Set lifestyle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
:type entries: list of dictionaries
:param entries: A sequence of mappings describing each lifecycle rule.
"""
rules = [dict(rule) for rule in rules] # Convert helpers if needed
self._patch_property("lifecycle", {"rule": rules}) | [
"def",
"lifecycle_rules",
"(",
"self",
",",
"rules",
")",
":",
"rules",
"=",
"[",
"dict",
"(",
"rule",
")",
"for",
"rule",
"in",
"rules",
"]",
"# Convert helpers if needed",
"self",
".",
"_patch_property",
"(",
"\"lifecycle\"",
",",
"{",
"\"rule\"",
":",
"rules",
"}",
")"
] | Set lifestyle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
:type entries: list of dictionaries
:param entries: A sequence of mappings describing each lifecycle rule. | [
"Set",
"lifestyle",
"rules",
"configured",
"for",
"this",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1286-L1296 |
27,886 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.enable_logging | def enable_logging(self, bucket_name, object_prefix=""):
"""Enable access logging for this bucket.
See https://cloud.google.com/storage/docs/access-logs
:type bucket_name: str
:param bucket_name: name of bucket in which to store access logs
:type object_prefix: str
:param object_prefix: prefix for access log filenames
"""
info = {"logBucket": bucket_name, "logObjectPrefix": object_prefix}
self._patch_property("logging", info) | python | def enable_logging(self, bucket_name, object_prefix=""):
"""Enable access logging for this bucket.
See https://cloud.google.com/storage/docs/access-logs
:type bucket_name: str
:param bucket_name: name of bucket in which to store access logs
:type object_prefix: str
:param object_prefix: prefix for access log filenames
"""
info = {"logBucket": bucket_name, "logObjectPrefix": object_prefix}
self._patch_property("logging", info) | [
"def",
"enable_logging",
"(",
"self",
",",
"bucket_name",
",",
"object_prefix",
"=",
"\"\"",
")",
":",
"info",
"=",
"{",
"\"logBucket\"",
":",
"bucket_name",
",",
"\"logObjectPrefix\"",
":",
"object_prefix",
"}",
"self",
".",
"_patch_property",
"(",
"\"logging\"",
",",
"info",
")"
] | Enable access logging for this bucket.
See https://cloud.google.com/storage/docs/access-logs
:type bucket_name: str
:param bucket_name: name of bucket in which to store access logs
:type object_prefix: str
:param object_prefix: prefix for access log filenames | [
"Enable",
"access",
"logging",
"for",
"this",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1388-L1400 |
27,887 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.retention_policy_effective_time | def retention_policy_effective_time(self):
"""Retrieve the effective time of the bucket's retention policy.
:rtype: datetime.datetime or ``NoneType``
:returns: point-in time at which the bucket's retention policy is
effective, or ``None`` if the property is not
set locally.
"""
policy = self._properties.get("retentionPolicy")
if policy is not None:
timestamp = policy.get("effectiveTime")
if timestamp is not None:
return _rfc3339_to_datetime(timestamp) | python | def retention_policy_effective_time(self):
"""Retrieve the effective time of the bucket's retention policy.
:rtype: datetime.datetime or ``NoneType``
:returns: point-in time at which the bucket's retention policy is
effective, or ``None`` if the property is not
set locally.
"""
policy = self._properties.get("retentionPolicy")
if policy is not None:
timestamp = policy.get("effectiveTime")
if timestamp is not None:
return _rfc3339_to_datetime(timestamp) | [
"def",
"retention_policy_effective_time",
"(",
"self",
")",
":",
"policy",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"\"retentionPolicy\"",
")",
"if",
"policy",
"is",
"not",
"None",
":",
"timestamp",
"=",
"policy",
".",
"get",
"(",
"\"effectiveTime\"",
")",
"if",
"timestamp",
"is",
"not",
"None",
":",
"return",
"_rfc3339_to_datetime",
"(",
"timestamp",
")"
] | Retrieve the effective time of the bucket's retention policy.
:rtype: datetime.datetime or ``NoneType``
:returns: point-in time at which the bucket's retention policy is
effective, or ``None`` if the property is not
set locally. | [
"Retrieve",
"the",
"effective",
"time",
"of",
"the",
"bucket",
"s",
"retention",
"policy",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1450-L1462 |
27,888 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.retention_period | def retention_period(self):
"""Retrieve or set the retention period for items in the bucket.
:rtype: int or ``NoneType``
:returns: number of seconds to retain items after upload or release
from event-based lock, or ``None`` if the property is not
set locally.
"""
policy = self._properties.get("retentionPolicy")
if policy is not None:
period = policy.get("retentionPeriod")
if period is not None:
return int(period) | python | def retention_period(self):
"""Retrieve or set the retention period for items in the bucket.
:rtype: int or ``NoneType``
:returns: number of seconds to retain items after upload or release
from event-based lock, or ``None`` if the property is not
set locally.
"""
policy = self._properties.get("retentionPolicy")
if policy is not None:
period = policy.get("retentionPeriod")
if period is not None:
return int(period) | [
"def",
"retention_period",
"(",
"self",
")",
":",
"policy",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"\"retentionPolicy\"",
")",
"if",
"policy",
"is",
"not",
"None",
":",
"period",
"=",
"policy",
".",
"get",
"(",
"\"retentionPeriod\"",
")",
"if",
"period",
"is",
"not",
"None",
":",
"return",
"int",
"(",
"period",
")"
] | Retrieve or set the retention period for items in the bucket.
:rtype: int or ``NoneType``
:returns: number of seconds to retain items after upload or release
from event-based lock, or ``None`` if the property is not
set locally. | [
"Retrieve",
"or",
"set",
"the",
"retention",
"period",
"for",
"items",
"in",
"the",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1478-L1490 |
27,889 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.retention_period | def retention_period(self, value):
"""Set the retention period for items in the bucket.
:type value: int
:param value:
number of seconds to retain items after upload or release from
event-based lock.
:raises ValueError: if the bucket's retention policy is locked.
"""
policy = self._properties.setdefault("retentionPolicy", {})
if value is not None:
policy["retentionPeriod"] = str(value)
else:
policy = None
self._patch_property("retentionPolicy", policy) | python | def retention_period(self, value):
"""Set the retention period for items in the bucket.
:type value: int
:param value:
number of seconds to retain items after upload or release from
event-based lock.
:raises ValueError: if the bucket's retention policy is locked.
"""
policy = self._properties.setdefault("retentionPolicy", {})
if value is not None:
policy["retentionPeriod"] = str(value)
else:
policy = None
self._patch_property("retentionPolicy", policy) | [
"def",
"retention_period",
"(",
"self",
",",
"value",
")",
":",
"policy",
"=",
"self",
".",
"_properties",
".",
"setdefault",
"(",
"\"retentionPolicy\"",
",",
"{",
"}",
")",
"if",
"value",
"is",
"not",
"None",
":",
"policy",
"[",
"\"retentionPeriod\"",
"]",
"=",
"str",
"(",
"value",
")",
"else",
":",
"policy",
"=",
"None",
"self",
".",
"_patch_property",
"(",
"\"retentionPolicy\"",
",",
"policy",
")"
] | Set the retention period for items in the bucket.
:type value: int
:param value:
number of seconds to retain items after upload or release from
event-based lock.
:raises ValueError: if the bucket's retention policy is locked. | [
"Set",
"the",
"retention",
"period",
"for",
"items",
"in",
"the",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1493-L1508 |
27,890 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.storage_class | def storage_class(self, value):
"""Set the storage class for the bucket.
See https://cloud.google.com/storage/docs/storage-classes
:type value: str
:param value: one of "MULTI_REGIONAL", "REGIONAL", "NEARLINE",
"COLDLINE", "STANDARD", or "DURABLE_REDUCED_AVAILABILITY"
"""
if value not in self._STORAGE_CLASSES:
raise ValueError("Invalid storage class: %s" % (value,))
self._patch_property("storageClass", value) | python | def storage_class(self, value):
"""Set the storage class for the bucket.
See https://cloud.google.com/storage/docs/storage-classes
:type value: str
:param value: one of "MULTI_REGIONAL", "REGIONAL", "NEARLINE",
"COLDLINE", "STANDARD", or "DURABLE_REDUCED_AVAILABILITY"
"""
if value not in self._STORAGE_CLASSES:
raise ValueError("Invalid storage class: %s" % (value,))
self._patch_property("storageClass", value) | [
"def",
"storage_class",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"self",
".",
"_STORAGE_CLASSES",
":",
"raise",
"ValueError",
"(",
"\"Invalid storage class: %s\"",
"%",
"(",
"value",
",",
")",
")",
"self",
".",
"_patch_property",
"(",
"\"storageClass\"",
",",
"value",
")"
] | Set the storage class for the bucket.
See https://cloud.google.com/storage/docs/storage-classes
:type value: str
:param value: one of "MULTI_REGIONAL", "REGIONAL", "NEARLINE",
"COLDLINE", "STANDARD", or "DURABLE_REDUCED_AVAILABILITY" | [
"Set",
"the",
"storage",
"class",
"for",
"the",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1539-L1550 |
27,891 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.configure_website | def configure_website(self, main_page_suffix=None, not_found_page=None):
"""Configure website-related properties.
See https://cloud.google.com/storage/docs/hosting-static-website
.. note::
This (apparently) only works
if your bucket name is a domain name
(and to do that, you need to get approved somehow...).
If you want this bucket to host a website, just provide the name
of an index page and a page to use when a blob isn't found:
.. literalinclude:: snippets.py
:start-after: [START configure_website]
:end-before: [END configure_website]
You probably should also make the whole bucket public:
.. literalinclude:: snippets.py
:start-after: [START make_public]
:end-before: [END make_public]
This says: "Make the bucket public, and all the stuff already in
the bucket, and anything else I add to the bucket. Just make it
all public."
:type main_page_suffix: str
:param main_page_suffix: The page to use as the main page
of a directory.
Typically something like index.html.
:type not_found_page: str
:param not_found_page: The file to use when a page isn't found.
"""
data = {"mainPageSuffix": main_page_suffix, "notFoundPage": not_found_page}
self._patch_property("website", data) | python | def configure_website(self, main_page_suffix=None, not_found_page=None):
"""Configure website-related properties.
See https://cloud.google.com/storage/docs/hosting-static-website
.. note::
This (apparently) only works
if your bucket name is a domain name
(and to do that, you need to get approved somehow...).
If you want this bucket to host a website, just provide the name
of an index page and a page to use when a blob isn't found:
.. literalinclude:: snippets.py
:start-after: [START configure_website]
:end-before: [END configure_website]
You probably should also make the whole bucket public:
.. literalinclude:: snippets.py
:start-after: [START make_public]
:end-before: [END make_public]
This says: "Make the bucket public, and all the stuff already in
the bucket, and anything else I add to the bucket. Just make it
all public."
:type main_page_suffix: str
:param main_page_suffix: The page to use as the main page
of a directory.
Typically something like index.html.
:type not_found_page: str
:param not_found_page: The file to use when a page isn't found.
"""
data = {"mainPageSuffix": main_page_suffix, "notFoundPage": not_found_page}
self._patch_property("website", data) | [
"def",
"configure_website",
"(",
"self",
",",
"main_page_suffix",
"=",
"None",
",",
"not_found_page",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"mainPageSuffix\"",
":",
"main_page_suffix",
",",
"\"notFoundPage\"",
":",
"not_found_page",
"}",
"self",
".",
"_patch_property",
"(",
"\"website\"",
",",
"data",
")"
] | Configure website-related properties.
See https://cloud.google.com/storage/docs/hosting-static-website
.. note::
This (apparently) only works
if your bucket name is a domain name
(and to do that, you need to get approved somehow...).
If you want this bucket to host a website, just provide the name
of an index page and a page to use when a blob isn't found:
.. literalinclude:: snippets.py
:start-after: [START configure_website]
:end-before: [END configure_website]
You probably should also make the whole bucket public:
.. literalinclude:: snippets.py
:start-after: [START make_public]
:end-before: [END make_public]
This says: "Make the bucket public, and all the stuff already in
the bucket, and anything else I add to the bucket. Just make it
all public."
:type main_page_suffix: str
:param main_page_suffix: The page to use as the main page
of a directory.
Typically something like index.html.
:type not_found_page: str
:param not_found_page: The file to use when a page isn't found. | [
"Configure",
"website",
"-",
"related",
"properties",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1624-L1660 |
27,892 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.get_iam_policy | def get_iam_policy(self, client=None):
"""Retrieve the IAM policy for the bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`google.api_core.iam.Policy`
:returns: the policy instance, based on the resource returned from
the ``getIamPolicy`` API request.
"""
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
info = client._connection.api_request(
method="GET",
path="%s/iam" % (self.path,),
query_params=query_params,
_target_object=None,
)
return Policy.from_api_repr(info) | python | def get_iam_policy(self, client=None):
"""Retrieve the IAM policy for the bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`google.api_core.iam.Policy`
:returns: the policy instance, based on the resource returned from
the ``getIamPolicy`` API request.
"""
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
info = client._connection.api_request(
method="GET",
path="%s/iam" % (self.path,),
query_params=query_params,
_target_object=None,
)
return Policy.from_api_repr(info) | [
"def",
"get_iam_policy",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"query_params",
"=",
"{",
"}",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"query_params",
"[",
"\"userProject\"",
"]",
"=",
"self",
".",
"user_project",
"info",
"=",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"\"%s/iam\"",
"%",
"(",
"self",
".",
"path",
",",
")",
",",
"query_params",
"=",
"query_params",
",",
"_target_object",
"=",
"None",
",",
")",
"return",
"Policy",
".",
"from_api_repr",
"(",
"info",
")"
] | Retrieve the IAM policy for the bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`google.api_core.iam.Policy`
:returns: the policy instance, based on the resource returned from
the ``getIamPolicy`` API request. | [
"Retrieve",
"the",
"IAM",
"policy",
"for",
"the",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1670-L1699 |
27,893 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.set_iam_policy | def set_iam_policy(self, policy, client=None):
"""Update the IAM policy for the bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy
If :attr:`user_project` is set, bills the API request to that project.
:type policy: :class:`google.api_core.iam.Policy`
:param policy: policy instance used to update bucket's IAM policy.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`google.api_core.iam.Policy`
:returns: the policy instance, based on the resource returned from
the ``setIamPolicy`` API request.
"""
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
resource = policy.to_api_repr()
resource["resourceId"] = self.path
info = client._connection.api_request(
method="PUT",
path="%s/iam" % (self.path,),
query_params=query_params,
data=resource,
_target_object=None,
)
return Policy.from_api_repr(info) | python | def set_iam_policy(self, policy, client=None):
"""Update the IAM policy for the bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy
If :attr:`user_project` is set, bills the API request to that project.
:type policy: :class:`google.api_core.iam.Policy`
:param policy: policy instance used to update bucket's IAM policy.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`google.api_core.iam.Policy`
:returns: the policy instance, based on the resource returned from
the ``setIamPolicy`` API request.
"""
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
resource = policy.to_api_repr()
resource["resourceId"] = self.path
info = client._connection.api_request(
method="PUT",
path="%s/iam" % (self.path,),
query_params=query_params,
data=resource,
_target_object=None,
)
return Policy.from_api_repr(info) | [
"def",
"set_iam_policy",
"(",
"self",
",",
"policy",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"query_params",
"=",
"{",
"}",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"query_params",
"[",
"\"userProject\"",
"]",
"=",
"self",
".",
"user_project",
"resource",
"=",
"policy",
".",
"to_api_repr",
"(",
")",
"resource",
"[",
"\"resourceId\"",
"]",
"=",
"self",
".",
"path",
"info",
"=",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"PUT\"",
",",
"path",
"=",
"\"%s/iam\"",
"%",
"(",
"self",
".",
"path",
",",
")",
",",
"query_params",
"=",
"query_params",
",",
"data",
"=",
"resource",
",",
"_target_object",
"=",
"None",
",",
")",
"return",
"Policy",
".",
"from_api_repr",
"(",
"info",
")"
] | Update the IAM policy for the bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy
If :attr:`user_project` is set, bills the API request to that project.
:type policy: :class:`google.api_core.iam.Policy`
:param policy: policy instance used to update bucket's IAM policy.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: :class:`google.api_core.iam.Policy`
:returns: the policy instance, based on the resource returned from
the ``setIamPolicy`` API request. | [
"Update",
"the",
"IAM",
"policy",
"for",
"the",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1701-L1736 |
27,894 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.make_private | def make_private(self, recursive=False, future=False, client=None):
"""Update bucket's ACL, revoking read access for anonymous users.
:type recursive: bool
:param recursive: If True, this will make all blobs inside the bucket
private as well.
:type future: bool
:param future: If True, this will make all objects created in the
future private as well.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:raises ValueError:
If ``recursive`` is True, and the bucket contains more than 256
blobs. This is to prevent extremely long runtime of this
method. For such buckets, iterate over the blobs returned by
:meth:`list_blobs` and call
:meth:`~google.cloud.storage.blob.Blob.make_private`
for each blob.
"""
self.acl.all().revoke_read()
self.acl.save(client=client)
if future:
doa = self.default_object_acl
if not doa.loaded:
doa.reload(client=client)
doa.all().revoke_read()
doa.save(client=client)
if recursive:
blobs = list(
self.list_blobs(
projection="full",
max_results=self._MAX_OBJECTS_FOR_ITERATION + 1,
client=client,
)
)
if len(blobs) > self._MAX_OBJECTS_FOR_ITERATION:
message = (
"Refusing to make private recursively with more than "
"%d objects. If you actually want to make every object "
"in this bucket private, iterate through the blobs "
"returned by 'Bucket.list_blobs()' and call "
"'make_private' on each one."
) % (self._MAX_OBJECTS_FOR_ITERATION,)
raise ValueError(message)
for blob in blobs:
blob.acl.all().revoke_read()
blob.acl.save(client=client) | python | def make_private(self, recursive=False, future=False, client=None):
"""Update bucket's ACL, revoking read access for anonymous users.
:type recursive: bool
:param recursive: If True, this will make all blobs inside the bucket
private as well.
:type future: bool
:param future: If True, this will make all objects created in the
future private as well.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:raises ValueError:
If ``recursive`` is True, and the bucket contains more than 256
blobs. This is to prevent extremely long runtime of this
method. For such buckets, iterate over the blobs returned by
:meth:`list_blobs` and call
:meth:`~google.cloud.storage.blob.Blob.make_private`
for each blob.
"""
self.acl.all().revoke_read()
self.acl.save(client=client)
if future:
doa = self.default_object_acl
if not doa.loaded:
doa.reload(client=client)
doa.all().revoke_read()
doa.save(client=client)
if recursive:
blobs = list(
self.list_blobs(
projection="full",
max_results=self._MAX_OBJECTS_FOR_ITERATION + 1,
client=client,
)
)
if len(blobs) > self._MAX_OBJECTS_FOR_ITERATION:
message = (
"Refusing to make private recursively with more than "
"%d objects. If you actually want to make every object "
"in this bucket private, iterate through the blobs "
"returned by 'Bucket.list_blobs()' and call "
"'make_private' on each one."
) % (self._MAX_OBJECTS_FOR_ITERATION,)
raise ValueError(message)
for blob in blobs:
blob.acl.all().revoke_read()
blob.acl.save(client=client) | [
"def",
"make_private",
"(",
"self",
",",
"recursive",
"=",
"False",
",",
"future",
"=",
"False",
",",
"client",
"=",
"None",
")",
":",
"self",
".",
"acl",
".",
"all",
"(",
")",
".",
"revoke_read",
"(",
")",
"self",
".",
"acl",
".",
"save",
"(",
"client",
"=",
"client",
")",
"if",
"future",
":",
"doa",
"=",
"self",
".",
"default_object_acl",
"if",
"not",
"doa",
".",
"loaded",
":",
"doa",
".",
"reload",
"(",
"client",
"=",
"client",
")",
"doa",
".",
"all",
"(",
")",
".",
"revoke_read",
"(",
")",
"doa",
".",
"save",
"(",
"client",
"=",
"client",
")",
"if",
"recursive",
":",
"blobs",
"=",
"list",
"(",
"self",
".",
"list_blobs",
"(",
"projection",
"=",
"\"full\"",
",",
"max_results",
"=",
"self",
".",
"_MAX_OBJECTS_FOR_ITERATION",
"+",
"1",
",",
"client",
"=",
"client",
",",
")",
")",
"if",
"len",
"(",
"blobs",
")",
">",
"self",
".",
"_MAX_OBJECTS_FOR_ITERATION",
":",
"message",
"=",
"(",
"\"Refusing to make private recursively with more than \"",
"\"%d objects. If you actually want to make every object \"",
"\"in this bucket private, iterate through the blobs \"",
"\"returned by 'Bucket.list_blobs()' and call \"",
"\"'make_private' on each one.\"",
")",
"%",
"(",
"self",
".",
"_MAX_OBJECTS_FOR_ITERATION",
",",
")",
"raise",
"ValueError",
"(",
"message",
")",
"for",
"blob",
"in",
"blobs",
":",
"blob",
".",
"acl",
".",
"all",
"(",
")",
".",
"revoke_read",
"(",
")",
"blob",
".",
"acl",
".",
"save",
"(",
"client",
"=",
"client",
")"
] | Update bucket's ACL, revoking read access for anonymous users.
:type recursive: bool
:param recursive: If True, this will make all blobs inside the bucket
private as well.
:type future: bool
:param future: If True, this will make all objects created in the
future private as well.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:raises ValueError:
If ``recursive`` is True, and the bucket contains more than 256
blobs. This is to prevent extremely long runtime of this
method. For such buckets, iterate over the blobs returned by
:meth:`list_blobs` and call
:meth:`~google.cloud.storage.blob.Blob.make_private`
for each blob. | [
"Update",
"bucket",
"s",
"ACL",
"revoking",
"read",
"access",
"for",
"anonymous",
"users",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1826-L1880 |
27,895 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.generate_upload_policy | def generate_upload_policy(self, conditions, expiration=None, client=None):
"""Create a signed upload policy for uploading objects.
This method generates and signs a policy document. You can use
`policy documents`_ to allow visitors to a website to upload files to
Google Cloud Storage without giving them direct write access.
For example:
.. literalinclude:: snippets.py
:start-after: [START policy_document]
:end-before: [END policy_document]
.. _policy documents:
https://cloud.google.com/storage/docs/xml-api\
/post-object#policydocument
:type expiration: datetime
:param expiration: Optional expiration in UTC. If not specified, the
policy will expire in 1 hour.
:type conditions: list
:param conditions: A list of conditions as described in the
`policy documents`_ documentation.
:type client: :class:`~google.cloud.storage.client.Client`
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: dict
:returns: A dictionary of (form field name, form field value) of form
fields that should be added to your HTML upload form in order
to attach the signature.
"""
client = self._require_client(client)
credentials = client._base_connection.credentials
_signing.ensure_signed_credentials(credentials)
if expiration is None:
expiration = _NOW() + datetime.timedelta(hours=1)
conditions = conditions + [{"bucket": self.name}]
policy_document = {
"expiration": _datetime_to_rfc3339(expiration),
"conditions": conditions,
}
encoded_policy_document = base64.b64encode(
json.dumps(policy_document).encode("utf-8")
)
signature = base64.b64encode(credentials.sign_bytes(encoded_policy_document))
fields = {
"bucket": self.name,
"GoogleAccessId": credentials.signer_email,
"policy": encoded_policy_document.decode("utf-8"),
"signature": signature.decode("utf-8"),
}
return fields | python | def generate_upload_policy(self, conditions, expiration=None, client=None):
"""Create a signed upload policy for uploading objects.
This method generates and signs a policy document. You can use
`policy documents`_ to allow visitors to a website to upload files to
Google Cloud Storage without giving them direct write access.
For example:
.. literalinclude:: snippets.py
:start-after: [START policy_document]
:end-before: [END policy_document]
.. _policy documents:
https://cloud.google.com/storage/docs/xml-api\
/post-object#policydocument
:type expiration: datetime
:param expiration: Optional expiration in UTC. If not specified, the
policy will expire in 1 hour.
:type conditions: list
:param conditions: A list of conditions as described in the
`policy documents`_ documentation.
:type client: :class:`~google.cloud.storage.client.Client`
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: dict
:returns: A dictionary of (form field name, form field value) of form
fields that should be added to your HTML upload form in order
to attach the signature.
"""
client = self._require_client(client)
credentials = client._base_connection.credentials
_signing.ensure_signed_credentials(credentials)
if expiration is None:
expiration = _NOW() + datetime.timedelta(hours=1)
conditions = conditions + [{"bucket": self.name}]
policy_document = {
"expiration": _datetime_to_rfc3339(expiration),
"conditions": conditions,
}
encoded_policy_document = base64.b64encode(
json.dumps(policy_document).encode("utf-8")
)
signature = base64.b64encode(credentials.sign_bytes(encoded_policy_document))
fields = {
"bucket": self.name,
"GoogleAccessId": credentials.signer_email,
"policy": encoded_policy_document.decode("utf-8"),
"signature": signature.decode("utf-8"),
}
return fields | [
"def",
"generate_upload_policy",
"(",
"self",
",",
"conditions",
",",
"expiration",
"=",
"None",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"credentials",
"=",
"client",
".",
"_base_connection",
".",
"credentials",
"_signing",
".",
"ensure_signed_credentials",
"(",
"credentials",
")",
"if",
"expiration",
"is",
"None",
":",
"expiration",
"=",
"_NOW",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"1",
")",
"conditions",
"=",
"conditions",
"+",
"[",
"{",
"\"bucket\"",
":",
"self",
".",
"name",
"}",
"]",
"policy_document",
"=",
"{",
"\"expiration\"",
":",
"_datetime_to_rfc3339",
"(",
"expiration",
")",
",",
"\"conditions\"",
":",
"conditions",
",",
"}",
"encoded_policy_document",
"=",
"base64",
".",
"b64encode",
"(",
"json",
".",
"dumps",
"(",
"policy_document",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"signature",
"=",
"base64",
".",
"b64encode",
"(",
"credentials",
".",
"sign_bytes",
"(",
"encoded_policy_document",
")",
")",
"fields",
"=",
"{",
"\"bucket\"",
":",
"self",
".",
"name",
",",
"\"GoogleAccessId\"",
":",
"credentials",
".",
"signer_email",
",",
"\"policy\"",
":",
"encoded_policy_document",
".",
"decode",
"(",
"\"utf-8\"",
")",
",",
"\"signature\"",
":",
"signature",
".",
"decode",
"(",
"\"utf-8\"",
")",
",",
"}",
"return",
"fields"
] | Create a signed upload policy for uploading objects.
This method generates and signs a policy document. You can use
`policy documents`_ to allow visitors to a website to upload files to
Google Cloud Storage without giving them direct write access.
For example:
.. literalinclude:: snippets.py
:start-after: [START policy_document]
:end-before: [END policy_document]
.. _policy documents:
https://cloud.google.com/storage/docs/xml-api\
/post-object#policydocument
:type expiration: datetime
:param expiration: Optional expiration in UTC. If not specified, the
policy will expire in 1 hour.
:type conditions: list
:param conditions: A list of conditions as described in the
`policy documents`_ documentation.
:type client: :class:`~google.cloud.storage.client.Client`
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the current bucket.
:rtype: dict
:returns: A dictionary of (form field name, form field value) of form
fields that should be added to your HTML upload form in order
to attach the signature. | [
"Create",
"a",
"signed",
"upload",
"policy",
"for",
"uploading",
"objects",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1882-L1942 |
27,896 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.lock_retention_policy | def lock_retention_policy(self, client=None):
"""Lock the bucket's retention policy.
:raises ValueError:
if the bucket has no metageneration (i.e., new or never reloaded);
if the bucket has no retention policy assigned;
if the bucket's retention policy is already locked.
"""
if "metageneration" not in self._properties:
raise ValueError("Bucket has no retention policy assigned: try 'reload'?")
policy = self._properties.get("retentionPolicy")
if policy is None:
raise ValueError("Bucket has no retention policy assigned: try 'reload'?")
if policy.get("isLocked"):
raise ValueError("Bucket's retention policy is already locked.")
client = self._require_client(client)
query_params = {"ifMetagenerationMatch": self.metageneration}
if self.user_project is not None:
query_params["userProject"] = self.user_project
path = "/b/{}/lockRetentionPolicy".format(self.name)
api_response = client._connection.api_request(
method="POST", path=path, query_params=query_params, _target_object=self
)
self._set_properties(api_response) | python | def lock_retention_policy(self, client=None):
"""Lock the bucket's retention policy.
:raises ValueError:
if the bucket has no metageneration (i.e., new or never reloaded);
if the bucket has no retention policy assigned;
if the bucket's retention policy is already locked.
"""
if "metageneration" not in self._properties:
raise ValueError("Bucket has no retention policy assigned: try 'reload'?")
policy = self._properties.get("retentionPolicy")
if policy is None:
raise ValueError("Bucket has no retention policy assigned: try 'reload'?")
if policy.get("isLocked"):
raise ValueError("Bucket's retention policy is already locked.")
client = self._require_client(client)
query_params = {"ifMetagenerationMatch": self.metageneration}
if self.user_project is not None:
query_params["userProject"] = self.user_project
path = "/b/{}/lockRetentionPolicy".format(self.name)
api_response = client._connection.api_request(
method="POST", path=path, query_params=query_params, _target_object=self
)
self._set_properties(api_response) | [
"def",
"lock_retention_policy",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"if",
"\"metageneration\"",
"not",
"in",
"self",
".",
"_properties",
":",
"raise",
"ValueError",
"(",
"\"Bucket has no retention policy assigned: try 'reload'?\"",
")",
"policy",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"\"retentionPolicy\"",
")",
"if",
"policy",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Bucket has no retention policy assigned: try 'reload'?\"",
")",
"if",
"policy",
".",
"get",
"(",
"\"isLocked\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Bucket's retention policy is already locked.\"",
")",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"query_params",
"=",
"{",
"\"ifMetagenerationMatch\"",
":",
"self",
".",
"metageneration",
"}",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"query_params",
"[",
"\"userProject\"",
"]",
"=",
"self",
".",
"user_project",
"path",
"=",
"\"/b/{}/lockRetentionPolicy\"",
".",
"format",
"(",
"self",
".",
"name",
")",
"api_response",
"=",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"path",
",",
"query_params",
"=",
"query_params",
",",
"_target_object",
"=",
"self",
")",
"self",
".",
"_set_properties",
"(",
"api_response",
")"
] | Lock the bucket's retention policy.
:raises ValueError:
if the bucket has no metageneration (i.e., new or never reloaded);
if the bucket has no retention policy assigned;
if the bucket's retention policy is already locked. | [
"Lock",
"the",
"bucket",
"s",
"retention",
"policy",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1944-L1974 |
27,897 | googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | Bucket.generate_signed_url | def generate_signed_url(
self,
expiration=None,
api_access_endpoint=_API_ACCESS_ENDPOINT,
method="GET",
headers=None,
query_parameters=None,
client=None,
credentials=None,
version=None,
):
"""Generates a signed URL for this bucket.
.. note::
If you are on Google Compute Engine, you can't generate a signed
URL using GCE service account. Follow `Issue 50`_ 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.
.. _Issue 50: https://github.com/GoogleCloudPlatform/\
google-auth-library-python/issues/50
If you have a bucket that you want to allow access to for a set
amount of time, you can use this method to generate a URL that
is only valid within a certain time period.
This is particularly useful if you don't want publicly
accessible buckets, but don't want to require users to explicitly
log in.
: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.
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
: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
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: (Optional) The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:type credentials: :class:`oauth2client.client.OAuth2Credentials` or
:class:`NoneType`
:param credentials: (Optional) The OAuth2 credentials to use to sign
the URL. Defaults to the credentials stored on the
client used.
:type version: str
:param version: (Optional) The version of signed credential to create.
Must be one of 'v2' | 'v4'.
:raises: :exc:`ValueError` when version is invalid.
: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.
"""
if version is None:
version = "v2"
elif version not in ("v2", "v4"):
raise ValueError("'version' must be either 'v2' or 'v4'")
resource = "/{bucket_name}".format(bucket_name=self.name)
if credentials is None:
client = self._require_client(client)
credentials = client._credentials
if version == "v2":
helper = generate_signed_url_v2
else:
helper = generate_signed_url_v4
return helper(
credentials,
resource=resource,
expiration=expiration,
api_access_endpoint=api_access_endpoint,
method=method.upper(),
headers=headers,
query_parameters=query_parameters,
) | python | def generate_signed_url(
self,
expiration=None,
api_access_endpoint=_API_ACCESS_ENDPOINT,
method="GET",
headers=None,
query_parameters=None,
client=None,
credentials=None,
version=None,
):
"""Generates a signed URL for this bucket.
.. note::
If you are on Google Compute Engine, you can't generate a signed
URL using GCE service account. Follow `Issue 50`_ 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.
.. _Issue 50: https://github.com/GoogleCloudPlatform/\
google-auth-library-python/issues/50
If you have a bucket that you want to allow access to for a set
amount of time, you can use this method to generate a URL that
is only valid within a certain time period.
This is particularly useful if you don't want publicly
accessible buckets, but don't want to require users to explicitly
log in.
: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.
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
: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
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: (Optional) The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:type credentials: :class:`oauth2client.client.OAuth2Credentials` or
:class:`NoneType`
:param credentials: (Optional) The OAuth2 credentials to use to sign
the URL. Defaults to the credentials stored on the
client used.
:type version: str
:param version: (Optional) The version of signed credential to create.
Must be one of 'v2' | 'v4'.
:raises: :exc:`ValueError` when version is invalid.
: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.
"""
if version is None:
version = "v2"
elif version not in ("v2", "v4"):
raise ValueError("'version' must be either 'v2' or 'v4'")
resource = "/{bucket_name}".format(bucket_name=self.name)
if credentials is None:
client = self._require_client(client)
credentials = client._credentials
if version == "v2":
helper = generate_signed_url_v2
else:
helper = generate_signed_url_v4
return helper(
credentials,
resource=resource,
expiration=expiration,
api_access_endpoint=api_access_endpoint,
method=method.upper(),
headers=headers,
query_parameters=query_parameters,
) | [
"def",
"generate_signed_url",
"(",
"self",
",",
"expiration",
"=",
"None",
",",
"api_access_endpoint",
"=",
"_API_ACCESS_ENDPOINT",
",",
"method",
"=",
"\"GET\"",
",",
"headers",
"=",
"None",
",",
"query_parameters",
"=",
"None",
",",
"client",
"=",
"None",
",",
"credentials",
"=",
"None",
",",
"version",
"=",
"None",
",",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"\"v2\"",
"elif",
"version",
"not",
"in",
"(",
"\"v2\"",
",",
"\"v4\"",
")",
":",
"raise",
"ValueError",
"(",
"\"'version' must be either 'v2' or 'v4'\"",
")",
"resource",
"=",
"\"/{bucket_name}\"",
".",
"format",
"(",
"bucket_name",
"=",
"self",
".",
"name",
")",
"if",
"credentials",
"is",
"None",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"credentials",
"=",
"client",
".",
"_credentials",
"if",
"version",
"==",
"\"v2\"",
":",
"helper",
"=",
"generate_signed_url_v2",
"else",
":",
"helper",
"=",
"generate_signed_url_v4",
"return",
"helper",
"(",
"credentials",
",",
"resource",
"=",
"resource",
",",
"expiration",
"=",
"expiration",
",",
"api_access_endpoint",
"=",
"api_access_endpoint",
",",
"method",
"=",
"method",
".",
"upper",
"(",
")",
",",
"headers",
"=",
"headers",
",",
"query_parameters",
"=",
"query_parameters",
",",
")"
] | Generates a signed URL for this bucket.
.. note::
If you are on Google Compute Engine, you can't generate a signed
URL using GCE service account. Follow `Issue 50`_ 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.
.. _Issue 50: https://github.com/GoogleCloudPlatform/\
google-auth-library-python/issues/50
If you have a bucket that you want to allow access to for a set
amount of time, you can use this method to generate a URL that
is only valid within a certain time period.
This is particularly useful if you don't want publicly
accessible buckets, but don't want to require users to explicitly
log in.
: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.
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
: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
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: (Optional) The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:type credentials: :class:`oauth2client.client.OAuth2Credentials` or
:class:`NoneType`
:param credentials: (Optional) The OAuth2 credentials to use to sign
the URL. Defaults to the credentials stored on the
client used.
:type version: str
:param version: (Optional) The version of signed credential to create.
Must be one of 'v2' | 'v4'.
:raises: :exc:`ValueError` when version is invalid.
: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. | [
"Generates",
"a",
"signed",
"URL",
"for",
"this",
"bucket",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1976-L2080 |
27,898 | googleapis/google-cloud-python | api_core/google/api_core/datetime_helpers.py | to_microseconds | def to_microseconds(value):
"""Convert a datetime to microseconds since the unix epoch.
Args:
value (datetime.datetime): The datetime to covert.
Returns:
int: Microseconds since the unix epoch.
"""
if not value.tzinfo:
value = value.replace(tzinfo=pytz.utc)
# Regardless of what timezone is on the value, convert it to UTC.
value = value.astimezone(pytz.utc)
# Convert the datetime to a microsecond timestamp.
return int(calendar.timegm(value.timetuple()) * 1e6) + value.microsecond | python | def to_microseconds(value):
"""Convert a datetime to microseconds since the unix epoch.
Args:
value (datetime.datetime): The datetime to covert.
Returns:
int: Microseconds since the unix epoch.
"""
if not value.tzinfo:
value = value.replace(tzinfo=pytz.utc)
# Regardless of what timezone is on the value, convert it to UTC.
value = value.astimezone(pytz.utc)
# Convert the datetime to a microsecond timestamp.
return int(calendar.timegm(value.timetuple()) * 1e6) + value.microsecond | [
"def",
"to_microseconds",
"(",
"value",
")",
":",
"if",
"not",
"value",
".",
"tzinfo",
":",
"value",
"=",
"value",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"# Regardless of what timezone is on the value, convert it to UTC.",
"value",
"=",
"value",
".",
"astimezone",
"(",
"pytz",
".",
"utc",
")",
"# Convert the datetime to a microsecond timestamp.",
"return",
"int",
"(",
"calendar",
".",
"timegm",
"(",
"value",
".",
"timetuple",
"(",
")",
")",
"*",
"1e6",
")",
"+",
"value",
".",
"microsecond"
] | Convert a datetime to microseconds since the unix epoch.
Args:
value (datetime.datetime): The datetime to covert.
Returns:
int: Microseconds since the unix epoch. | [
"Convert",
"a",
"datetime",
"to",
"microseconds",
"since",
"the",
"unix",
"epoch",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/datetime_helpers.py#L76-L90 |
27,899 | googleapis/google-cloud-python | api_core/google/api_core/datetime_helpers.py | from_rfc3339 | def from_rfc3339(value):
"""Convert a microsecond-precision timestamp to datetime.
Args:
value (str): The RFC3339 string to convert.
Returns:
datetime.datetime: The datetime object equivalent to the timestamp in
UTC.
"""
return datetime.datetime.strptime(value, _RFC3339_MICROS).replace(tzinfo=pytz.utc) | python | def from_rfc3339(value):
"""Convert a microsecond-precision timestamp to datetime.
Args:
value (str): The RFC3339 string to convert.
Returns:
datetime.datetime: The datetime object equivalent to the timestamp in
UTC.
"""
return datetime.datetime.strptime(value, _RFC3339_MICROS).replace(tzinfo=pytz.utc) | [
"def",
"from_rfc3339",
"(",
"value",
")",
":",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"value",
",",
"_RFC3339_MICROS",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")"
] | Convert a microsecond-precision timestamp to datetime.
Args:
value (str): The RFC3339 string to convert.
Returns:
datetime.datetime: The datetime object equivalent to the timestamp in
UTC. | [
"Convert",
"a",
"microsecond",
"-",
"precision",
"timestamp",
"to",
"datetime",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/datetime_helpers.py#L117-L127 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.