id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
28,000 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/table.py | _item_to_row | def _item_to_row(iterator, resource):
"""Convert a JSON row to the native object.
.. note::
This assumes that the ``schema`` attribute has been
added to the iterator after being created, which
should be done by the caller.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type resource: dict
:param resource: An item to be converted to a row.
:rtype: :class:`~google.cloud.bigquery.table.Row`
:returns: The next row in the page.
"""
return Row(
_helpers._row_tuple_from_json(resource, iterator.schema),
iterator._field_to_index,
) | python | def _item_to_row(iterator, resource):
"""Convert a JSON row to the native object.
.. note::
This assumes that the ``schema`` attribute has been
added to the iterator after being created, which
should be done by the caller.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type resource: dict
:param resource: An item to be converted to a row.
:rtype: :class:`~google.cloud.bigquery.table.Row`
:returns: The next row in the page.
"""
return Row(
_helpers._row_tuple_from_json(resource, iterator.schema),
iterator._field_to_index,
) | [
"def",
"_item_to_row",
"(",
"iterator",
",",
"resource",
")",
":",
"return",
"Row",
"(",
"_helpers",
".",
"_row_tuple_from_json",
"(",
"resource",
",",
"iterator",
".",
"schema",
")",
",",
"iterator",
".",
"_field_to_index",
",",
")"
] | Convert a JSON row to the native object.
.. note::
This assumes that the ``schema`` attribute has been
added to the iterator after being created, which
should be done by the caller.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type resource: dict
:param resource: An item to be converted to a row.
:rtype: :class:`~google.cloud.bigquery.table.Row`
:returns: The next row in the page. | [
"Convert",
"a",
"JSON",
"row",
"to",
"the",
"native",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L1882-L1903 |
28,001 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/table.py | _table_arg_to_table_ref | def _table_arg_to_table_ref(value, default_project=None):
"""Helper to convert a string or Table to TableReference.
This function keeps TableReference and other kinds of objects unchanged.
"""
if isinstance(value, six.string_types):
value = TableReference.from_string(value, default_project=default_project)
if isinstance(value, (Table, TableListItem)):
value = value.reference
return value | python | def _table_arg_to_table_ref(value, default_project=None):
"""Helper to convert a string or Table to TableReference.
This function keeps TableReference and other kinds of objects unchanged.
"""
if isinstance(value, six.string_types):
value = TableReference.from_string(value, default_project=default_project)
if isinstance(value, (Table, TableListItem)):
value = value.reference
return value | [
"def",
"_table_arg_to_table_ref",
"(",
"value",
",",
"default_project",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"value",
"=",
"TableReference",
".",
"from_string",
"(",
"value",
",",
"default_project",
"=",
"default_project",
")",
"if",
"isinstance",
"(",
"value",
",",
"(",
"Table",
",",
"TableListItem",
")",
")",
":",
"value",
"=",
"value",
".",
"reference",
"return",
"value"
] | Helper to convert a string or Table to TableReference.
This function keeps TableReference and other kinds of objects unchanged. | [
"Helper",
"to",
"convert",
"a",
"string",
"or",
"Table",
"to",
"TableReference",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L1928-L1937 |
28,002 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/table.py | _table_arg_to_table | def _table_arg_to_table(value, default_project=None):
"""Helper to convert a string or TableReference to a Table.
This function keeps Table and other kinds of objects unchanged.
"""
if isinstance(value, six.string_types):
value = TableReference.from_string(value, default_project=default_project)
if isinstance(value, TableReference):
value = Table(value)
if isinstance(value, TableListItem):
newvalue = Table(value.reference)
newvalue._properties = value._properties
value = newvalue
return value | python | def _table_arg_to_table(value, default_project=None):
"""Helper to convert a string or TableReference to a Table.
This function keeps Table and other kinds of objects unchanged.
"""
if isinstance(value, six.string_types):
value = TableReference.from_string(value, default_project=default_project)
if isinstance(value, TableReference):
value = Table(value)
if isinstance(value, TableListItem):
newvalue = Table(value.reference)
newvalue._properties = value._properties
value = newvalue
return value | [
"def",
"_table_arg_to_table",
"(",
"value",
",",
"default_project",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"value",
"=",
"TableReference",
".",
"from_string",
"(",
"value",
",",
"default_project",
"=",
"default_project",
")",
"if",
"isinstance",
"(",
"value",
",",
"TableReference",
")",
":",
"value",
"=",
"Table",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"TableListItem",
")",
":",
"newvalue",
"=",
"Table",
"(",
"value",
".",
"reference",
")",
"newvalue",
".",
"_properties",
"=",
"value",
".",
"_properties",
"value",
"=",
"newvalue",
"return",
"value"
] | Helper to convert a string or TableReference to a Table.
This function keeps Table and other kinds of objects unchanged. | [
"Helper",
"to",
"convert",
"a",
"string",
"or",
"TableReference",
"to",
"a",
"Table",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L1940-L1954 |
28,003 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/table.py | TableReference.from_string | def from_string(cls, table_id, default_project=None):
"""Construct a table reference from table ID string.
Args:
table_id (str):
A table ID in standard SQL format. If ``default_project``
is not specified, this must included a project ID, dataset
ID, and table ID, each separated by ``.``.
default_project (str):
Optional. The project ID to use when ``table_id`` does not
include a project ID.
Returns:
TableReference: Table reference parsed from ``table_id``.
Examples:
>>> TableReference.from_string('my-project.mydataset.mytable')
TableRef...(DatasetRef...('my-project', 'mydataset'), 'mytable')
Raises:
ValueError:
If ``table_id`` is not a fully-qualified table ID in
standard SQL format.
"""
from google.cloud.bigquery.dataset import DatasetReference
(
output_project_id,
output_dataset_id,
output_table_id,
) = _helpers._parse_3_part_id(
table_id, default_project=default_project, property_name="table_id"
)
return cls(
DatasetReference(output_project_id, output_dataset_id), output_table_id
) | python | def from_string(cls, table_id, default_project=None):
"""Construct a table reference from table ID string.
Args:
table_id (str):
A table ID in standard SQL format. If ``default_project``
is not specified, this must included a project ID, dataset
ID, and table ID, each separated by ``.``.
default_project (str):
Optional. The project ID to use when ``table_id`` does not
include a project ID.
Returns:
TableReference: Table reference parsed from ``table_id``.
Examples:
>>> TableReference.from_string('my-project.mydataset.mytable')
TableRef...(DatasetRef...('my-project', 'mydataset'), 'mytable')
Raises:
ValueError:
If ``table_id`` is not a fully-qualified table ID in
standard SQL format.
"""
from google.cloud.bigquery.dataset import DatasetReference
(
output_project_id,
output_dataset_id,
output_table_id,
) = _helpers._parse_3_part_id(
table_id, default_project=default_project, property_name="table_id"
)
return cls(
DatasetReference(output_project_id, output_dataset_id), output_table_id
) | [
"def",
"from_string",
"(",
"cls",
",",
"table_id",
",",
"default_project",
"=",
"None",
")",
":",
"from",
"google",
".",
"cloud",
".",
"bigquery",
".",
"dataset",
"import",
"DatasetReference",
"(",
"output_project_id",
",",
"output_dataset_id",
",",
"output_table_id",
",",
")",
"=",
"_helpers",
".",
"_parse_3_part_id",
"(",
"table_id",
",",
"default_project",
"=",
"default_project",
",",
"property_name",
"=",
"\"table_id\"",
")",
"return",
"cls",
"(",
"DatasetReference",
"(",
"output_project_id",
",",
"output_dataset_id",
")",
",",
"output_table_id",
")"
] | Construct a table reference from table ID string.
Args:
table_id (str):
A table ID in standard SQL format. If ``default_project``
is not specified, this must included a project ID, dataset
ID, and table ID, each separated by ``.``.
default_project (str):
Optional. The project ID to use when ``table_id`` does not
include a project ID.
Returns:
TableReference: Table reference parsed from ``table_id``.
Examples:
>>> TableReference.from_string('my-project.mydataset.mytable')
TableRef...(DatasetRef...('my-project', 'mydataset'), 'mytable')
Raises:
ValueError:
If ``table_id`` is not a fully-qualified table ID in
standard SQL format. | [
"Construct",
"a",
"table",
"reference",
"from",
"table",
"ID",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L224-L260 |
28,004 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/table.py | TableReference.to_bqstorage | def to_bqstorage(self):
"""Construct a BigQuery Storage API representation of this table.
Install the ``google-cloud-bigquery-storage`` package to use this
feature.
If the ``table_id`` contains a partition identifier (e.g.
``my_table$201812``) or a snapshot identifier (e.g.
``mytable@1234567890``), it is ignored. Use
:class:`google.cloud.bigquery_storage_v1beta1.types.TableReadOptions`
to filter rows by partition. Use
:class:`google.cloud.bigquery_storage_v1beta1.types.TableModifiers`
to select a specific snapshot to read from.
Returns:
google.cloud.bigquery_storage_v1beta1.types.TableReference:
A reference to this table in the BigQuery Storage API.
Raises:
ValueError:
If the :mod:`google.cloud.bigquery_storage_v1beta1` module
cannot be imported.
"""
if bigquery_storage_v1beta1 is None:
raise ValueError(_NO_BQSTORAGE_ERROR)
table_ref = bigquery_storage_v1beta1.types.TableReference()
table_ref.project_id = self._project
table_ref.dataset_id = self._dataset_id
table_id = self._table_id
if "@" in table_id:
table_id = table_id.split("@")[0]
if "$" in table_id:
table_id = table_id.split("$")[0]
table_ref.table_id = table_id
return table_ref | python | def to_bqstorage(self):
"""Construct a BigQuery Storage API representation of this table.
Install the ``google-cloud-bigquery-storage`` package to use this
feature.
If the ``table_id`` contains a partition identifier (e.g.
``my_table$201812``) or a snapshot identifier (e.g.
``mytable@1234567890``), it is ignored. Use
:class:`google.cloud.bigquery_storage_v1beta1.types.TableReadOptions`
to filter rows by partition. Use
:class:`google.cloud.bigquery_storage_v1beta1.types.TableModifiers`
to select a specific snapshot to read from.
Returns:
google.cloud.bigquery_storage_v1beta1.types.TableReference:
A reference to this table in the BigQuery Storage API.
Raises:
ValueError:
If the :mod:`google.cloud.bigquery_storage_v1beta1` module
cannot be imported.
"""
if bigquery_storage_v1beta1 is None:
raise ValueError(_NO_BQSTORAGE_ERROR)
table_ref = bigquery_storage_v1beta1.types.TableReference()
table_ref.project_id = self._project
table_ref.dataset_id = self._dataset_id
table_id = self._table_id
if "@" in table_id:
table_id = table_id.split("@")[0]
if "$" in table_id:
table_id = table_id.split("$")[0]
table_ref.table_id = table_id
return table_ref | [
"def",
"to_bqstorage",
"(",
"self",
")",
":",
"if",
"bigquery_storage_v1beta1",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_NO_BQSTORAGE_ERROR",
")",
"table_ref",
"=",
"bigquery_storage_v1beta1",
".",
"types",
".",
"TableReference",
"(",
")",
"table_ref",
".",
"project_id",
"=",
"self",
".",
"_project",
"table_ref",
".",
"dataset_id",
"=",
"self",
".",
"_dataset_id",
"table_id",
"=",
"self",
".",
"_table_id",
"if",
"\"@\"",
"in",
"table_id",
":",
"table_id",
"=",
"table_id",
".",
"split",
"(",
"\"@\"",
")",
"[",
"0",
"]",
"if",
"\"$\"",
"in",
"table_id",
":",
"table_id",
"=",
"table_id",
".",
"split",
"(",
"\"$\"",
")",
"[",
"0",
"]",
"table_ref",
".",
"table_id",
"=",
"table_id",
"return",
"table_ref"
] | Construct a BigQuery Storage API representation of this table.
Install the ``google-cloud-bigquery-storage`` package to use this
feature.
If the ``table_id`` contains a partition identifier (e.g.
``my_table$201812``) or a snapshot identifier (e.g.
``mytable@1234567890``), it is ignored. Use
:class:`google.cloud.bigquery_storage_v1beta1.types.TableReadOptions`
to filter rows by partition. Use
:class:`google.cloud.bigquery_storage_v1beta1.types.TableModifiers`
to select a specific snapshot to read from.
Returns:
google.cloud.bigquery_storage_v1beta1.types.TableReference:
A reference to this table in the BigQuery Storage API.
Raises:
ValueError:
If the :mod:`google.cloud.bigquery_storage_v1beta1` module
cannot be imported. | [
"Construct",
"a",
"BigQuery",
"Storage",
"API",
"representation",
"of",
"this",
"table",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L293-L332 |
28,005 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/table.py | Row.get | def get(self, key, default=None):
"""Return a value for key, with a default value if it does not exist.
Args:
key (str): The key of the column to access
default (object):
The default value to use if the key does not exist. (Defaults
to :data:`None`.)
Returns:
object:
The value associated with the provided key, or a default value.
Examples:
When the key exists, the value associated with it is returned.
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('x')
'a'
The default value is :data:`None` when the key does not exist.
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z')
None
The default value can be overrided with the ``default`` parameter.
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z', '')
''
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z', default = '')
''
"""
index = self._xxx_field_to_index.get(key)
if index is None:
return default
return self._xxx_values[index] | python | def get(self, key, default=None):
"""Return a value for key, with a default value if it does not exist.
Args:
key (str): The key of the column to access
default (object):
The default value to use if the key does not exist. (Defaults
to :data:`None`.)
Returns:
object:
The value associated with the provided key, or a default value.
Examples:
When the key exists, the value associated with it is returned.
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('x')
'a'
The default value is :data:`None` when the key does not exist.
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z')
None
The default value can be overrided with the ``default`` parameter.
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z', '')
''
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z', default = '')
''
"""
index = self._xxx_field_to_index.get(key)
if index is None:
return default
return self._xxx_values[index] | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"index",
"=",
"self",
".",
"_xxx_field_to_index",
".",
"get",
"(",
"key",
")",
"if",
"index",
"is",
"None",
":",
"return",
"default",
"return",
"self",
".",
"_xxx_values",
"[",
"index",
"]"
] | Return a value for key, with a default value if it does not exist.
Args:
key (str): The key of the column to access
default (object):
The default value to use if the key does not exist. (Defaults
to :data:`None`.)
Returns:
object:
The value associated with the provided key, or a default value.
Examples:
When the key exists, the value associated with it is returned.
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('x')
'a'
The default value is :data:`None` when the key does not exist.
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z')
None
The default value can be overrided with the ``default`` parameter.
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z', '')
''
>>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z', default = '')
'' | [
"Return",
"a",
"value",
"for",
"key",
"with",
"a",
"default",
"value",
"if",
"it",
"does",
"not",
"exist",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L1213-L1248 |
28,006 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/table.py | RowIterator._get_progress_bar | def _get_progress_bar(self, progress_bar_type):
"""Construct a tqdm progress bar object, if tqdm is installed."""
if tqdm is None:
if progress_bar_type is not None:
warnings.warn(_NO_TQDM_ERROR, UserWarning, stacklevel=3)
return None
description = "Downloading"
unit = "rows"
try:
if progress_bar_type == "tqdm":
return tqdm.tqdm(desc=description, total=self.total_rows, unit=unit)
elif progress_bar_type == "tqdm_notebook":
return tqdm.tqdm_notebook(
desc=description, total=self.total_rows, unit=unit
)
elif progress_bar_type == "tqdm_gui":
return tqdm.tqdm_gui(desc=description, total=self.total_rows, unit=unit)
except (KeyError, TypeError):
# Protect ourselves from any tqdm errors. In case of
# unexpected tqdm behavior, just fall back to showing
# no progress bar.
warnings.warn(_NO_TQDM_ERROR, UserWarning, stacklevel=3)
return None | python | def _get_progress_bar(self, progress_bar_type):
"""Construct a tqdm progress bar object, if tqdm is installed."""
if tqdm is None:
if progress_bar_type is not None:
warnings.warn(_NO_TQDM_ERROR, UserWarning, stacklevel=3)
return None
description = "Downloading"
unit = "rows"
try:
if progress_bar_type == "tqdm":
return tqdm.tqdm(desc=description, total=self.total_rows, unit=unit)
elif progress_bar_type == "tqdm_notebook":
return tqdm.tqdm_notebook(
desc=description, total=self.total_rows, unit=unit
)
elif progress_bar_type == "tqdm_gui":
return tqdm.tqdm_gui(desc=description, total=self.total_rows, unit=unit)
except (KeyError, TypeError):
# Protect ourselves from any tqdm errors. In case of
# unexpected tqdm behavior, just fall back to showing
# no progress bar.
warnings.warn(_NO_TQDM_ERROR, UserWarning, stacklevel=3)
return None | [
"def",
"_get_progress_bar",
"(",
"self",
",",
"progress_bar_type",
")",
":",
"if",
"tqdm",
"is",
"None",
":",
"if",
"progress_bar_type",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"_NO_TQDM_ERROR",
",",
"UserWarning",
",",
"stacklevel",
"=",
"3",
")",
"return",
"None",
"description",
"=",
"\"Downloading\"",
"unit",
"=",
"\"rows\"",
"try",
":",
"if",
"progress_bar_type",
"==",
"\"tqdm\"",
":",
"return",
"tqdm",
".",
"tqdm",
"(",
"desc",
"=",
"description",
",",
"total",
"=",
"self",
".",
"total_rows",
",",
"unit",
"=",
"unit",
")",
"elif",
"progress_bar_type",
"==",
"\"tqdm_notebook\"",
":",
"return",
"tqdm",
".",
"tqdm_notebook",
"(",
"desc",
"=",
"description",
",",
"total",
"=",
"self",
".",
"total_rows",
",",
"unit",
"=",
"unit",
")",
"elif",
"progress_bar_type",
"==",
"\"tqdm_gui\"",
":",
"return",
"tqdm",
".",
"tqdm_gui",
"(",
"desc",
"=",
"description",
",",
"total",
"=",
"self",
".",
"total_rows",
",",
"unit",
"=",
"unit",
")",
"except",
"(",
"KeyError",
",",
"TypeError",
")",
":",
"# Protect ourselves from any tqdm errors. In case of",
"# unexpected tqdm behavior, just fall back to showing",
"# no progress bar.",
"warnings",
".",
"warn",
"(",
"_NO_TQDM_ERROR",
",",
"UserWarning",
",",
"stacklevel",
"=",
"3",
")",
"return",
"None"
] | Construct a tqdm progress bar object, if tqdm is installed. | [
"Construct",
"a",
"tqdm",
"progress",
"bar",
"object",
"if",
"tqdm",
"is",
"installed",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L1582-L1606 |
28,007 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/table.py | RowIterator.to_dataframe | def to_dataframe(self, bqstorage_client=None, dtypes=None, progress_bar_type=None):
"""Create a pandas DataFrame by loading all pages of a query.
Args:
bqstorage_client ( \
google.cloud.bigquery_storage_v1beta1.BigQueryStorageClient \
):
**Beta 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. When a problem
is encountered reading a table, the tabledata.list method
from the BigQuery API is used, instead.
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.
Possible values of ``progress_bar_type`` include:
``None``
No progress bar.
``'tqdm'``
Use the :func:`tqdm.tqdm` function to print a progress bar
to :data:`sys.stderr`.
``'tqdm_notebook'``
Use the :func:`tqdm.tqdm_notebook` function to display a
progress bar as a Jupyter notebook widget.
``'tqdm_gui'``
Use the :func:`tqdm.tqdm_gui` function to display a
progress bar as a graphical dialog box.
..versionadded:: 1.11.0
Returns:
pandas.DataFrame:
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 :mod:`pandas` library cannot be imported, or the
:mod:`google.cloud.bigquery_storage_v1beta1` module is
required but cannot be imported.
"""
if pandas is None:
raise ValueError(_NO_PANDAS_ERROR)
if dtypes is None:
dtypes = {}
progress_bar = self._get_progress_bar(progress_bar_type)
if bqstorage_client is not None:
try:
return self._to_dataframe_bqstorage(
bqstorage_client, dtypes, progress_bar=progress_bar
)
except google.api_core.exceptions.Forbidden:
# Don't hide errors such as insufficient permissions to create
# a read session, or the API is not enabled. Both of those are
# clearly problems if the developer has explicitly asked for
# BigQuery Storage API support.
raise
except google.api_core.exceptions.GoogleAPICallError:
# There is a known issue with reading from small anonymous
# query results tables, so some errors are expected. Rather
# than throw those errors, try reading the DataFrame again, but
# with the tabledata.list API.
pass
return self._to_dataframe_tabledata_list(dtypes, progress_bar=progress_bar) | python | def to_dataframe(self, bqstorage_client=None, dtypes=None, progress_bar_type=None):
"""Create a pandas DataFrame by loading all pages of a query.
Args:
bqstorage_client ( \
google.cloud.bigquery_storage_v1beta1.BigQueryStorageClient \
):
**Beta 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. When a problem
is encountered reading a table, the tabledata.list method
from the BigQuery API is used, instead.
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.
Possible values of ``progress_bar_type`` include:
``None``
No progress bar.
``'tqdm'``
Use the :func:`tqdm.tqdm` function to print a progress bar
to :data:`sys.stderr`.
``'tqdm_notebook'``
Use the :func:`tqdm.tqdm_notebook` function to display a
progress bar as a Jupyter notebook widget.
``'tqdm_gui'``
Use the :func:`tqdm.tqdm_gui` function to display a
progress bar as a graphical dialog box.
..versionadded:: 1.11.0
Returns:
pandas.DataFrame:
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 :mod:`pandas` library cannot be imported, or the
:mod:`google.cloud.bigquery_storage_v1beta1` module is
required but cannot be imported.
"""
if pandas is None:
raise ValueError(_NO_PANDAS_ERROR)
if dtypes is None:
dtypes = {}
progress_bar = self._get_progress_bar(progress_bar_type)
if bqstorage_client is not None:
try:
return self._to_dataframe_bqstorage(
bqstorage_client, dtypes, progress_bar=progress_bar
)
except google.api_core.exceptions.Forbidden:
# Don't hide errors such as insufficient permissions to create
# a read session, or the API is not enabled. Both of those are
# clearly problems if the developer has explicitly asked for
# BigQuery Storage API support.
raise
except google.api_core.exceptions.GoogleAPICallError:
# There is a known issue with reading from small anonymous
# query results tables, so some errors are expected. Rather
# than throw those errors, try reading the DataFrame again, but
# with the tabledata.list API.
pass
return self._to_dataframe_tabledata_list(dtypes, progress_bar=progress_bar) | [
"def",
"to_dataframe",
"(",
"self",
",",
"bqstorage_client",
"=",
"None",
",",
"dtypes",
"=",
"None",
",",
"progress_bar_type",
"=",
"None",
")",
":",
"if",
"pandas",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_NO_PANDAS_ERROR",
")",
"if",
"dtypes",
"is",
"None",
":",
"dtypes",
"=",
"{",
"}",
"progress_bar",
"=",
"self",
".",
"_get_progress_bar",
"(",
"progress_bar_type",
")",
"if",
"bqstorage_client",
"is",
"not",
"None",
":",
"try",
":",
"return",
"self",
".",
"_to_dataframe_bqstorage",
"(",
"bqstorage_client",
",",
"dtypes",
",",
"progress_bar",
"=",
"progress_bar",
")",
"except",
"google",
".",
"api_core",
".",
"exceptions",
".",
"Forbidden",
":",
"# Don't hide errors such as insufficient permissions to create",
"# a read session, or the API is not enabled. Both of those are",
"# clearly problems if the developer has explicitly asked for",
"# BigQuery Storage API support.",
"raise",
"except",
"google",
".",
"api_core",
".",
"exceptions",
".",
"GoogleAPICallError",
":",
"# There is a known issue with reading from small anonymous",
"# query results tables, so some errors are expected. Rather",
"# than throw those errors, try reading the DataFrame again, but",
"# with the tabledata.list API.",
"pass",
"return",
"self",
".",
"_to_dataframe_tabledata_list",
"(",
"dtypes",
",",
"progress_bar",
"=",
"progress_bar",
")"
] | Create a pandas DataFrame by loading all pages of a query.
Args:
bqstorage_client ( \
google.cloud.bigquery_storage_v1beta1.BigQueryStorageClient \
):
**Beta 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. When a problem
is encountered reading a table, the tabledata.list method
from the BigQuery API is used, instead.
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.
Possible values of ``progress_bar_type`` include:
``None``
No progress bar.
``'tqdm'``
Use the :func:`tqdm.tqdm` function to print a progress bar
to :data:`sys.stderr`.
``'tqdm_notebook'``
Use the :func:`tqdm.tqdm_notebook` function to display a
progress bar as a Jupyter notebook widget.
``'tqdm_gui'``
Use the :func:`tqdm.tqdm_gui` function to display a
progress bar as a graphical dialog box.
..versionadded:: 1.11.0
Returns:
pandas.DataFrame:
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 :mod:`pandas` library cannot be imported, or the
:mod:`google.cloud.bigquery_storage_v1beta1` module is
required but cannot be imported. | [
"Create",
"a",
"pandas",
"DataFrame",
"by",
"loading",
"all",
"pages",
"of",
"a",
"query",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L1608-L1695 |
28,008 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/table.py | _EmptyRowIterator.to_dataframe | def to_dataframe(self, bqstorage_client=None, dtypes=None, progress_bar_type=None):
"""Create an empty dataframe.
Args:
bqstorage_client (Any):
Ignored. Added for compatibility with RowIterator.
dtypes (Any):
Ignored. Added for compatibility with RowIterator.
progress_bar_type (Any):
Ignored. Added for compatibility with RowIterator.
Returns:
pandas.DataFrame:
An empty :class:`~pandas.DataFrame`.
"""
if pandas is None:
raise ValueError(_NO_PANDAS_ERROR)
return pandas.DataFrame() | python | def to_dataframe(self, bqstorage_client=None, dtypes=None, progress_bar_type=None):
"""Create an empty dataframe.
Args:
bqstorage_client (Any):
Ignored. Added for compatibility with RowIterator.
dtypes (Any):
Ignored. Added for compatibility with RowIterator.
progress_bar_type (Any):
Ignored. Added for compatibility with RowIterator.
Returns:
pandas.DataFrame:
An empty :class:`~pandas.DataFrame`.
"""
if pandas is None:
raise ValueError(_NO_PANDAS_ERROR)
return pandas.DataFrame() | [
"def",
"to_dataframe",
"(",
"self",
",",
"bqstorage_client",
"=",
"None",
",",
"dtypes",
"=",
"None",
",",
"progress_bar_type",
"=",
"None",
")",
":",
"if",
"pandas",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_NO_PANDAS_ERROR",
")",
"return",
"pandas",
".",
"DataFrame",
"(",
")"
] | Create an empty dataframe.
Args:
bqstorage_client (Any):
Ignored. Added for compatibility with RowIterator.
dtypes (Any):
Ignored. Added for compatibility with RowIterator.
progress_bar_type (Any):
Ignored. Added for compatibility with RowIterator.
Returns:
pandas.DataFrame:
An empty :class:`~pandas.DataFrame`. | [
"Create",
"an",
"empty",
"dataframe",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L1710-L1727 |
28,009 | googleapis/google-cloud-python | storage/google/cloud/storage/batch.py | Batch._prepare_batch_request | def _prepare_batch_request(self):
"""Prepares headers and body for a batch request.
:rtype: tuple (dict, str)
:returns: The pair of headers and body of the batch request to be sent.
:raises: :class:`ValueError` if no requests have been deferred.
"""
if len(self._requests) == 0:
raise ValueError("No deferred requests")
multi = MIMEMultipart()
for method, uri, headers, body in self._requests:
subrequest = MIMEApplicationHTTP(method, uri, headers, body)
multi.attach(subrequest)
# The `email` package expects to deal with "native" strings
if six.PY3: # pragma: NO COVER Python3
buf = io.StringIO()
else:
buf = io.BytesIO()
generator = Generator(buf, False, 0)
generator.flatten(multi)
payload = buf.getvalue()
# Strip off redundant header text
_, body = payload.split("\n\n", 1)
return dict(multi._headers), body | python | def _prepare_batch_request(self):
"""Prepares headers and body for a batch request.
:rtype: tuple (dict, str)
:returns: The pair of headers and body of the batch request to be sent.
:raises: :class:`ValueError` if no requests have been deferred.
"""
if len(self._requests) == 0:
raise ValueError("No deferred requests")
multi = MIMEMultipart()
for method, uri, headers, body in self._requests:
subrequest = MIMEApplicationHTTP(method, uri, headers, body)
multi.attach(subrequest)
# The `email` package expects to deal with "native" strings
if six.PY3: # pragma: NO COVER Python3
buf = io.StringIO()
else:
buf = io.BytesIO()
generator = Generator(buf, False, 0)
generator.flatten(multi)
payload = buf.getvalue()
# Strip off redundant header text
_, body = payload.split("\n\n", 1)
return dict(multi._headers), body | [
"def",
"_prepare_batch_request",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_requests",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"No deferred requests\"",
")",
"multi",
"=",
"MIMEMultipart",
"(",
")",
"for",
"method",
",",
"uri",
",",
"headers",
",",
"body",
"in",
"self",
".",
"_requests",
":",
"subrequest",
"=",
"MIMEApplicationHTTP",
"(",
"method",
",",
"uri",
",",
"headers",
",",
"body",
")",
"multi",
".",
"attach",
"(",
"subrequest",
")",
"# The `email` package expects to deal with \"native\" strings",
"if",
"six",
".",
"PY3",
":",
"# pragma: NO COVER Python3",
"buf",
"=",
"io",
".",
"StringIO",
"(",
")",
"else",
":",
"buf",
"=",
"io",
".",
"BytesIO",
"(",
")",
"generator",
"=",
"Generator",
"(",
"buf",
",",
"False",
",",
"0",
")",
"generator",
".",
"flatten",
"(",
"multi",
")",
"payload",
"=",
"buf",
".",
"getvalue",
"(",
")",
"# Strip off redundant header text",
"_",
",",
"body",
"=",
"payload",
".",
"split",
"(",
"\"\\n\\n\"",
",",
"1",
")",
"return",
"dict",
"(",
"multi",
".",
"_headers",
")",
",",
"body"
] | Prepares headers and body for a batch request.
:rtype: tuple (dict, str)
:returns: The pair of headers and body of the batch request to be sent.
:raises: :class:`ValueError` if no requests have been deferred. | [
"Prepares",
"headers",
"and",
"body",
"for",
"a",
"batch",
"request",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/batch.py#L191-L218 |
28,010 | googleapis/google-cloud-python | storage/google/cloud/storage/batch.py | Batch._finish_futures | def _finish_futures(self, responses):
"""Apply all the batch responses to the futures created.
:type responses: list of (headers, payload) tuples.
:param responses: List of headers and payloads from each response in
the batch.
:raises: :class:`ValueError` if no requests have been deferred.
"""
# If a bad status occurs, we track it, but don't raise an exception
# until all futures have been populated.
exception_args = None
if len(self._target_objects) != len(responses):
raise ValueError("Expected a response for every request.")
for target_object, subresponse in zip(self._target_objects, responses):
if not 200 <= subresponse.status_code < 300:
exception_args = exception_args or subresponse
elif target_object is not None:
try:
target_object._properties = subresponse.json()
except ValueError:
target_object._properties = subresponse.content
if exception_args is not None:
raise exceptions.from_http_response(exception_args) | python | def _finish_futures(self, responses):
"""Apply all the batch responses to the futures created.
:type responses: list of (headers, payload) tuples.
:param responses: List of headers and payloads from each response in
the batch.
:raises: :class:`ValueError` if no requests have been deferred.
"""
# If a bad status occurs, we track it, but don't raise an exception
# until all futures have been populated.
exception_args = None
if len(self._target_objects) != len(responses):
raise ValueError("Expected a response for every request.")
for target_object, subresponse in zip(self._target_objects, responses):
if not 200 <= subresponse.status_code < 300:
exception_args = exception_args or subresponse
elif target_object is not None:
try:
target_object._properties = subresponse.json()
except ValueError:
target_object._properties = subresponse.content
if exception_args is not None:
raise exceptions.from_http_response(exception_args) | [
"def",
"_finish_futures",
"(",
"self",
",",
"responses",
")",
":",
"# If a bad status occurs, we track it, but don't raise an exception",
"# until all futures have been populated.",
"exception_args",
"=",
"None",
"if",
"len",
"(",
"self",
".",
"_target_objects",
")",
"!=",
"len",
"(",
"responses",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected a response for every request.\"",
")",
"for",
"target_object",
",",
"subresponse",
"in",
"zip",
"(",
"self",
".",
"_target_objects",
",",
"responses",
")",
":",
"if",
"not",
"200",
"<=",
"subresponse",
".",
"status_code",
"<",
"300",
":",
"exception_args",
"=",
"exception_args",
"or",
"subresponse",
"elif",
"target_object",
"is",
"not",
"None",
":",
"try",
":",
"target_object",
".",
"_properties",
"=",
"subresponse",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"target_object",
".",
"_properties",
"=",
"subresponse",
".",
"content",
"if",
"exception_args",
"is",
"not",
"None",
":",
"raise",
"exceptions",
".",
"from_http_response",
"(",
"exception_args",
")"
] | Apply all the batch responses to the futures created.
:type responses: list of (headers, payload) tuples.
:param responses: List of headers and payloads from each response in
the batch.
:raises: :class:`ValueError` if no requests have been deferred. | [
"Apply",
"all",
"the",
"batch",
"responses",
"to",
"the",
"futures",
"created",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/batch.py#L220-L246 |
28,011 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/snapshot.py | _SnapshotBase.read | def read(self, table, columns, keyset, index="", limit=0, partition=None):
"""Perform a ``StreamingRead`` API request for rows in a table.
:type table: str
:param table: name of the table from which to fetch data
:type columns: list of str
:param columns: names of columns to be retrieved
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
:param keyset: keys / ranges identifying rows to be retrieved
:type index: str
:param index: (Optional) name of index to use, rather than the
table's primary key
:type limit: int
:param limit: (Optional) maximum number of rows to return.
Incompatible with ``partition``.
:type partition: bytes
:param partition: (Optional) one of the partition tokens returned
from :meth:`partition_read`. Incompatible with
``limit``.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:raises ValueError:
for reuse of single-use snapshots, or if a transaction ID is
already pending for multiple-use snapshots.
"""
if self._read_request_count > 0:
if not self._multi_use:
raise ValueError("Cannot re-use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction ID pending.")
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
restart = functools.partial(
api.streaming_read,
self._session.name,
table,
columns,
keyset._to_pb(),
transaction=transaction,
index=index,
limit=limit,
partition_token=partition,
metadata=metadata,
)
iterator = _restart_on_unavailable(restart)
self._read_request_count += 1
if self._multi_use:
return StreamedResultSet(iterator, source=self)
else:
return StreamedResultSet(iterator) | python | def read(self, table, columns, keyset, index="", limit=0, partition=None):
"""Perform a ``StreamingRead`` API request for rows in a table.
:type table: str
:param table: name of the table from which to fetch data
:type columns: list of str
:param columns: names of columns to be retrieved
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
:param keyset: keys / ranges identifying rows to be retrieved
:type index: str
:param index: (Optional) name of index to use, rather than the
table's primary key
:type limit: int
:param limit: (Optional) maximum number of rows to return.
Incompatible with ``partition``.
:type partition: bytes
:param partition: (Optional) one of the partition tokens returned
from :meth:`partition_read`. Incompatible with
``limit``.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:raises ValueError:
for reuse of single-use snapshots, or if a transaction ID is
already pending for multiple-use snapshots.
"""
if self._read_request_count > 0:
if not self._multi_use:
raise ValueError("Cannot re-use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction ID pending.")
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
restart = functools.partial(
api.streaming_read,
self._session.name,
table,
columns,
keyset._to_pb(),
transaction=transaction,
index=index,
limit=limit,
partition_token=partition,
metadata=metadata,
)
iterator = _restart_on_unavailable(restart)
self._read_request_count += 1
if self._multi_use:
return StreamedResultSet(iterator, source=self)
else:
return StreamedResultSet(iterator) | [
"def",
"read",
"(",
"self",
",",
"table",
",",
"columns",
",",
"keyset",
",",
"index",
"=",
"\"\"",
",",
"limit",
"=",
"0",
",",
"partition",
"=",
"None",
")",
":",
"if",
"self",
".",
"_read_request_count",
">",
"0",
":",
"if",
"not",
"self",
".",
"_multi_use",
":",
"raise",
"ValueError",
"(",
"\"Cannot re-use single-use snapshot.\"",
")",
"if",
"self",
".",
"_transaction_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Transaction ID pending.\"",
")",
"database",
"=",
"self",
".",
"_session",
".",
"_database",
"api",
"=",
"database",
".",
"spanner_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"database",
".",
"name",
")",
"transaction",
"=",
"self",
".",
"_make_txn_selector",
"(",
")",
"restart",
"=",
"functools",
".",
"partial",
"(",
"api",
".",
"streaming_read",
",",
"self",
".",
"_session",
".",
"name",
",",
"table",
",",
"columns",
",",
"keyset",
".",
"_to_pb",
"(",
")",
",",
"transaction",
"=",
"transaction",
",",
"index",
"=",
"index",
",",
"limit",
"=",
"limit",
",",
"partition_token",
"=",
"partition",
",",
"metadata",
"=",
"metadata",
",",
")",
"iterator",
"=",
"_restart_on_unavailable",
"(",
"restart",
")",
"self",
".",
"_read_request_count",
"+=",
"1",
"if",
"self",
".",
"_multi_use",
":",
"return",
"StreamedResultSet",
"(",
"iterator",
",",
"source",
"=",
"self",
")",
"else",
":",
"return",
"StreamedResultSet",
"(",
"iterator",
")"
] | Perform a ``StreamingRead`` API request for rows in a table.
:type table: str
:param table: name of the table from which to fetch data
:type columns: list of str
:param columns: names of columns to be retrieved
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
:param keyset: keys / ranges identifying rows to be retrieved
:type index: str
:param index: (Optional) name of index to use, rather than the
table's primary key
:type limit: int
:param limit: (Optional) maximum number of rows to return.
Incompatible with ``partition``.
:type partition: bytes
:param partition: (Optional) one of the partition tokens returned
from :meth:`partition_read`. Incompatible with
``limit``.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:raises ValueError:
for reuse of single-use snapshots, or if a transaction ID is
already pending for multiple-use snapshots. | [
"Perform",
"a",
"StreamingRead",
"API",
"request",
"for",
"rows",
"in",
"a",
"table",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/snapshot.py#L89-L152 |
28,012 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/snapshot.py | _SnapshotBase.execute_sql | def execute_sql(
self,
sql,
params=None,
param_types=None,
query_mode=None,
partition=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
):
"""Perform an ``ExecuteStreamingSql`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:type query_mode:
:class:`google.cloud.spanner_v1.proto.ExecuteSqlRequest.QueryMode`
:param query_mode: Mode governing return of results / query plan. See
https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode1
:type partition: bytes
:param partition: (Optional) one of the partition tokens returned
from :meth:`partition_query`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:raises ValueError:
for reuse of single-use snapshots, or if a transaction ID is
already pending for multiple-use snapshots.
"""
if self._read_request_count > 0:
if not self._multi_use:
raise ValueError("Cannot re-use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction ID pending.")
if params is not None:
if param_types is None:
raise ValueError("Specify 'param_types' when passing 'params'.")
params_pb = Struct(
fields={key: _make_value_pb(value) for key, value in params.items()}
)
else:
params_pb = None
database = self._session._database
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
api = database.spanner_api
restart = functools.partial(
api.execute_streaming_sql,
self._session.name,
sql,
transaction=transaction,
params=params_pb,
param_types=param_types,
query_mode=query_mode,
partition_token=partition,
seqno=self._execute_sql_count,
metadata=metadata,
retry=retry,
timeout=timeout,
)
iterator = _restart_on_unavailable(restart)
self._read_request_count += 1
self._execute_sql_count += 1
if self._multi_use:
return StreamedResultSet(iterator, source=self)
else:
return StreamedResultSet(iterator) | python | def execute_sql(
self,
sql,
params=None,
param_types=None,
query_mode=None,
partition=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
):
"""Perform an ``ExecuteStreamingSql`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:type query_mode:
:class:`google.cloud.spanner_v1.proto.ExecuteSqlRequest.QueryMode`
:param query_mode: Mode governing return of results / query plan. See
https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode1
:type partition: bytes
:param partition: (Optional) one of the partition tokens returned
from :meth:`partition_query`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:raises ValueError:
for reuse of single-use snapshots, or if a transaction ID is
already pending for multiple-use snapshots.
"""
if self._read_request_count > 0:
if not self._multi_use:
raise ValueError("Cannot re-use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction ID pending.")
if params is not None:
if param_types is None:
raise ValueError("Specify 'param_types' when passing 'params'.")
params_pb = Struct(
fields={key: _make_value_pb(value) for key, value in params.items()}
)
else:
params_pb = None
database = self._session._database
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
api = database.spanner_api
restart = functools.partial(
api.execute_streaming_sql,
self._session.name,
sql,
transaction=transaction,
params=params_pb,
param_types=param_types,
query_mode=query_mode,
partition_token=partition,
seqno=self._execute_sql_count,
metadata=metadata,
retry=retry,
timeout=timeout,
)
iterator = _restart_on_unavailable(restart)
self._read_request_count += 1
self._execute_sql_count += 1
if self._multi_use:
return StreamedResultSet(iterator, source=self)
else:
return StreamedResultSet(iterator) | [
"def",
"execute_sql",
"(",
"self",
",",
"sql",
",",
"params",
"=",
"None",
",",
"param_types",
"=",
"None",
",",
"query_mode",
"=",
"None",
",",
"partition",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
")",
":",
"if",
"self",
".",
"_read_request_count",
">",
"0",
":",
"if",
"not",
"self",
".",
"_multi_use",
":",
"raise",
"ValueError",
"(",
"\"Cannot re-use single-use snapshot.\"",
")",
"if",
"self",
".",
"_transaction_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Transaction ID pending.\"",
")",
"if",
"params",
"is",
"not",
"None",
":",
"if",
"param_types",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Specify 'param_types' when passing 'params'.\"",
")",
"params_pb",
"=",
"Struct",
"(",
"fields",
"=",
"{",
"key",
":",
"_make_value_pb",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
"}",
")",
"else",
":",
"params_pb",
"=",
"None",
"database",
"=",
"self",
".",
"_session",
".",
"_database",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"database",
".",
"name",
")",
"transaction",
"=",
"self",
".",
"_make_txn_selector",
"(",
")",
"api",
"=",
"database",
".",
"spanner_api",
"restart",
"=",
"functools",
".",
"partial",
"(",
"api",
".",
"execute_streaming_sql",
",",
"self",
".",
"_session",
".",
"name",
",",
"sql",
",",
"transaction",
"=",
"transaction",
",",
"params",
"=",
"params_pb",
",",
"param_types",
"=",
"param_types",
",",
"query_mode",
"=",
"query_mode",
",",
"partition_token",
"=",
"partition",
",",
"seqno",
"=",
"self",
".",
"_execute_sql_count",
",",
"metadata",
"=",
"metadata",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
")",
"iterator",
"=",
"_restart_on_unavailable",
"(",
"restart",
")",
"self",
".",
"_read_request_count",
"+=",
"1",
"self",
".",
"_execute_sql_count",
"+=",
"1",
"if",
"self",
".",
"_multi_use",
":",
"return",
"StreamedResultSet",
"(",
"iterator",
",",
"source",
"=",
"self",
")",
"else",
":",
"return",
"StreamedResultSet",
"(",
"iterator",
")"
] | Perform an ``ExecuteStreamingSql`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:type query_mode:
:class:`google.cloud.spanner_v1.proto.ExecuteSqlRequest.QueryMode`
:param query_mode: Mode governing return of results / query plan. See
https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode1
:type partition: bytes
:param partition: (Optional) one of the partition tokens returned
from :meth:`partition_query`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:raises ValueError:
for reuse of single-use snapshots, or if a transaction ID is
already pending for multiple-use snapshots. | [
"Perform",
"an",
"ExecuteStreamingSql",
"API",
"request",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/snapshot.py#L154-L237 |
28,013 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/snapshot.py | _SnapshotBase.partition_read | def partition_read(
self,
table,
columns,
keyset,
index="",
partition_size_bytes=None,
max_partitions=None,
):
"""Perform a ``ParitionRead`` API request for rows in a table.
:type table: str
:param table: name of the table from which to fetch data
:type columns: list of str
:param columns: names of columns to be retrieved
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
:param keyset: keys / ranges identifying rows to be retrieved
:type index: str
:param index: (Optional) name of index to use, rather than the
table's primary key
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of bytes
:returns: a sequence of partition tokens
:raises ValueError:
for single-use snapshots, or if a transaction ID is
already associtated with the snapshot.
"""
if not self._multi_use:
raise ValueError("Cannot use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction not started.")
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
partition_options = PartitionOptions(
partition_size_bytes=partition_size_bytes, max_partitions=max_partitions
)
response = api.partition_read(
session=self._session.name,
table=table,
columns=columns,
key_set=keyset._to_pb(),
transaction=transaction,
index=index,
partition_options=partition_options,
metadata=metadata,
)
return [partition.partition_token for partition in response.partitions] | python | def partition_read(
self,
table,
columns,
keyset,
index="",
partition_size_bytes=None,
max_partitions=None,
):
"""Perform a ``ParitionRead`` API request for rows in a table.
:type table: str
:param table: name of the table from which to fetch data
:type columns: list of str
:param columns: names of columns to be retrieved
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
:param keyset: keys / ranges identifying rows to be retrieved
:type index: str
:param index: (Optional) name of index to use, rather than the
table's primary key
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of bytes
:returns: a sequence of partition tokens
:raises ValueError:
for single-use snapshots, or if a transaction ID is
already associtated with the snapshot.
"""
if not self._multi_use:
raise ValueError("Cannot use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction not started.")
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
partition_options = PartitionOptions(
partition_size_bytes=partition_size_bytes, max_partitions=max_partitions
)
response = api.partition_read(
session=self._session.name,
table=table,
columns=columns,
key_set=keyset._to_pb(),
transaction=transaction,
index=index,
partition_options=partition_options,
metadata=metadata,
)
return [partition.partition_token for partition in response.partitions] | [
"def",
"partition_read",
"(",
"self",
",",
"table",
",",
"columns",
",",
"keyset",
",",
"index",
"=",
"\"\"",
",",
"partition_size_bytes",
"=",
"None",
",",
"max_partitions",
"=",
"None",
",",
")",
":",
"if",
"not",
"self",
".",
"_multi_use",
":",
"raise",
"ValueError",
"(",
"\"Cannot use single-use snapshot.\"",
")",
"if",
"self",
".",
"_transaction_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Transaction not started.\"",
")",
"database",
"=",
"self",
".",
"_session",
".",
"_database",
"api",
"=",
"database",
".",
"spanner_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"database",
".",
"name",
")",
"transaction",
"=",
"self",
".",
"_make_txn_selector",
"(",
")",
"partition_options",
"=",
"PartitionOptions",
"(",
"partition_size_bytes",
"=",
"partition_size_bytes",
",",
"max_partitions",
"=",
"max_partitions",
")",
"response",
"=",
"api",
".",
"partition_read",
"(",
"session",
"=",
"self",
".",
"_session",
".",
"name",
",",
"table",
"=",
"table",
",",
"columns",
"=",
"columns",
",",
"key_set",
"=",
"keyset",
".",
"_to_pb",
"(",
")",
",",
"transaction",
"=",
"transaction",
",",
"index",
"=",
"index",
",",
"partition_options",
"=",
"partition_options",
",",
"metadata",
"=",
"metadata",
",",
")",
"return",
"[",
"partition",
".",
"partition_token",
"for",
"partition",
"in",
"response",
".",
"partitions",
"]"
] | Perform a ``ParitionRead`` API request for rows in a table.
:type table: str
:param table: name of the table from which to fetch data
:type columns: list of str
:param columns: names of columns to be retrieved
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
:param keyset: keys / ranges identifying rows to be retrieved
:type index: str
:param index: (Optional) name of index to use, rather than the
table's primary key
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of bytes
:returns: a sequence of partition tokens
:raises ValueError:
for single-use snapshots, or if a transaction ID is
already associtated with the snapshot. | [
"Perform",
"a",
"ParitionRead",
"API",
"request",
"for",
"rows",
"in",
"a",
"table",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/snapshot.py#L239-L306 |
28,014 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/snapshot.py | _SnapshotBase.partition_query | def partition_query(
self,
sql,
params=None,
param_types=None,
partition_size_bytes=None,
max_partitions=None,
):
"""Perform a ``ParitionQuery`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of bytes
:returns: a sequence of partition tokens
:raises ValueError:
for single-use snapshots, or if a transaction ID is
already associtated with the snapshot.
"""
if not self._multi_use:
raise ValueError("Cannot use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction not started.")
if params is not None:
if param_types is None:
raise ValueError("Specify 'param_types' when passing 'params'.")
params_pb = Struct(
fields={key: _make_value_pb(value) for key, value in params.items()}
)
else:
params_pb = None
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
partition_options = PartitionOptions(
partition_size_bytes=partition_size_bytes, max_partitions=max_partitions
)
response = api.partition_query(
session=self._session.name,
sql=sql,
transaction=transaction,
params=params_pb,
param_types=param_types,
partition_options=partition_options,
metadata=metadata,
)
return [partition.partition_token for partition in response.partitions] | python | def partition_query(
self,
sql,
params=None,
param_types=None,
partition_size_bytes=None,
max_partitions=None,
):
"""Perform a ``ParitionQuery`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of bytes
:returns: a sequence of partition tokens
:raises ValueError:
for single-use snapshots, or if a transaction ID is
already associtated with the snapshot.
"""
if not self._multi_use:
raise ValueError("Cannot use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction not started.")
if params is not None:
if param_types is None:
raise ValueError("Specify 'param_types' when passing 'params'.")
params_pb = Struct(
fields={key: _make_value_pb(value) for key, value in params.items()}
)
else:
params_pb = None
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
partition_options = PartitionOptions(
partition_size_bytes=partition_size_bytes, max_partitions=max_partitions
)
response = api.partition_query(
session=self._session.name,
sql=sql,
transaction=transaction,
params=params_pb,
param_types=param_types,
partition_options=partition_options,
metadata=metadata,
)
return [partition.partition_token for partition in response.partitions] | [
"def",
"partition_query",
"(",
"self",
",",
"sql",
",",
"params",
"=",
"None",
",",
"param_types",
"=",
"None",
",",
"partition_size_bytes",
"=",
"None",
",",
"max_partitions",
"=",
"None",
",",
")",
":",
"if",
"not",
"self",
".",
"_multi_use",
":",
"raise",
"ValueError",
"(",
"\"Cannot use single-use snapshot.\"",
")",
"if",
"self",
".",
"_transaction_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Transaction not started.\"",
")",
"if",
"params",
"is",
"not",
"None",
":",
"if",
"param_types",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Specify 'param_types' when passing 'params'.\"",
")",
"params_pb",
"=",
"Struct",
"(",
"fields",
"=",
"{",
"key",
":",
"_make_value_pb",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
"}",
")",
"else",
":",
"params_pb",
"=",
"None",
"database",
"=",
"self",
".",
"_session",
".",
"_database",
"api",
"=",
"database",
".",
"spanner_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"database",
".",
"name",
")",
"transaction",
"=",
"self",
".",
"_make_txn_selector",
"(",
")",
"partition_options",
"=",
"PartitionOptions",
"(",
"partition_size_bytes",
"=",
"partition_size_bytes",
",",
"max_partitions",
"=",
"max_partitions",
")",
"response",
"=",
"api",
".",
"partition_query",
"(",
"session",
"=",
"self",
".",
"_session",
".",
"name",
",",
"sql",
"=",
"sql",
",",
"transaction",
"=",
"transaction",
",",
"params",
"=",
"params_pb",
",",
"param_types",
"=",
"param_types",
",",
"partition_options",
"=",
"partition_options",
",",
"metadata",
"=",
"metadata",
",",
")",
"return",
"[",
"partition",
".",
"partition_token",
"for",
"partition",
"in",
"response",
".",
"partitions",
"]"
] | Perform a ``ParitionQuery`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of bytes
:returns: a sequence of partition tokens
:raises ValueError:
for single-use snapshots, or if a transaction ID is
already associtated with the snapshot. | [
"Perform",
"a",
"ParitionQuery",
"API",
"request",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/snapshot.py#L308-L381 |
28,015 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/snapshot.py | Snapshot.begin | def begin(self):
"""Begin a read-only transaction on the database.
:rtype: bytes
:returns: the ID for the newly-begun transaction.
:raises ValueError:
if the transaction is already begun, committed, or rolled back.
"""
if not self._multi_use:
raise ValueError("Cannot call 'begin' on single-use snapshots")
if self._transaction_id is not None:
raise ValueError("Read-only transaction already begun")
if self._read_request_count > 0:
raise ValueError("Read-only transaction already pending")
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
txn_selector = self._make_txn_selector()
response = api.begin_transaction(
self._session.name, txn_selector.begin, metadata=metadata
)
self._transaction_id = response.id
return self._transaction_id | python | def begin(self):
"""Begin a read-only transaction on the database.
:rtype: bytes
:returns: the ID for the newly-begun transaction.
:raises ValueError:
if the transaction is already begun, committed, or rolled back.
"""
if not self._multi_use:
raise ValueError("Cannot call 'begin' on single-use snapshots")
if self._transaction_id is not None:
raise ValueError("Read-only transaction already begun")
if self._read_request_count > 0:
raise ValueError("Read-only transaction already pending")
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
txn_selector = self._make_txn_selector()
response = api.begin_transaction(
self._session.name, txn_selector.begin, metadata=metadata
)
self._transaction_id = response.id
return self._transaction_id | [
"def",
"begin",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_multi_use",
":",
"raise",
"ValueError",
"(",
"\"Cannot call 'begin' on single-use snapshots\"",
")",
"if",
"self",
".",
"_transaction_id",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Read-only transaction already begun\"",
")",
"if",
"self",
".",
"_read_request_count",
">",
"0",
":",
"raise",
"ValueError",
"(",
"\"Read-only transaction already pending\"",
")",
"database",
"=",
"self",
".",
"_session",
".",
"_database",
"api",
"=",
"database",
".",
"spanner_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"database",
".",
"name",
")",
"txn_selector",
"=",
"self",
".",
"_make_txn_selector",
"(",
")",
"response",
"=",
"api",
".",
"begin_transaction",
"(",
"self",
".",
"_session",
".",
"name",
",",
"txn_selector",
".",
"begin",
",",
"metadata",
"=",
"metadata",
")",
"self",
".",
"_transaction_id",
"=",
"response",
".",
"id",
"return",
"self",
".",
"_transaction_id"
] | Begin a read-only transaction on the database.
:rtype: bytes
:returns: the ID for the newly-begun transaction.
:raises ValueError:
if the transaction is already begun, committed, or rolled back. | [
"Begin",
"a",
"read",
"-",
"only",
"transaction",
"on",
"the",
"database",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/snapshot.py#L479-L505 |
28,016 | googleapis/google-cloud-python | api_core/google/api_core/gapic_v1/client_info.py | ClientInfo.to_user_agent | def to_user_agent(self):
"""Returns the user-agent string for this client info."""
# Note: the order here is important as the internal metrics system
# expects these items to be in specific locations.
ua = ""
if self.user_agent is not None:
ua += "{user_agent} "
ua += "gl-python/{python_version} "
if self.grpc_version is not None:
ua += "grpc/{grpc_version} "
ua += "gax/{api_core_version} "
if self.gapic_version is not None:
ua += "gapic/{gapic_version} "
if self.client_library_version is not None:
ua += "gccl/{client_library_version} "
return ua.format(**self.__dict__).strip() | python | def to_user_agent(self):
"""Returns the user-agent string for this client info."""
# Note: the order here is important as the internal metrics system
# expects these items to be in specific locations.
ua = ""
if self.user_agent is not None:
ua += "{user_agent} "
ua += "gl-python/{python_version} "
if self.grpc_version is not None:
ua += "grpc/{grpc_version} "
ua += "gax/{api_core_version} "
if self.gapic_version is not None:
ua += "gapic/{gapic_version} "
if self.client_library_version is not None:
ua += "gccl/{client_library_version} "
return ua.format(**self.__dict__).strip() | [
"def",
"to_user_agent",
"(",
"self",
")",
":",
"# Note: the order here is important as the internal metrics system",
"# expects these items to be in specific locations.",
"ua",
"=",
"\"\"",
"if",
"self",
".",
"user_agent",
"is",
"not",
"None",
":",
"ua",
"+=",
"\"{user_agent} \"",
"ua",
"+=",
"\"gl-python/{python_version} \"",
"if",
"self",
".",
"grpc_version",
"is",
"not",
"None",
":",
"ua",
"+=",
"\"grpc/{grpc_version} \"",
"ua",
"+=",
"\"gax/{api_core_version} \"",
"if",
"self",
".",
"gapic_version",
"is",
"not",
"None",
":",
"ua",
"+=",
"\"gapic/{gapic_version} \"",
"if",
"self",
".",
"client_library_version",
"is",
"not",
"None",
":",
"ua",
"+=",
"\"gccl/{client_library_version} \"",
"return",
"ua",
".",
"format",
"(",
"*",
"*",
"self",
".",
"__dict__",
")",
".",
"strip",
"(",
")"
] | Returns the user-agent string for this client info. | [
"Returns",
"the",
"user",
"-",
"agent",
"string",
"for",
"this",
"client",
"info",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/gapic_v1/client_info.py#L75-L98 |
28,017 | googleapis/google-cloud-python | trace/google/cloud/trace/v1/_gapic.py | make_trace_api | def make_trace_api(client):
"""
Create an instance of the gapic Trace API.
Args:
client (~google.cloud.trace.client.Client): The client that holds
configuration details.
Returns:
A :class:`~google.cloud.trace._gapic._TraceAPI` instance with the
proper configurations.
"""
generated = trace_service_client.TraceServiceClient(
credentials=client._credentials, client_info=_CLIENT_INFO
)
return _TraceAPI(generated, client) | python | def make_trace_api(client):
"""
Create an instance of the gapic Trace API.
Args:
client (~google.cloud.trace.client.Client): The client that holds
configuration details.
Returns:
A :class:`~google.cloud.trace._gapic._TraceAPI` instance with the
proper configurations.
"""
generated = trace_service_client.TraceServiceClient(
credentials=client._credentials, client_info=_CLIENT_INFO
)
return _TraceAPI(generated, client) | [
"def",
"make_trace_api",
"(",
"client",
")",
":",
"generated",
"=",
"trace_service_client",
".",
"TraceServiceClient",
"(",
"credentials",
"=",
"client",
".",
"_credentials",
",",
"client_info",
"=",
"_CLIENT_INFO",
")",
"return",
"_TraceAPI",
"(",
"generated",
",",
"client",
")"
] | Create an instance of the gapic Trace API.
Args:
client (~google.cloud.trace.client.Client): The client that holds
configuration details.
Returns:
A :class:`~google.cloud.trace._gapic._TraceAPI` instance with the
proper configurations. | [
"Create",
"an",
"instance",
"of",
"the",
"gapic",
"Trace",
"API",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/trace/google/cloud/trace/v1/_gapic.py#L168-L183 |
28,018 | googleapis/google-cloud-python | storage/google/cloud/storage/client.py | _item_to_bucket | def _item_to_bucket(iterator, item):
"""Convert a JSON bucket to the native object.
: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 bucket.
:rtype: :class:`.Bucket`
:returns: The next bucket in the page.
"""
name = item.get("name")
bucket = Bucket(iterator.client, name)
bucket._set_properties(item)
return bucket | python | def _item_to_bucket(iterator, item):
"""Convert a JSON bucket to the native object.
: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 bucket.
:rtype: :class:`.Bucket`
:returns: The next bucket in the page.
"""
name = item.get("name")
bucket = Bucket(iterator.client, name)
bucket._set_properties(item)
return bucket | [
"def",
"_item_to_bucket",
"(",
"iterator",
",",
"item",
")",
":",
"name",
"=",
"item",
".",
"get",
"(",
"\"name\"",
")",
"bucket",
"=",
"Bucket",
"(",
"iterator",
".",
"client",
",",
"name",
")",
"bucket",
".",
"_set_properties",
"(",
"item",
")",
"return",
"bucket"
] | Convert a JSON bucket to the native object.
: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 bucket.
:rtype: :class:`.Bucket`
:returns: The next bucket in the page. | [
"Convert",
"a",
"JSON",
"bucket",
"to",
"the",
"native",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/client.py#L374-L389 |
28,019 | googleapis/google-cloud-python | storage/google/cloud/storage/client.py | Client.get_service_account_email | def get_service_account_email(self, project=None):
"""Get the email address of the project's GCS service account
:type project: str
:param project:
(Optional) Project ID to use for retreiving GCS service account
email address. Defaults to the client's project.
:rtype: str
:returns: service account email address
"""
if project is None:
project = self.project
path = "/projects/%s/serviceAccount" % (project,)
api_response = self._base_connection.api_request(method="GET", path=path)
return api_response["email_address"] | python | def get_service_account_email(self, project=None):
"""Get the email address of the project's GCS service account
:type project: str
:param project:
(Optional) Project ID to use for retreiving GCS service account
email address. Defaults to the client's project.
:rtype: str
:returns: service account email address
"""
if project is None:
project = self.project
path = "/projects/%s/serviceAccount" % (project,)
api_response = self._base_connection.api_request(method="GET", path=path)
return api_response["email_address"] | [
"def",
"get_service_account_email",
"(",
"self",
",",
"project",
"=",
"None",
")",
":",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"path",
"=",
"\"/projects/%s/serviceAccount\"",
"%",
"(",
"project",
",",
")",
"api_response",
"=",
"self",
".",
"_base_connection",
".",
"api_request",
"(",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"path",
")",
"return",
"api_response",
"[",
"\"email_address\"",
"]"
] | Get the email address of the project's GCS service account
:type project: str
:param project:
(Optional) Project ID to use for retreiving GCS service account
email address. Defaults to the client's project.
:rtype: str
:returns: service account email address | [
"Get",
"the",
"email",
"address",
"of",
"the",
"project",
"s",
"GCS",
"service",
"account"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/client.py#L157-L172 |
28,020 | googleapis/google-cloud-python | storage/google/cloud/storage/client.py | Client.bucket | def bucket(self, bucket_name, user_project=None):
"""Factory constructor for bucket object.
.. note::
This will not make an HTTP request; it simply instantiates
a bucket object owned by this client.
:type bucket_name: str
:param bucket_name: The name of the bucket to be instantiated.
:type user_project: str
:param user_project: (Optional) the project ID to be billed for API
requests made via the bucket.
:rtype: :class:`google.cloud.storage.bucket.Bucket`
:returns: The bucket object created.
"""
return Bucket(client=self, name=bucket_name, user_project=user_project) | python | def bucket(self, bucket_name, user_project=None):
"""Factory constructor for bucket object.
.. note::
This will not make an HTTP request; it simply instantiates
a bucket object owned by this client.
:type bucket_name: str
:param bucket_name: The name of the bucket to be instantiated.
:type user_project: str
:param user_project: (Optional) the project ID to be billed for API
requests made via the bucket.
:rtype: :class:`google.cloud.storage.bucket.Bucket`
:returns: The bucket object created.
"""
return Bucket(client=self, name=bucket_name, user_project=user_project) | [
"def",
"bucket",
"(",
"self",
",",
"bucket_name",
",",
"user_project",
"=",
"None",
")",
":",
"return",
"Bucket",
"(",
"client",
"=",
"self",
",",
"name",
"=",
"bucket_name",
",",
"user_project",
"=",
"user_project",
")"
] | Factory constructor for bucket object.
.. note::
This will not make an HTTP request; it simply instantiates
a bucket object owned by this client.
:type bucket_name: str
:param bucket_name: The name of the bucket to be instantiated.
:type user_project: str
:param user_project: (Optional) the project ID to be billed for API
requests made via the bucket.
:rtype: :class:`google.cloud.storage.bucket.Bucket`
:returns: The bucket object created. | [
"Factory",
"constructor",
"for",
"bucket",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/client.py#L174-L191 |
28,021 | googleapis/google-cloud-python | storage/google/cloud/storage/client.py | Client.get_bucket | def get_bucket(self, bucket_name):
"""Get a bucket by name.
If the bucket isn't found, this will raise a
:class:`google.cloud.exceptions.NotFound`.
For example:
.. literalinclude:: snippets.py
:start-after: [START get_bucket]
:end-before: [END get_bucket]
This implements "storage.buckets.get".
:type bucket_name: str
:param bucket_name: The name of the bucket to get.
:rtype: :class:`google.cloud.storage.bucket.Bucket`
:returns: The bucket matching the name provided.
:raises: :class:`google.cloud.exceptions.NotFound`
"""
bucket = Bucket(self, name=bucket_name)
bucket.reload(client=self)
return bucket | python | def get_bucket(self, bucket_name):
"""Get a bucket by name.
If the bucket isn't found, this will raise a
:class:`google.cloud.exceptions.NotFound`.
For example:
.. literalinclude:: snippets.py
:start-after: [START get_bucket]
:end-before: [END get_bucket]
This implements "storage.buckets.get".
:type bucket_name: str
:param bucket_name: The name of the bucket to get.
:rtype: :class:`google.cloud.storage.bucket.Bucket`
:returns: The bucket matching the name provided.
:raises: :class:`google.cloud.exceptions.NotFound`
"""
bucket = Bucket(self, name=bucket_name)
bucket.reload(client=self)
return bucket | [
"def",
"get_bucket",
"(",
"self",
",",
"bucket_name",
")",
":",
"bucket",
"=",
"Bucket",
"(",
"self",
",",
"name",
"=",
"bucket_name",
")",
"bucket",
".",
"reload",
"(",
"client",
"=",
"self",
")",
"return",
"bucket"
] | Get a bucket by name.
If the bucket isn't found, this will raise a
:class:`google.cloud.exceptions.NotFound`.
For example:
.. literalinclude:: snippets.py
:start-after: [START get_bucket]
:end-before: [END get_bucket]
This implements "storage.buckets.get".
:type bucket_name: str
:param bucket_name: The name of the bucket to get.
:rtype: :class:`google.cloud.storage.bucket.Bucket`
:returns: The bucket matching the name provided.
:raises: :class:`google.cloud.exceptions.NotFound` | [
"Get",
"a",
"bucket",
"by",
"name",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/client.py#L205-L228 |
28,022 | googleapis/google-cloud-python | storage/google/cloud/storage/client.py | Client.list_buckets | def list_buckets(
self,
max_results=None,
page_token=None,
prefix=None,
projection="noAcl",
fields=None,
project=None,
):
"""Get all buckets in the project associated to the client.
This will not populate the list of blobs available in each
bucket.
.. literalinclude:: snippets.py
:start-after: [START list_buckets]
:end-before: [END list_buckets]
This implements "storage.buckets.list".
:type max_results: int
:param max_results: Optional. The maximum number of buckets to return.
:type page_token: str
:param page_token:
Optional. If present, return the next batch of buckets, 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. Filter results to buckets whose names begin
with this prefix.
:type projection: str
:param projection:
(Optional) Specifies the set of properties to return. If used, must
be 'full' or 'noAcl'. Defaults to 'noAcl'.
: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
bucket returned: 'items/id,nextPageToken'
:type project: str
:param project: (Optional) the project whose buckets are to be listed.
If not passed, uses the project set on the client.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:raises ValueError: if both ``project`` is ``None`` and the client's
project is also ``None``.
:returns: Iterator of all :class:`~google.cloud.storage.bucket.Bucket`
belonging to this project.
"""
if project is None:
project = self.project
if project is None:
raise ValueError("Client project not set: pass an explicit project.")
extra_params = {"project": project}
if prefix is not None:
extra_params["prefix"] = prefix
extra_params["projection"] = projection
if fields is not None:
extra_params["fields"] = fields
return page_iterator.HTTPIterator(
client=self,
api_request=self._connection.api_request,
path="/b",
item_to_value=_item_to_bucket,
page_token=page_token,
max_results=max_results,
extra_params=extra_params,
) | python | def list_buckets(
self,
max_results=None,
page_token=None,
prefix=None,
projection="noAcl",
fields=None,
project=None,
):
"""Get all buckets in the project associated to the client.
This will not populate the list of blobs available in each
bucket.
.. literalinclude:: snippets.py
:start-after: [START list_buckets]
:end-before: [END list_buckets]
This implements "storage.buckets.list".
:type max_results: int
:param max_results: Optional. The maximum number of buckets to return.
:type page_token: str
:param page_token:
Optional. If present, return the next batch of buckets, 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. Filter results to buckets whose names begin
with this prefix.
:type projection: str
:param projection:
(Optional) Specifies the set of properties to return. If used, must
be 'full' or 'noAcl'. Defaults to 'noAcl'.
: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
bucket returned: 'items/id,nextPageToken'
:type project: str
:param project: (Optional) the project whose buckets are to be listed.
If not passed, uses the project set on the client.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:raises ValueError: if both ``project`` is ``None`` and the client's
project is also ``None``.
:returns: Iterator of all :class:`~google.cloud.storage.bucket.Bucket`
belonging to this project.
"""
if project is None:
project = self.project
if project is None:
raise ValueError("Client project not set: pass an explicit project.")
extra_params = {"project": project}
if prefix is not None:
extra_params["prefix"] = prefix
extra_params["projection"] = projection
if fields is not None:
extra_params["fields"] = fields
return page_iterator.HTTPIterator(
client=self,
api_request=self._connection.api_request,
path="/b",
item_to_value=_item_to_bucket,
page_token=page_token,
max_results=max_results,
extra_params=extra_params,
) | [
"def",
"list_buckets",
"(",
"self",
",",
"max_results",
"=",
"None",
",",
"page_token",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"projection",
"=",
"\"noAcl\"",
",",
"fields",
"=",
"None",
",",
"project",
"=",
"None",
",",
")",
":",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"if",
"project",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Client project not set: pass an explicit project.\"",
")",
"extra_params",
"=",
"{",
"\"project\"",
":",
"project",
"}",
"if",
"prefix",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"prefix\"",
"]",
"=",
"prefix",
"extra_params",
"[",
"\"projection\"",
"]",
"=",
"projection",
"if",
"fields",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"fields\"",
"]",
"=",
"fields",
"return",
"page_iterator",
".",
"HTTPIterator",
"(",
"client",
"=",
"self",
",",
"api_request",
"=",
"self",
".",
"_connection",
".",
"api_request",
",",
"path",
"=",
"\"/b\"",
",",
"item_to_value",
"=",
"_item_to_bucket",
",",
"page_token",
"=",
"page_token",
",",
"max_results",
"=",
"max_results",
",",
"extra_params",
"=",
"extra_params",
",",
")"
] | Get all buckets in the project associated to the client.
This will not populate the list of blobs available in each
bucket.
.. literalinclude:: snippets.py
:start-after: [START list_buckets]
:end-before: [END list_buckets]
This implements "storage.buckets.list".
:type max_results: int
:param max_results: Optional. The maximum number of buckets to return.
:type page_token: str
:param page_token:
Optional. If present, return the next batch of buckets, 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. Filter results to buckets whose names begin
with this prefix.
:type projection: str
:param projection:
(Optional) Specifies the set of properties to return. If used, must
be 'full' or 'noAcl'. Defaults to 'noAcl'.
: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
bucket returned: 'items/id,nextPageToken'
:type project: str
:param project: (Optional) the project whose buckets are to be listed.
If not passed, uses the project set on the client.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:raises ValueError: if both ``project`` is ``None`` and the client's
project is also ``None``.
:returns: Iterator of all :class:`~google.cloud.storage.bucket.Bucket`
belonging to this project. | [
"Get",
"all",
"buckets",
"in",
"the",
"project",
"associated",
"to",
"the",
"client",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/client.py#L290-L371 |
28,023 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | _make_job_id | def _make_job_id(job_id, prefix=None):
"""Construct an ID for a new job.
:type job_id: str or ``NoneType``
:param job_id: the user-provided job ID
:type prefix: str or ``NoneType``
:param prefix: (Optional) the user-provided prefix for a job ID
:rtype: str
:returns: A job ID
"""
if job_id is not None:
return job_id
elif prefix is not None:
return str(prefix) + str(uuid.uuid4())
else:
return str(uuid.uuid4()) | python | def _make_job_id(job_id, prefix=None):
"""Construct an ID for a new job.
:type job_id: str or ``NoneType``
:param job_id: the user-provided job ID
:type prefix: str or ``NoneType``
:param prefix: (Optional) the user-provided prefix for a job ID
:rtype: str
:returns: A job ID
"""
if job_id is not None:
return job_id
elif prefix is not None:
return str(prefix) + str(uuid.uuid4())
else:
return str(uuid.uuid4()) | [
"def",
"_make_job_id",
"(",
"job_id",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"job_id",
"is",
"not",
"None",
":",
"return",
"job_id",
"elif",
"prefix",
"is",
"not",
"None",
":",
"return",
"str",
"(",
"prefix",
")",
"+",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"else",
":",
"return",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")"
] | Construct an ID for a new job.
:type job_id: str or ``NoneType``
:param job_id: the user-provided job ID
:type prefix: str or ``NoneType``
:param prefix: (Optional) the user-provided prefix for a job ID
:rtype: str
:returns: A job ID | [
"Construct",
"an",
"ID",
"for",
"a",
"new",
"job",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L2059-L2076 |
28,024 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | _check_mode | def _check_mode(stream):
"""Check that a stream was opened in read-binary mode.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:raises: :exc:`ValueError` if the ``stream.mode`` is a valid attribute
and is not among ``rb``, ``r+b`` or ``rb+``.
"""
mode = getattr(stream, "mode", None)
if isinstance(stream, gzip.GzipFile):
if mode != gzip.READ:
raise ValueError(
"Cannot upload gzip files opened in write mode: use "
"gzip.GzipFile(filename, mode='rb')"
)
else:
if mode is not None and mode not in ("rb", "r+b", "rb+"):
raise ValueError(
"Cannot upload files opened in text mode: use "
"open(filename, mode='rb') or open(filename, mode='r+b')"
) | python | def _check_mode(stream):
"""Check that a stream was opened in read-binary mode.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:raises: :exc:`ValueError` if the ``stream.mode`` is a valid attribute
and is not among ``rb``, ``r+b`` or ``rb+``.
"""
mode = getattr(stream, "mode", None)
if isinstance(stream, gzip.GzipFile):
if mode != gzip.READ:
raise ValueError(
"Cannot upload gzip files opened in write mode: use "
"gzip.GzipFile(filename, mode='rb')"
)
else:
if mode is not None and mode not in ("rb", "r+b", "rb+"):
raise ValueError(
"Cannot upload files opened in text mode: use "
"open(filename, mode='rb') or open(filename, mode='r+b')"
) | [
"def",
"_check_mode",
"(",
"stream",
")",
":",
"mode",
"=",
"getattr",
"(",
"stream",
",",
"\"mode\"",
",",
"None",
")",
"if",
"isinstance",
"(",
"stream",
",",
"gzip",
".",
"GzipFile",
")",
":",
"if",
"mode",
"!=",
"gzip",
".",
"READ",
":",
"raise",
"ValueError",
"(",
"\"Cannot upload gzip files opened in write mode: use \"",
"\"gzip.GzipFile(filename, mode='rb')\"",
")",
"else",
":",
"if",
"mode",
"is",
"not",
"None",
"and",
"mode",
"not",
"in",
"(",
"\"rb\"",
",",
"\"r+b\"",
",",
"\"rb+\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot upload files opened in text mode: use \"",
"\"open(filename, mode='rb') or open(filename, mode='r+b')\"",
")"
] | Check that a stream was opened in read-binary mode.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:raises: :exc:`ValueError` if the ``stream.mode`` is a valid attribute
and is not among ``rb``, ``r+b`` or ``rb+``. | [
"Check",
"that",
"a",
"stream",
"was",
"opened",
"in",
"read",
"-",
"binary",
"mode",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L2079-L2101 |
28,025 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.get_service_account_email | def get_service_account_email(self, project=None):
"""Get the email address of the project's BigQuery service account
Note:
This is the service account that BigQuery uses to manage tables
encrypted by a key in KMS.
Args:
project (str, optional):
Project ID to use for retreiving service account email.
Defaults to the client's project.
Returns:
str: service account email address
Example:
>>> from google.cloud import bigquery
>>> client = bigquery.Client()
>>> client.get_service_account_email()
my_service_account@my-project.iam.gserviceaccount.com
"""
if project is None:
project = self.project
path = "/projects/%s/serviceAccount" % (project,)
api_response = self._connection.api_request(method="GET", path=path)
return api_response["email"] | python | def get_service_account_email(self, project=None):
"""Get the email address of the project's BigQuery service account
Note:
This is the service account that BigQuery uses to manage tables
encrypted by a key in KMS.
Args:
project (str, optional):
Project ID to use for retreiving service account email.
Defaults to the client's project.
Returns:
str: service account email address
Example:
>>> from google.cloud import bigquery
>>> client = bigquery.Client()
>>> client.get_service_account_email()
my_service_account@my-project.iam.gserviceaccount.com
"""
if project is None:
project = self.project
path = "/projects/%s/serviceAccount" % (project,)
api_response = self._connection.api_request(method="GET", path=path)
return api_response["email"] | [
"def",
"get_service_account_email",
"(",
"self",
",",
"project",
"=",
"None",
")",
":",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"path",
"=",
"\"/projects/%s/serviceAccount\"",
"%",
"(",
"project",
",",
")",
"api_response",
"=",
"self",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"path",
")",
"return",
"api_response",
"[",
"\"email\"",
"]"
] | Get the email address of the project's BigQuery service account
Note:
This is the service account that BigQuery uses to manage tables
encrypted by a key in KMS.
Args:
project (str, optional):
Project ID to use for retreiving service account email.
Defaults to the client's project.
Returns:
str: service account email address
Example:
>>> from google.cloud import bigquery
>>> client = bigquery.Client()
>>> client.get_service_account_email()
my_service_account@my-project.iam.gserviceaccount.com | [
"Get",
"the",
"email",
"address",
"of",
"the",
"project",
"s",
"BigQuery",
"service",
"account"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L164-L191 |
28,026 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.list_projects | def list_projects(self, max_results=None, page_token=None, retry=DEFAULT_RETRY):
"""List projects for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/projects/list
:type max_results: int
:param max_results: (Optional) maximum number of projects to return,
If not passed, defaults to a value set by the API.
:type page_token: str
:param page_token:
(Optional) Token representing a cursor into the projects. If
not passed, the API will return the first page of projects.
The token marks the beginning of the iterator to be returned
and the value of the ``page_token`` can be accessed at
``next_page_token`` of the
:class:`~google.api_core.page_iterator.HTTPIterator`.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of :class:`~google.cloud.bigquery.client.Project`
accessible to the current client.
"""
return page_iterator.HTTPIterator(
client=self,
api_request=functools.partial(self._call_api, retry),
path="/projects",
item_to_value=_item_to_project,
items_key="projects",
page_token=page_token,
max_results=max_results,
) | python | def list_projects(self, max_results=None, page_token=None, retry=DEFAULT_RETRY):
"""List projects for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/projects/list
:type max_results: int
:param max_results: (Optional) maximum number of projects to return,
If not passed, defaults to a value set by the API.
:type page_token: str
:param page_token:
(Optional) Token representing a cursor into the projects. If
not passed, the API will return the first page of projects.
The token marks the beginning of the iterator to be returned
and the value of the ``page_token`` can be accessed at
``next_page_token`` of the
:class:`~google.api_core.page_iterator.HTTPIterator`.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of :class:`~google.cloud.bigquery.client.Project`
accessible to the current client.
"""
return page_iterator.HTTPIterator(
client=self,
api_request=functools.partial(self._call_api, retry),
path="/projects",
item_to_value=_item_to_project,
items_key="projects",
page_token=page_token,
max_results=max_results,
) | [
"def",
"list_projects",
"(",
"self",
",",
"max_results",
"=",
"None",
",",
"page_token",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"return",
"page_iterator",
".",
"HTTPIterator",
"(",
"client",
"=",
"self",
",",
"api_request",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_call_api",
",",
"retry",
")",
",",
"path",
"=",
"\"/projects\"",
",",
"item_to_value",
"=",
"_item_to_project",
",",
"items_key",
"=",
"\"projects\"",
",",
"page_token",
"=",
"page_token",
",",
"max_results",
"=",
"max_results",
",",
")"
] | List projects for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/projects/list
:type max_results: int
:param max_results: (Optional) maximum number of projects to return,
If not passed, defaults to a value set by the API.
:type page_token: str
:param page_token:
(Optional) Token representing a cursor into the projects. If
not passed, the API will return the first page of projects.
The token marks the beginning of the iterator to be returned
and the value of the ``page_token`` can be accessed at
``next_page_token`` of the
:class:`~google.api_core.page_iterator.HTTPIterator`.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
:rtype: :class:`~google.api_core.page_iterator.Iterator`
:returns: Iterator of :class:`~google.cloud.bigquery.client.Project`
accessible to the current client. | [
"List",
"projects",
"for",
"the",
"project",
"associated",
"with",
"this",
"client",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L193-L227 |
28,027 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.list_datasets | def list_datasets(
self,
project=None,
include_all=False,
filter=None,
max_results=None,
page_token=None,
retry=DEFAULT_RETRY,
):
"""List datasets for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list
Args:
project (str):
Optional. Project ID to use for retreiving datasets. Defaults
to the client's project.
include_all (bool):
Optional. True if results include hidden datasets. Defaults
to False.
filter (str):
Optional. An expression for filtering the results by label.
For syntax, see
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list#filter.
max_results (int):
Optional. Maximum number of datasets to return.
page_token (str):
Optional. Token representing a cursor into the datasets. If
not passed, the API will return the first page of datasets.
The token marks the beginning of the iterator to be returned
and the value of the ``page_token`` can be accessed at
``next_page_token`` of the
:class:`~google.api_core.page_iterator.HTTPIterator`.
retry (google.api_core.retry.Retry):
Optional. How to retry the RPC.
Returns:
google.api_core.page_iterator.Iterator:
Iterator of
:class:`~google.cloud.bigquery.dataset.DatasetListItem`.
associated with the project.
"""
extra_params = {}
if project is None:
project = self.project
if include_all:
extra_params["all"] = True
if filter:
# TODO: consider supporting a dict of label -> value for filter,
# and converting it into a string here.
extra_params["filter"] = filter
path = "/projects/%s/datasets" % (project,)
return page_iterator.HTTPIterator(
client=self,
api_request=functools.partial(self._call_api, retry),
path=path,
item_to_value=_item_to_dataset,
items_key="datasets",
page_token=page_token,
max_results=max_results,
extra_params=extra_params,
) | python | def list_datasets(
self,
project=None,
include_all=False,
filter=None,
max_results=None,
page_token=None,
retry=DEFAULT_RETRY,
):
"""List datasets for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list
Args:
project (str):
Optional. Project ID to use for retreiving datasets. Defaults
to the client's project.
include_all (bool):
Optional. True if results include hidden datasets. Defaults
to False.
filter (str):
Optional. An expression for filtering the results by label.
For syntax, see
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list#filter.
max_results (int):
Optional. Maximum number of datasets to return.
page_token (str):
Optional. Token representing a cursor into the datasets. If
not passed, the API will return the first page of datasets.
The token marks the beginning of the iterator to be returned
and the value of the ``page_token`` can be accessed at
``next_page_token`` of the
:class:`~google.api_core.page_iterator.HTTPIterator`.
retry (google.api_core.retry.Retry):
Optional. How to retry the RPC.
Returns:
google.api_core.page_iterator.Iterator:
Iterator of
:class:`~google.cloud.bigquery.dataset.DatasetListItem`.
associated with the project.
"""
extra_params = {}
if project is None:
project = self.project
if include_all:
extra_params["all"] = True
if filter:
# TODO: consider supporting a dict of label -> value for filter,
# and converting it into a string here.
extra_params["filter"] = filter
path = "/projects/%s/datasets" % (project,)
return page_iterator.HTTPIterator(
client=self,
api_request=functools.partial(self._call_api, retry),
path=path,
item_to_value=_item_to_dataset,
items_key="datasets",
page_token=page_token,
max_results=max_results,
extra_params=extra_params,
) | [
"def",
"list_datasets",
"(",
"self",
",",
"project",
"=",
"None",
",",
"include_all",
"=",
"False",
",",
"filter",
"=",
"None",
",",
"max_results",
"=",
"None",
",",
"page_token",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY",
",",
")",
":",
"extra_params",
"=",
"{",
"}",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"if",
"include_all",
":",
"extra_params",
"[",
"\"all\"",
"]",
"=",
"True",
"if",
"filter",
":",
"# TODO: consider supporting a dict of label -> value for filter,",
"# and converting it into a string here.",
"extra_params",
"[",
"\"filter\"",
"]",
"=",
"filter",
"path",
"=",
"\"/projects/%s/datasets\"",
"%",
"(",
"project",
",",
")",
"return",
"page_iterator",
".",
"HTTPIterator",
"(",
"client",
"=",
"self",
",",
"api_request",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_call_api",
",",
"retry",
")",
",",
"path",
"=",
"path",
",",
"item_to_value",
"=",
"_item_to_dataset",
",",
"items_key",
"=",
"\"datasets\"",
",",
"page_token",
"=",
"page_token",
",",
"max_results",
"=",
"max_results",
",",
"extra_params",
"=",
"extra_params",
",",
")"
] | List datasets for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list
Args:
project (str):
Optional. Project ID to use for retreiving datasets. Defaults
to the client's project.
include_all (bool):
Optional. True if results include hidden datasets. Defaults
to False.
filter (str):
Optional. An expression for filtering the results by label.
For syntax, see
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list#filter.
max_results (int):
Optional. Maximum number of datasets to return.
page_token (str):
Optional. Token representing a cursor into the datasets. If
not passed, the API will return the first page of datasets.
The token marks the beginning of the iterator to be returned
and the value of the ``page_token`` can be accessed at
``next_page_token`` of the
:class:`~google.api_core.page_iterator.HTTPIterator`.
retry (google.api_core.retry.Retry):
Optional. How to retry the RPC.
Returns:
google.api_core.page_iterator.Iterator:
Iterator of
:class:`~google.cloud.bigquery.dataset.DatasetListItem`.
associated with the project. | [
"List",
"datasets",
"for",
"the",
"project",
"associated",
"with",
"this",
"client",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L229-L291 |
28,028 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.dataset | def dataset(self, dataset_id, project=None):
"""Construct a reference to a dataset.
:type dataset_id: str
:param dataset_id: ID of the dataset.
:type project: str
:param project: (Optional) project ID for the dataset (defaults to
the project of the client).
:rtype: :class:`google.cloud.bigquery.dataset.DatasetReference`
:returns: a new ``DatasetReference`` instance
"""
if project is None:
project = self.project
return DatasetReference(project, dataset_id) | python | def dataset(self, dataset_id, project=None):
"""Construct a reference to a dataset.
:type dataset_id: str
:param dataset_id: ID of the dataset.
:type project: str
:param project: (Optional) project ID for the dataset (defaults to
the project of the client).
:rtype: :class:`google.cloud.bigquery.dataset.DatasetReference`
:returns: a new ``DatasetReference`` instance
"""
if project is None:
project = self.project
return DatasetReference(project, dataset_id) | [
"def",
"dataset",
"(",
"self",
",",
"dataset_id",
",",
"project",
"=",
"None",
")",
":",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"return",
"DatasetReference",
"(",
"project",
",",
"dataset_id",
")"
] | Construct a reference to a dataset.
:type dataset_id: str
:param dataset_id: ID of the dataset.
:type project: str
:param project: (Optional) project ID for the dataset (defaults to
the project of the client).
:rtype: :class:`google.cloud.bigquery.dataset.DatasetReference`
:returns: a new ``DatasetReference`` instance | [
"Construct",
"a",
"reference",
"to",
"a",
"dataset",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L293-L309 |
28,029 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.get_dataset | def get_dataset(self, dataset_ref, retry=DEFAULT_RETRY):
"""Fetch the dataset referenced by ``dataset_ref``
Args:
dataset_ref (Union[ \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A reference to the dataset to fetch from the BigQuery API.
If a string is passed in, this method attempts to create a
dataset reference from a string using
:func:`~google.cloud.bigquery.dataset.DatasetReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.dataset.Dataset:
A ``Dataset`` instance.
"""
if isinstance(dataset_ref, str):
dataset_ref = DatasetReference.from_string(
dataset_ref, default_project=self.project
)
api_response = self._call_api(retry, method="GET", path=dataset_ref.path)
return Dataset.from_api_repr(api_response) | python | def get_dataset(self, dataset_ref, retry=DEFAULT_RETRY):
"""Fetch the dataset referenced by ``dataset_ref``
Args:
dataset_ref (Union[ \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A reference to the dataset to fetch from the BigQuery API.
If a string is passed in, this method attempts to create a
dataset reference from a string using
:func:`~google.cloud.bigquery.dataset.DatasetReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.dataset.Dataset:
A ``Dataset`` instance.
"""
if isinstance(dataset_ref, str):
dataset_ref = DatasetReference.from_string(
dataset_ref, default_project=self.project
)
api_response = self._call_api(retry, method="GET", path=dataset_ref.path)
return Dataset.from_api_repr(api_response) | [
"def",
"get_dataset",
"(",
"self",
",",
"dataset_ref",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"if",
"isinstance",
"(",
"dataset_ref",
",",
"str",
")",
":",
"dataset_ref",
"=",
"DatasetReference",
".",
"from_string",
"(",
"dataset_ref",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"api_response",
"=",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"dataset_ref",
".",
"path",
")",
"return",
"Dataset",
".",
"from_api_repr",
"(",
"api_response",
")"
] | Fetch the dataset referenced by ``dataset_ref``
Args:
dataset_ref (Union[ \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A reference to the dataset to fetch from the BigQuery API.
If a string is passed in, this method attempts to create a
dataset reference from a string using
:func:`~google.cloud.bigquery.dataset.DatasetReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.dataset.Dataset:
A ``Dataset`` instance. | [
"Fetch",
"the",
"dataset",
"referenced",
"by",
"dataset_ref"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L409-L434 |
28,030 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.get_table | def get_table(self, table, retry=DEFAULT_RETRY):
"""Fetch the table referenced by ``table``.
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
A reference to the table to fetch from the BigQuery API.
If a string is passed in, this method attempts to create a
table reference from a string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.table.Table:
A ``Table`` instance.
"""
table_ref = _table_arg_to_table_ref(table, default_project=self.project)
api_response = self._call_api(retry, method="GET", path=table_ref.path)
return Table.from_api_repr(api_response) | python | def get_table(self, table, retry=DEFAULT_RETRY):
"""Fetch the table referenced by ``table``.
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
A reference to the table to fetch from the BigQuery API.
If a string is passed in, this method attempts to create a
table reference from a string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.table.Table:
A ``Table`` instance.
"""
table_ref = _table_arg_to_table_ref(table, default_project=self.project)
api_response = self._call_api(retry, method="GET", path=table_ref.path)
return Table.from_api_repr(api_response) | [
"def",
"get_table",
"(",
"self",
",",
"table",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"table_ref",
"=",
"_table_arg_to_table_ref",
"(",
"table",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"api_response",
"=",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"table_ref",
".",
"path",
")",
"return",
"Table",
".",
"from_api_repr",
"(",
"api_response",
")"
] | Fetch the table referenced by ``table``.
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
A reference to the table to fetch from the BigQuery API.
If a string is passed in, this method attempts to create a
table reference from a string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.table.Table:
A ``Table`` instance. | [
"Fetch",
"the",
"table",
"referenced",
"by",
"table",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L463-L485 |
28,031 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.update_dataset | def update_dataset(self, dataset, fields, retry=DEFAULT_RETRY):
"""Change some fields of a dataset.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None`` in
``dataset``, it will be deleted.
If ``dataset.etag`` is not ``None``, the update will only
succeed if the dataset on the server has the same ETag. Thus
reading a dataset with ``get_dataset``, changing its fields,
and then passing it to ``update_dataset`` will ensure that the changes
will only be saved if no modifications to the dataset occurred
since the read.
Args:
dataset (google.cloud.bigquery.dataset.Dataset):
The dataset to update.
fields (Sequence[str]):
The properties of ``dataset`` to change (e.g. "friendly_name").
retry (google.api_core.retry.Retry, optional):
How to retry the RPC.
Returns:
google.cloud.bigquery.dataset.Dataset:
The modified ``Dataset`` instance.
"""
partial = dataset._build_resource(fields)
if dataset.etag is not None:
headers = {"If-Match": dataset.etag}
else:
headers = None
api_response = self._call_api(
retry, method="PATCH", path=dataset.path, data=partial, headers=headers
)
return Dataset.from_api_repr(api_response) | python | def update_dataset(self, dataset, fields, retry=DEFAULT_RETRY):
"""Change some fields of a dataset.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None`` in
``dataset``, it will be deleted.
If ``dataset.etag`` is not ``None``, the update will only
succeed if the dataset on the server has the same ETag. Thus
reading a dataset with ``get_dataset``, changing its fields,
and then passing it to ``update_dataset`` will ensure that the changes
will only be saved if no modifications to the dataset occurred
since the read.
Args:
dataset (google.cloud.bigquery.dataset.Dataset):
The dataset to update.
fields (Sequence[str]):
The properties of ``dataset`` to change (e.g. "friendly_name").
retry (google.api_core.retry.Retry, optional):
How to retry the RPC.
Returns:
google.cloud.bigquery.dataset.Dataset:
The modified ``Dataset`` instance.
"""
partial = dataset._build_resource(fields)
if dataset.etag is not None:
headers = {"If-Match": dataset.etag}
else:
headers = None
api_response = self._call_api(
retry, method="PATCH", path=dataset.path, data=partial, headers=headers
)
return Dataset.from_api_repr(api_response) | [
"def",
"update_dataset",
"(",
"self",
",",
"dataset",
",",
"fields",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"partial",
"=",
"dataset",
".",
"_build_resource",
"(",
"fields",
")",
"if",
"dataset",
".",
"etag",
"is",
"not",
"None",
":",
"headers",
"=",
"{",
"\"If-Match\"",
":",
"dataset",
".",
"etag",
"}",
"else",
":",
"headers",
"=",
"None",
"api_response",
"=",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"PATCH\"",
",",
"path",
"=",
"dataset",
".",
"path",
",",
"data",
"=",
"partial",
",",
"headers",
"=",
"headers",
")",
"return",
"Dataset",
".",
"from_api_repr",
"(",
"api_response",
")"
] | Change some fields of a dataset.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None`` in
``dataset``, it will be deleted.
If ``dataset.etag`` is not ``None``, the update will only
succeed if the dataset on the server has the same ETag. Thus
reading a dataset with ``get_dataset``, changing its fields,
and then passing it to ``update_dataset`` will ensure that the changes
will only be saved if no modifications to the dataset occurred
since the read.
Args:
dataset (google.cloud.bigquery.dataset.Dataset):
The dataset to update.
fields (Sequence[str]):
The properties of ``dataset`` to change (e.g. "friendly_name").
retry (google.api_core.retry.Retry, optional):
How to retry the RPC.
Returns:
google.cloud.bigquery.dataset.Dataset:
The modified ``Dataset`` instance. | [
"Change",
"some",
"fields",
"of",
"a",
"dataset",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L487-L521 |
28,032 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.update_table | def update_table(self, table, fields, retry=DEFAULT_RETRY):
"""Change some fields of a table.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None``
in ``table``, it will be deleted.
If ``table.etag`` is not ``None``, the update will only succeed if
the table on the server has the same ETag. Thus reading a table with
``get_table``, changing its fields, and then passing it to
``update_table`` will ensure that the changes will only be saved if
no modifications to the table occurred since the read.
Args:
table (google.cloud.bigquery.table.Table): The table to update.
fields (Sequence[str]):
The fields of ``table`` to change, spelled as the Table
properties (e.g. "friendly_name").
retry (google.api_core.retry.Retry):
(Optional) A description of how to retry the API call.
Returns:
google.cloud.bigquery.table.Table:
The table resource returned from the API call.
"""
partial = table._build_resource(fields)
if table.etag is not None:
headers = {"If-Match": table.etag}
else:
headers = None
api_response = self._call_api(
retry, method="PATCH", path=table.path, data=partial, headers=headers
)
return Table.from_api_repr(api_response) | python | def update_table(self, table, fields, retry=DEFAULT_RETRY):
"""Change some fields of a table.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None``
in ``table``, it will be deleted.
If ``table.etag`` is not ``None``, the update will only succeed if
the table on the server has the same ETag. Thus reading a table with
``get_table``, changing its fields, and then passing it to
``update_table`` will ensure that the changes will only be saved if
no modifications to the table occurred since the read.
Args:
table (google.cloud.bigquery.table.Table): The table to update.
fields (Sequence[str]):
The fields of ``table`` to change, spelled as the Table
properties (e.g. "friendly_name").
retry (google.api_core.retry.Retry):
(Optional) A description of how to retry the API call.
Returns:
google.cloud.bigquery.table.Table:
The table resource returned from the API call.
"""
partial = table._build_resource(fields)
if table.etag is not None:
headers = {"If-Match": table.etag}
else:
headers = None
api_response = self._call_api(
retry, method="PATCH", path=table.path, data=partial, headers=headers
)
return Table.from_api_repr(api_response) | [
"def",
"update_table",
"(",
"self",
",",
"table",
",",
"fields",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"partial",
"=",
"table",
".",
"_build_resource",
"(",
"fields",
")",
"if",
"table",
".",
"etag",
"is",
"not",
"None",
":",
"headers",
"=",
"{",
"\"If-Match\"",
":",
"table",
".",
"etag",
"}",
"else",
":",
"headers",
"=",
"None",
"api_response",
"=",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"PATCH\"",
",",
"path",
"=",
"table",
".",
"path",
",",
"data",
"=",
"partial",
",",
"headers",
"=",
"headers",
")",
"return",
"Table",
".",
"from_api_repr",
"(",
"api_response",
")"
] | Change some fields of a table.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None``
in ``table``, it will be deleted.
If ``table.etag`` is not ``None``, the update will only succeed if
the table on the server has the same ETag. Thus reading a table with
``get_table``, changing its fields, and then passing it to
``update_table`` will ensure that the changes will only be saved if
no modifications to the table occurred since the read.
Args:
table (google.cloud.bigquery.table.Table): The table to update.
fields (Sequence[str]):
The fields of ``table`` to change, spelled as the Table
properties (e.g. "friendly_name").
retry (google.api_core.retry.Retry):
(Optional) A description of how to retry the API call.
Returns:
google.cloud.bigquery.table.Table:
The table resource returned from the API call. | [
"Change",
"some",
"fields",
"of",
"a",
"table",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L558-L591 |
28,033 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client._get_query_results | def _get_query_results(
self, job_id, retry, project=None, timeout_ms=None, location=None
):
"""Get the query results object for a query job.
Arguments:
job_id (str): Name of the query job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
project (str):
(Optional) project ID for the query job (defaults to the
project of the client).
timeout_ms (int):
(Optional) number of milliseconds the the API call should
wait for the query to complete before the request times out.
location (str): Location of the query job.
Returns:
google.cloud.bigquery.query._QueryResults:
A new ``_QueryResults`` instance.
"""
extra_params = {"maxResults": 0}
if project is None:
project = self.project
if timeout_ms is not None:
extra_params["timeoutMs"] = timeout_ms
if location is None:
location = self.location
if location is not None:
extra_params["location"] = location
path = "/projects/{}/queries/{}".format(project, job_id)
# This call is typically made in a polling loop that checks whether the
# job is complete (from QueryJob.done(), called ultimately from
# QueryJob.result()). So we don't need to poll here.
resource = self._call_api(
retry, method="GET", path=path, query_params=extra_params
)
return _QueryResults.from_api_repr(resource) | python | def _get_query_results(
self, job_id, retry, project=None, timeout_ms=None, location=None
):
"""Get the query results object for a query job.
Arguments:
job_id (str): Name of the query job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
project (str):
(Optional) project ID for the query job (defaults to the
project of the client).
timeout_ms (int):
(Optional) number of milliseconds the the API call should
wait for the query to complete before the request times out.
location (str): Location of the query job.
Returns:
google.cloud.bigquery.query._QueryResults:
A new ``_QueryResults`` instance.
"""
extra_params = {"maxResults": 0}
if project is None:
project = self.project
if timeout_ms is not None:
extra_params["timeoutMs"] = timeout_ms
if location is None:
location = self.location
if location is not None:
extra_params["location"] = location
path = "/projects/{}/queries/{}".format(project, job_id)
# This call is typically made in a polling loop that checks whether the
# job is complete (from QueryJob.done(), called ultimately from
# QueryJob.result()). So we don't need to poll here.
resource = self._call_api(
retry, method="GET", path=path, query_params=extra_params
)
return _QueryResults.from_api_repr(resource) | [
"def",
"_get_query_results",
"(",
"self",
",",
"job_id",
",",
"retry",
",",
"project",
"=",
"None",
",",
"timeout_ms",
"=",
"None",
",",
"location",
"=",
"None",
")",
":",
"extra_params",
"=",
"{",
"\"maxResults\"",
":",
"0",
"}",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"if",
"timeout_ms",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"timeoutMs\"",
"]",
"=",
"timeout_ms",
"if",
"location",
"is",
"None",
":",
"location",
"=",
"self",
".",
"location",
"if",
"location",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"location\"",
"]",
"=",
"location",
"path",
"=",
"\"/projects/{}/queries/{}\"",
".",
"format",
"(",
"project",
",",
"job_id",
")",
"# This call is typically made in a polling loop that checks whether the",
"# job is complete (from QueryJob.done(), called ultimately from",
"# QueryJob.result()). So we don't need to poll here.",
"resource",
"=",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"path",
",",
"query_params",
"=",
"extra_params",
")",
"return",
"_QueryResults",
".",
"from_api_repr",
"(",
"resource",
")"
] | Get the query results object for a query job.
Arguments:
job_id (str): Name of the query job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
project (str):
(Optional) project ID for the query job (defaults to the
project of the client).
timeout_ms (int):
(Optional) number of milliseconds the the API call should
wait for the query to complete before the request times out.
location (str): Location of the query job.
Returns:
google.cloud.bigquery.query._QueryResults:
A new ``_QueryResults`` instance. | [
"Get",
"the",
"query",
"results",
"object",
"for",
"a",
"query",
"job",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L823-L867 |
28,034 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.job_from_resource | def job_from_resource(self, resource):
"""Detect correct job type from resource and instantiate.
:type resource: dict
:param resource: one job resource from API response
:rtype: One of:
:class:`google.cloud.bigquery.job.LoadJob`,
:class:`google.cloud.bigquery.job.CopyJob`,
:class:`google.cloud.bigquery.job.ExtractJob`,
or :class:`google.cloud.bigquery.job.QueryJob`
:returns: the job instance, constructed via the resource
"""
config = resource.get("configuration", {})
if "load" in config:
return job.LoadJob.from_api_repr(resource, self)
elif "copy" in config:
return job.CopyJob.from_api_repr(resource, self)
elif "extract" in config:
return job.ExtractJob.from_api_repr(resource, self)
elif "query" in config:
return job.QueryJob.from_api_repr(resource, self)
return job.UnknownJob.from_api_repr(resource, self) | python | def job_from_resource(self, resource):
"""Detect correct job type from resource and instantiate.
:type resource: dict
:param resource: one job resource from API response
:rtype: One of:
:class:`google.cloud.bigquery.job.LoadJob`,
:class:`google.cloud.bigquery.job.CopyJob`,
:class:`google.cloud.bigquery.job.ExtractJob`,
or :class:`google.cloud.bigquery.job.QueryJob`
:returns: the job instance, constructed via the resource
"""
config = resource.get("configuration", {})
if "load" in config:
return job.LoadJob.from_api_repr(resource, self)
elif "copy" in config:
return job.CopyJob.from_api_repr(resource, self)
elif "extract" in config:
return job.ExtractJob.from_api_repr(resource, self)
elif "query" in config:
return job.QueryJob.from_api_repr(resource, self)
return job.UnknownJob.from_api_repr(resource, self) | [
"def",
"job_from_resource",
"(",
"self",
",",
"resource",
")",
":",
"config",
"=",
"resource",
".",
"get",
"(",
"\"configuration\"",
",",
"{",
"}",
")",
"if",
"\"load\"",
"in",
"config",
":",
"return",
"job",
".",
"LoadJob",
".",
"from_api_repr",
"(",
"resource",
",",
"self",
")",
"elif",
"\"copy\"",
"in",
"config",
":",
"return",
"job",
".",
"CopyJob",
".",
"from_api_repr",
"(",
"resource",
",",
"self",
")",
"elif",
"\"extract\"",
"in",
"config",
":",
"return",
"job",
".",
"ExtractJob",
".",
"from_api_repr",
"(",
"resource",
",",
"self",
")",
"elif",
"\"query\"",
"in",
"config",
":",
"return",
"job",
".",
"QueryJob",
".",
"from_api_repr",
"(",
"resource",
",",
"self",
")",
"return",
"job",
".",
"UnknownJob",
".",
"from_api_repr",
"(",
"resource",
",",
"self",
")"
] | Detect correct job type from resource and instantiate.
:type resource: dict
:param resource: one job resource from API response
:rtype: One of:
:class:`google.cloud.bigquery.job.LoadJob`,
:class:`google.cloud.bigquery.job.CopyJob`,
:class:`google.cloud.bigquery.job.ExtractJob`,
or :class:`google.cloud.bigquery.job.QueryJob`
:returns: the job instance, constructed via the resource | [
"Detect",
"correct",
"job",
"type",
"from",
"resource",
"and",
"instantiate",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L869-L891 |
28,035 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.cancel_job | def cancel_job(self, job_id, project=None, location=None, retry=DEFAULT_RETRY):
"""Attempt to cancel a job from a job ID.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel
Arguments:
job_id (str): Unique job identifier.
Keyword Arguments:
project (str):
(Optional) ID of the project which owns the job (defaults to
the client's project).
location (str): Location where the job was run.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
Union[google.cloud.bigquery.job.LoadJob, \
google.cloud.bigquery.job.CopyJob, \
google.cloud.bigquery.job.ExtractJob, \
google.cloud.bigquery.job.QueryJob]:
Job instance, based on the resource returned by the API.
"""
extra_params = {"projection": "full"}
if project is None:
project = self.project
if location is None:
location = self.location
if location is not None:
extra_params["location"] = location
path = "/projects/{}/jobs/{}/cancel".format(project, job_id)
resource = self._call_api(
retry, method="POST", path=path, query_params=extra_params
)
return self.job_from_resource(resource["job"]) | python | def cancel_job(self, job_id, project=None, location=None, retry=DEFAULT_RETRY):
"""Attempt to cancel a job from a job ID.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel
Arguments:
job_id (str): Unique job identifier.
Keyword Arguments:
project (str):
(Optional) ID of the project which owns the job (defaults to
the client's project).
location (str): Location where the job was run.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
Union[google.cloud.bigquery.job.LoadJob, \
google.cloud.bigquery.job.CopyJob, \
google.cloud.bigquery.job.ExtractJob, \
google.cloud.bigquery.job.QueryJob]:
Job instance, based on the resource returned by the API.
"""
extra_params = {"projection": "full"}
if project is None:
project = self.project
if location is None:
location = self.location
if location is not None:
extra_params["location"] = location
path = "/projects/{}/jobs/{}/cancel".format(project, job_id)
resource = self._call_api(
retry, method="POST", path=path, query_params=extra_params
)
return self.job_from_resource(resource["job"]) | [
"def",
"cancel_job",
"(",
"self",
",",
"job_id",
",",
"project",
"=",
"None",
",",
"location",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"extra_params",
"=",
"{",
"\"projection\"",
":",
"\"full\"",
"}",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"if",
"location",
"is",
"None",
":",
"location",
"=",
"self",
".",
"location",
"if",
"location",
"is",
"not",
"None",
":",
"extra_params",
"[",
"\"location\"",
"]",
"=",
"location",
"path",
"=",
"\"/projects/{}/jobs/{}/cancel\"",
".",
"format",
"(",
"project",
",",
"job_id",
")",
"resource",
"=",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"path",
",",
"query_params",
"=",
"extra_params",
")",
"return",
"self",
".",
"job_from_resource",
"(",
"resource",
"[",
"\"job\"",
"]",
")"
] | Attempt to cancel a job from a job ID.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel
Arguments:
job_id (str): Unique job identifier.
Keyword Arguments:
project (str):
(Optional) ID of the project which owns the job (defaults to
the client's project).
location (str): Location where the job was run.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
Union[google.cloud.bigquery.job.LoadJob, \
google.cloud.bigquery.job.CopyJob, \
google.cloud.bigquery.job.ExtractJob, \
google.cloud.bigquery.job.QueryJob]:
Job instance, based on the resource returned by the API. | [
"Attempt",
"to",
"cancel",
"a",
"job",
"from",
"a",
"job",
"ID",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L936-L977 |
28,036 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.list_jobs | def list_jobs(
self,
project=None,
max_results=None,
page_token=None,
all_users=None,
state_filter=None,
retry=DEFAULT_RETRY,
min_creation_time=None,
max_creation_time=None,
):
"""List jobs for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/list
Args:
project (str, optional):
Project ID to use for retreiving datasets. Defaults
to the client's project.
max_results (int, optional):
Maximum number of jobs to return.
page_token (str, optional):
Opaque marker for the next "page" of jobs. If not
passed, the API will return the first page of jobs. The token
marks the beginning of the iterator to be returned and the
value of the ``page_token`` can be accessed at
``next_page_token`` of
:class:`~google.api_core.page_iterator.HTTPIterator`.
all_users (bool, optional):
If true, include jobs owned by all users in the project.
Defaults to :data:`False`.
state_filter (str, optional):
If set, include only jobs matching the given state. One of:
* ``"done"``
* ``"pending"``
* ``"running"``
retry (google.api_core.retry.Retry, optional):
How to retry the RPC.
min_creation_time (datetime.datetime, optional):
Min value for job creation time. If set, only jobs created
after or at this timestamp are returned. If the datetime has
no time zone assumes UTC time.
max_creation_time (datetime.datetime, optional):
Max value for job creation time. If set, only jobs created
before or at this timestamp are returned. If the datetime has
no time zone assumes UTC time.
Returns:
google.api_core.page_iterator.Iterator:
Iterable of job instances.
"""
extra_params = {
"allUsers": all_users,
"stateFilter": state_filter,
"minCreationTime": _str_or_none(
google.cloud._helpers._millis_from_datetime(min_creation_time)
),
"maxCreationTime": _str_or_none(
google.cloud._helpers._millis_from_datetime(max_creation_time)
),
"projection": "full",
}
extra_params = {
param: value for param, value in extra_params.items() if value is not None
}
if project is None:
project = self.project
path = "/projects/%s/jobs" % (project,)
return page_iterator.HTTPIterator(
client=self,
api_request=functools.partial(self._call_api, retry),
path=path,
item_to_value=_item_to_job,
items_key="jobs",
page_token=page_token,
max_results=max_results,
extra_params=extra_params,
) | python | def list_jobs(
self,
project=None,
max_results=None,
page_token=None,
all_users=None,
state_filter=None,
retry=DEFAULT_RETRY,
min_creation_time=None,
max_creation_time=None,
):
"""List jobs for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/list
Args:
project (str, optional):
Project ID to use for retreiving datasets. Defaults
to the client's project.
max_results (int, optional):
Maximum number of jobs to return.
page_token (str, optional):
Opaque marker for the next "page" of jobs. If not
passed, the API will return the first page of jobs. The token
marks the beginning of the iterator to be returned and the
value of the ``page_token`` can be accessed at
``next_page_token`` of
:class:`~google.api_core.page_iterator.HTTPIterator`.
all_users (bool, optional):
If true, include jobs owned by all users in the project.
Defaults to :data:`False`.
state_filter (str, optional):
If set, include only jobs matching the given state. One of:
* ``"done"``
* ``"pending"``
* ``"running"``
retry (google.api_core.retry.Retry, optional):
How to retry the RPC.
min_creation_time (datetime.datetime, optional):
Min value for job creation time. If set, only jobs created
after or at this timestamp are returned. If the datetime has
no time zone assumes UTC time.
max_creation_time (datetime.datetime, optional):
Max value for job creation time. If set, only jobs created
before or at this timestamp are returned. If the datetime has
no time zone assumes UTC time.
Returns:
google.api_core.page_iterator.Iterator:
Iterable of job instances.
"""
extra_params = {
"allUsers": all_users,
"stateFilter": state_filter,
"minCreationTime": _str_or_none(
google.cloud._helpers._millis_from_datetime(min_creation_time)
),
"maxCreationTime": _str_or_none(
google.cloud._helpers._millis_from_datetime(max_creation_time)
),
"projection": "full",
}
extra_params = {
param: value for param, value in extra_params.items() if value is not None
}
if project is None:
project = self.project
path = "/projects/%s/jobs" % (project,)
return page_iterator.HTTPIterator(
client=self,
api_request=functools.partial(self._call_api, retry),
path=path,
item_to_value=_item_to_job,
items_key="jobs",
page_token=page_token,
max_results=max_results,
extra_params=extra_params,
) | [
"def",
"list_jobs",
"(",
"self",
",",
"project",
"=",
"None",
",",
"max_results",
"=",
"None",
",",
"page_token",
"=",
"None",
",",
"all_users",
"=",
"None",
",",
"state_filter",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY",
",",
"min_creation_time",
"=",
"None",
",",
"max_creation_time",
"=",
"None",
",",
")",
":",
"extra_params",
"=",
"{",
"\"allUsers\"",
":",
"all_users",
",",
"\"stateFilter\"",
":",
"state_filter",
",",
"\"minCreationTime\"",
":",
"_str_or_none",
"(",
"google",
".",
"cloud",
".",
"_helpers",
".",
"_millis_from_datetime",
"(",
"min_creation_time",
")",
")",
",",
"\"maxCreationTime\"",
":",
"_str_or_none",
"(",
"google",
".",
"cloud",
".",
"_helpers",
".",
"_millis_from_datetime",
"(",
"max_creation_time",
")",
")",
",",
"\"projection\"",
":",
"\"full\"",
",",
"}",
"extra_params",
"=",
"{",
"param",
":",
"value",
"for",
"param",
",",
"value",
"in",
"extra_params",
".",
"items",
"(",
")",
"if",
"value",
"is",
"not",
"None",
"}",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"path",
"=",
"\"/projects/%s/jobs\"",
"%",
"(",
"project",
",",
")",
"return",
"page_iterator",
".",
"HTTPIterator",
"(",
"client",
"=",
"self",
",",
"api_request",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_call_api",
",",
"retry",
")",
",",
"path",
"=",
"path",
",",
"item_to_value",
"=",
"_item_to_job",
",",
"items_key",
"=",
"\"jobs\"",
",",
"page_token",
"=",
"page_token",
",",
"max_results",
"=",
"max_results",
",",
"extra_params",
"=",
"extra_params",
",",
")"
] | List jobs for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/list
Args:
project (str, optional):
Project ID to use for retreiving datasets. Defaults
to the client's project.
max_results (int, optional):
Maximum number of jobs to return.
page_token (str, optional):
Opaque marker for the next "page" of jobs. If not
passed, the API will return the first page of jobs. The token
marks the beginning of the iterator to be returned and the
value of the ``page_token`` can be accessed at
``next_page_token`` of
:class:`~google.api_core.page_iterator.HTTPIterator`.
all_users (bool, optional):
If true, include jobs owned by all users in the project.
Defaults to :data:`False`.
state_filter (str, optional):
If set, include only jobs matching the given state. One of:
* ``"done"``
* ``"pending"``
* ``"running"``
retry (google.api_core.retry.Retry, optional):
How to retry the RPC.
min_creation_time (datetime.datetime, optional):
Min value for job creation time. If set, only jobs created
after or at this timestamp are returned. If the datetime has
no time zone assumes UTC time.
max_creation_time (datetime.datetime, optional):
Max value for job creation time. If set, only jobs created
before or at this timestamp are returned. If the datetime has
no time zone assumes UTC time.
Returns:
google.api_core.page_iterator.Iterator:
Iterable of job instances. | [
"List",
"jobs",
"for",
"the",
"project",
"associated",
"with",
"this",
"client",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L979-L1060 |
28,037 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.load_table_from_uri | def load_table_from_uri(
self,
source_uris,
destination,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
retry=DEFAULT_RETRY,
):
"""Starts a job for loading data into a table from CloudStorage.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load
Arguments:
source_uris (Union[str, Sequence[str]]):
URIs of data files to be loaded; in format
``gs://<bucket_name>/<object_name_or_glob>``.
destination (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
Table into which data is to be loaded. If a string is passed
in, this method attempts to create a table reference from a
string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
Keyword Arguments:
job_id (str): (Optional) Name of the job.
job_id_prefix (str):
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.LoadJobConfig):
(Optional) Extra configuration options for the job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.job.LoadJob: A new load job.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
job_ref = job._JobReference(job_id, project=project, location=location)
if isinstance(source_uris, six.string_types):
source_uris = [source_uris]
destination = _table_arg_to_table_ref(destination, default_project=self.project)
load_job = job.LoadJob(job_ref, source_uris, destination, self, job_config)
load_job._begin(retry=retry)
return load_job | python | def load_table_from_uri(
self,
source_uris,
destination,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
retry=DEFAULT_RETRY,
):
"""Starts a job for loading data into a table from CloudStorage.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load
Arguments:
source_uris (Union[str, Sequence[str]]):
URIs of data files to be loaded; in format
``gs://<bucket_name>/<object_name_or_glob>``.
destination (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
Table into which data is to be loaded. If a string is passed
in, this method attempts to create a table reference from a
string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
Keyword Arguments:
job_id (str): (Optional) Name of the job.
job_id_prefix (str):
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.LoadJobConfig):
(Optional) Extra configuration options for the job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.job.LoadJob: A new load job.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
job_ref = job._JobReference(job_id, project=project, location=location)
if isinstance(source_uris, six.string_types):
source_uris = [source_uris]
destination = _table_arg_to_table_ref(destination, default_project=self.project)
load_job = job.LoadJob(job_ref, source_uris, destination, self, job_config)
load_job._begin(retry=retry)
return load_job | [
"def",
"load_table_from_uri",
"(",
"self",
",",
"source_uris",
",",
"destination",
",",
"job_id",
"=",
"None",
",",
"job_id_prefix",
"=",
"None",
",",
"location",
"=",
"None",
",",
"project",
"=",
"None",
",",
"job_config",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY",
",",
")",
":",
"job_id",
"=",
"_make_job_id",
"(",
"job_id",
",",
"job_id_prefix",
")",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"if",
"location",
"is",
"None",
":",
"location",
"=",
"self",
".",
"location",
"job_ref",
"=",
"job",
".",
"_JobReference",
"(",
"job_id",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
")",
"if",
"isinstance",
"(",
"source_uris",
",",
"six",
".",
"string_types",
")",
":",
"source_uris",
"=",
"[",
"source_uris",
"]",
"destination",
"=",
"_table_arg_to_table_ref",
"(",
"destination",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"load_job",
"=",
"job",
".",
"LoadJob",
"(",
"job_ref",
",",
"source_uris",
",",
"destination",
",",
"self",
",",
"job_config",
")",
"load_job",
".",
"_begin",
"(",
"retry",
"=",
"retry",
")",
"return",
"load_job"
] | Starts a job for loading data into a table from CloudStorage.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load
Arguments:
source_uris (Union[str, Sequence[str]]):
URIs of data files to be loaded; in format
``gs://<bucket_name>/<object_name_or_glob>``.
destination (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
Table into which data is to be loaded. If a string is passed
in, this method attempts to create a table reference from a
string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
Keyword Arguments:
job_id (str): (Optional) Name of the job.
job_id_prefix (str):
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.LoadJobConfig):
(Optional) Extra configuration options for the job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.job.LoadJob: A new load job. | [
"Starts",
"a",
"job",
"for",
"loading",
"data",
"into",
"a",
"table",
"from",
"CloudStorage",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1062-L1129 |
28,038 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.load_table_from_file | def load_table_from_file(
self,
file_obj,
destination,
rewind=False,
size=None,
num_retries=_DEFAULT_NUM_RETRIES,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
):
"""Upload the contents of this table from a file-like object.
Similar to :meth:`load_table_from_uri`, this method creates, starts and
returns a :class:`~google.cloud.bigquery.job.LoadJob`.
Arguments:
file_obj (file): A file handle opened in binary mode for reading.
destination (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
Table into which data is to be loaded. If a string is passed
in, this method attempts to create a table reference from a
string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
Keyword Arguments:
rewind (bool):
If True, seek to the beginning of the file handle before
reading the file.
size (int):
The number of bytes to read from the file handle. If size is
``None`` or large, resumable upload will be used. Otherwise,
multipart upload will be used.
num_retries (int): Number of upload retries. Defaults to 6.
job_id (str): (Optional) Name of the job.
job_id_prefix (str):
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.LoadJobConfig):
(Optional) Extra configuration options for the job.
Returns:
google.cloud.bigquery.job.LoadJob: A new load job.
Raises:
ValueError:
If ``size`` is not passed in and can not be determined, or if
the ``file_obj`` can be detected to be a file opened in text
mode.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
destination = _table_arg_to_table_ref(destination, default_project=self.project)
job_ref = job._JobReference(job_id, project=project, location=location)
load_job = job.LoadJob(job_ref, None, destination, self, job_config)
job_resource = load_job.to_api_repr()
if rewind:
file_obj.seek(0, os.SEEK_SET)
_check_mode(file_obj)
try:
if size is None or size >= _MAX_MULTIPART_SIZE:
response = self._do_resumable_upload(
file_obj, job_resource, num_retries
)
else:
response = self._do_multipart_upload(
file_obj, job_resource, size, num_retries
)
except resumable_media.InvalidResponse as exc:
raise exceptions.from_http_response(exc.response)
return self.job_from_resource(response.json()) | python | def load_table_from_file(
self,
file_obj,
destination,
rewind=False,
size=None,
num_retries=_DEFAULT_NUM_RETRIES,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
):
"""Upload the contents of this table from a file-like object.
Similar to :meth:`load_table_from_uri`, this method creates, starts and
returns a :class:`~google.cloud.bigquery.job.LoadJob`.
Arguments:
file_obj (file): A file handle opened in binary mode for reading.
destination (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
Table into which data is to be loaded. If a string is passed
in, this method attempts to create a table reference from a
string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
Keyword Arguments:
rewind (bool):
If True, seek to the beginning of the file handle before
reading the file.
size (int):
The number of bytes to read from the file handle. If size is
``None`` or large, resumable upload will be used. Otherwise,
multipart upload will be used.
num_retries (int): Number of upload retries. Defaults to 6.
job_id (str): (Optional) Name of the job.
job_id_prefix (str):
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.LoadJobConfig):
(Optional) Extra configuration options for the job.
Returns:
google.cloud.bigquery.job.LoadJob: A new load job.
Raises:
ValueError:
If ``size`` is not passed in and can not be determined, or if
the ``file_obj`` can be detected to be a file opened in text
mode.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
destination = _table_arg_to_table_ref(destination, default_project=self.project)
job_ref = job._JobReference(job_id, project=project, location=location)
load_job = job.LoadJob(job_ref, None, destination, self, job_config)
job_resource = load_job.to_api_repr()
if rewind:
file_obj.seek(0, os.SEEK_SET)
_check_mode(file_obj)
try:
if size is None or size >= _MAX_MULTIPART_SIZE:
response = self._do_resumable_upload(
file_obj, job_resource, num_retries
)
else:
response = self._do_multipart_upload(
file_obj, job_resource, size, num_retries
)
except resumable_media.InvalidResponse as exc:
raise exceptions.from_http_response(exc.response)
return self.job_from_resource(response.json()) | [
"def",
"load_table_from_file",
"(",
"self",
",",
"file_obj",
",",
"destination",
",",
"rewind",
"=",
"False",
",",
"size",
"=",
"None",
",",
"num_retries",
"=",
"_DEFAULT_NUM_RETRIES",
",",
"job_id",
"=",
"None",
",",
"job_id_prefix",
"=",
"None",
",",
"location",
"=",
"None",
",",
"project",
"=",
"None",
",",
"job_config",
"=",
"None",
",",
")",
":",
"job_id",
"=",
"_make_job_id",
"(",
"job_id",
",",
"job_id_prefix",
")",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"if",
"location",
"is",
"None",
":",
"location",
"=",
"self",
".",
"location",
"destination",
"=",
"_table_arg_to_table_ref",
"(",
"destination",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"job_ref",
"=",
"job",
".",
"_JobReference",
"(",
"job_id",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
")",
"load_job",
"=",
"job",
".",
"LoadJob",
"(",
"job_ref",
",",
"None",
",",
"destination",
",",
"self",
",",
"job_config",
")",
"job_resource",
"=",
"load_job",
".",
"to_api_repr",
"(",
")",
"if",
"rewind",
":",
"file_obj",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"_check_mode",
"(",
"file_obj",
")",
"try",
":",
"if",
"size",
"is",
"None",
"or",
"size",
">=",
"_MAX_MULTIPART_SIZE",
":",
"response",
"=",
"self",
".",
"_do_resumable_upload",
"(",
"file_obj",
",",
"job_resource",
",",
"num_retries",
")",
"else",
":",
"response",
"=",
"self",
".",
"_do_multipart_upload",
"(",
"file_obj",
",",
"job_resource",
",",
"size",
",",
"num_retries",
")",
"except",
"resumable_media",
".",
"InvalidResponse",
"as",
"exc",
":",
"raise",
"exceptions",
".",
"from_http_response",
"(",
"exc",
".",
"response",
")",
"return",
"self",
".",
"job_from_resource",
"(",
"response",
".",
"json",
"(",
")",
")"
] | Upload the contents of this table from a file-like object.
Similar to :meth:`load_table_from_uri`, this method creates, starts and
returns a :class:`~google.cloud.bigquery.job.LoadJob`.
Arguments:
file_obj (file): A file handle opened in binary mode for reading.
destination (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
Table into which data is to be loaded. If a string is passed
in, this method attempts to create a table reference from a
string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
Keyword Arguments:
rewind (bool):
If True, seek to the beginning of the file handle before
reading the file.
size (int):
The number of bytes to read from the file handle. If size is
``None`` or large, resumable upload will be used. Otherwise,
multipart upload will be used.
num_retries (int): Number of upload retries. Defaults to 6.
job_id (str): (Optional) Name of the job.
job_id_prefix (str):
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.LoadJobConfig):
(Optional) Extra configuration options for the job.
Returns:
google.cloud.bigquery.job.LoadJob: A new load job.
Raises:
ValueError:
If ``size`` is not passed in and can not be determined, or if
the ``file_obj`` can be detected to be a file opened in text
mode. | [
"Upload",
"the",
"contents",
"of",
"this",
"table",
"from",
"a",
"file",
"-",
"like",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1131-L1223 |
28,039 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.load_table_from_dataframe | def load_table_from_dataframe(
self,
dataframe,
destination,
num_retries=_DEFAULT_NUM_RETRIES,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
):
"""Upload the contents of a table from a pandas DataFrame.
Similar to :meth:`load_table_from_uri`, this method creates, starts and
returns a :class:`~google.cloud.bigquery.job.LoadJob`.
Arguments:
dataframe (pandas.DataFrame):
A :class:`~pandas.DataFrame` containing the data to load.
destination (google.cloud.bigquery.table.TableReference):
The destination table to use for loading the data. If it is an
existing table, the schema of the :class:`~pandas.DataFrame`
must match the schema of the destination table. If the table
does not yet exist, the schema is inferred from the
:class:`~pandas.DataFrame`.
If a string is passed in, this method attempts to create a
table reference from a string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
Keyword Arguments:
num_retries (int, optional): Number of upload retries.
job_id (str, optional): Name of the job.
job_id_prefix (str, optional):
The user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
destination table.
project (str, optional):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.LoadJobConfig, optional):
Extra configuration options for the job.
Returns:
google.cloud.bigquery.job.LoadJob: A new load job.
Raises:
ImportError:
If a usable parquet engine cannot be found. This method
requires :mod:`pyarrow` or :mod:`fastparquet` to be
installed.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if job_config is None:
job_config = job.LoadJobConfig()
job_config.source_format = job.SourceFormat.PARQUET
if location is None:
location = self.location
tmpfd, tmppath = tempfile.mkstemp(suffix="_job_{}.parquet".format(job_id[:8]))
os.close(tmpfd)
try:
dataframe.to_parquet(tmppath)
with open(tmppath, "rb") as parquet_file:
return self.load_table_from_file(
parquet_file,
destination,
num_retries=num_retries,
rewind=True,
job_id=job_id,
job_id_prefix=job_id_prefix,
location=location,
project=project,
job_config=job_config,
)
finally:
os.remove(tmppath) | python | def load_table_from_dataframe(
self,
dataframe,
destination,
num_retries=_DEFAULT_NUM_RETRIES,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
):
"""Upload the contents of a table from a pandas DataFrame.
Similar to :meth:`load_table_from_uri`, this method creates, starts and
returns a :class:`~google.cloud.bigquery.job.LoadJob`.
Arguments:
dataframe (pandas.DataFrame):
A :class:`~pandas.DataFrame` containing the data to load.
destination (google.cloud.bigquery.table.TableReference):
The destination table to use for loading the data. If it is an
existing table, the schema of the :class:`~pandas.DataFrame`
must match the schema of the destination table. If the table
does not yet exist, the schema is inferred from the
:class:`~pandas.DataFrame`.
If a string is passed in, this method attempts to create a
table reference from a string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
Keyword Arguments:
num_retries (int, optional): Number of upload retries.
job_id (str, optional): Name of the job.
job_id_prefix (str, optional):
The user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
destination table.
project (str, optional):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.LoadJobConfig, optional):
Extra configuration options for the job.
Returns:
google.cloud.bigquery.job.LoadJob: A new load job.
Raises:
ImportError:
If a usable parquet engine cannot be found. This method
requires :mod:`pyarrow` or :mod:`fastparquet` to be
installed.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if job_config is None:
job_config = job.LoadJobConfig()
job_config.source_format = job.SourceFormat.PARQUET
if location is None:
location = self.location
tmpfd, tmppath = tempfile.mkstemp(suffix="_job_{}.parquet".format(job_id[:8]))
os.close(tmpfd)
try:
dataframe.to_parquet(tmppath)
with open(tmppath, "rb") as parquet_file:
return self.load_table_from_file(
parquet_file,
destination,
num_retries=num_retries,
rewind=True,
job_id=job_id,
job_id_prefix=job_id_prefix,
location=location,
project=project,
job_config=job_config,
)
finally:
os.remove(tmppath) | [
"def",
"load_table_from_dataframe",
"(",
"self",
",",
"dataframe",
",",
"destination",
",",
"num_retries",
"=",
"_DEFAULT_NUM_RETRIES",
",",
"job_id",
"=",
"None",
",",
"job_id_prefix",
"=",
"None",
",",
"location",
"=",
"None",
",",
"project",
"=",
"None",
",",
"job_config",
"=",
"None",
",",
")",
":",
"job_id",
"=",
"_make_job_id",
"(",
"job_id",
",",
"job_id_prefix",
")",
"if",
"job_config",
"is",
"None",
":",
"job_config",
"=",
"job",
".",
"LoadJobConfig",
"(",
")",
"job_config",
".",
"source_format",
"=",
"job",
".",
"SourceFormat",
".",
"PARQUET",
"if",
"location",
"is",
"None",
":",
"location",
"=",
"self",
".",
"location",
"tmpfd",
",",
"tmppath",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"\"_job_{}.parquet\"",
".",
"format",
"(",
"job_id",
"[",
":",
"8",
"]",
")",
")",
"os",
".",
"close",
"(",
"tmpfd",
")",
"try",
":",
"dataframe",
".",
"to_parquet",
"(",
"tmppath",
")",
"with",
"open",
"(",
"tmppath",
",",
"\"rb\"",
")",
"as",
"parquet_file",
":",
"return",
"self",
".",
"load_table_from_file",
"(",
"parquet_file",
",",
"destination",
",",
"num_retries",
"=",
"num_retries",
",",
"rewind",
"=",
"True",
",",
"job_id",
"=",
"job_id",
",",
"job_id_prefix",
"=",
"job_id_prefix",
",",
"location",
"=",
"location",
",",
"project",
"=",
"project",
",",
"job_config",
"=",
"job_config",
",",
")",
"finally",
":",
"os",
".",
"remove",
"(",
"tmppath",
")"
] | Upload the contents of a table from a pandas DataFrame.
Similar to :meth:`load_table_from_uri`, this method creates, starts and
returns a :class:`~google.cloud.bigquery.job.LoadJob`.
Arguments:
dataframe (pandas.DataFrame):
A :class:`~pandas.DataFrame` containing the data to load.
destination (google.cloud.bigquery.table.TableReference):
The destination table to use for loading the data. If it is an
existing table, the schema of the :class:`~pandas.DataFrame`
must match the schema of the destination table. If the table
does not yet exist, the schema is inferred from the
:class:`~pandas.DataFrame`.
If a string is passed in, this method attempts to create a
table reference from a string using
:func:`google.cloud.bigquery.table.TableReference.from_string`.
Keyword Arguments:
num_retries (int, optional): Number of upload retries.
job_id (str, optional): Name of the job.
job_id_prefix (str, optional):
The user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
destination table.
project (str, optional):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.LoadJobConfig, optional):
Extra configuration options for the job.
Returns:
google.cloud.bigquery.job.LoadJob: A new load job.
Raises:
ImportError:
If a usable parquet engine cannot be found. This method
requires :mod:`pyarrow` or :mod:`fastparquet` to be
installed. | [
"Upload",
"the",
"contents",
"of",
"a",
"table",
"from",
"a",
"pandas",
"DataFrame",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1225-L1309 |
28,040 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.copy_table | def copy_table(
self,
sources,
destination,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
retry=DEFAULT_RETRY,
):
"""Copy one or more tables to another table.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.copy
Arguments:
sources (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
Sequence[ \
Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
] \
], \
]):
Table or tables to be copied.
destination (Union[
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
Table into which data is to be copied.
Keyword Arguments:
job_id (str): (Optional) The ID of the job.
job_id_prefix (str)
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of any
source table as well as the destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.CopyJobConfig):
(Optional) Extra configuration options for the job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.job.CopyJob: A new copy job instance.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
job_ref = job._JobReference(job_id, project=project, location=location)
# sources can be one of many different input types. (string, Table,
# TableReference, or a sequence of any of those.) Convert them all to a
# list of TableReferences.
#
# _table_arg_to_table_ref leaves lists unmodified.
sources = _table_arg_to_table_ref(sources, default_project=self.project)
if not isinstance(sources, collections_abc.Sequence):
sources = [sources]
sources = [
_table_arg_to_table_ref(source, default_project=self.project)
for source in sources
]
destination = _table_arg_to_table_ref(destination, default_project=self.project)
copy_job = job.CopyJob(
job_ref, sources, destination, client=self, job_config=job_config
)
copy_job._begin(retry=retry)
return copy_job | python | def copy_table(
self,
sources,
destination,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
retry=DEFAULT_RETRY,
):
"""Copy one or more tables to another table.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.copy
Arguments:
sources (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
Sequence[ \
Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
] \
], \
]):
Table or tables to be copied.
destination (Union[
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
Table into which data is to be copied.
Keyword Arguments:
job_id (str): (Optional) The ID of the job.
job_id_prefix (str)
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of any
source table as well as the destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.CopyJobConfig):
(Optional) Extra configuration options for the job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.job.CopyJob: A new copy job instance.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
job_ref = job._JobReference(job_id, project=project, location=location)
# sources can be one of many different input types. (string, Table,
# TableReference, or a sequence of any of those.) Convert them all to a
# list of TableReferences.
#
# _table_arg_to_table_ref leaves lists unmodified.
sources = _table_arg_to_table_ref(sources, default_project=self.project)
if not isinstance(sources, collections_abc.Sequence):
sources = [sources]
sources = [
_table_arg_to_table_ref(source, default_project=self.project)
for source in sources
]
destination = _table_arg_to_table_ref(destination, default_project=self.project)
copy_job = job.CopyJob(
job_ref, sources, destination, client=self, job_config=job_config
)
copy_job._begin(retry=retry)
return copy_job | [
"def",
"copy_table",
"(",
"self",
",",
"sources",
",",
"destination",
",",
"job_id",
"=",
"None",
",",
"job_id_prefix",
"=",
"None",
",",
"location",
"=",
"None",
",",
"project",
"=",
"None",
",",
"job_config",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY",
",",
")",
":",
"job_id",
"=",
"_make_job_id",
"(",
"job_id",
",",
"job_id_prefix",
")",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"if",
"location",
"is",
"None",
":",
"location",
"=",
"self",
".",
"location",
"job_ref",
"=",
"job",
".",
"_JobReference",
"(",
"job_id",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
")",
"# sources can be one of many different input types. (string, Table,",
"# TableReference, or a sequence of any of those.) Convert them all to a",
"# list of TableReferences.",
"#",
"# _table_arg_to_table_ref leaves lists unmodified.",
"sources",
"=",
"_table_arg_to_table_ref",
"(",
"sources",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"if",
"not",
"isinstance",
"(",
"sources",
",",
"collections_abc",
".",
"Sequence",
")",
":",
"sources",
"=",
"[",
"sources",
"]",
"sources",
"=",
"[",
"_table_arg_to_table_ref",
"(",
"source",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"for",
"source",
"in",
"sources",
"]",
"destination",
"=",
"_table_arg_to_table_ref",
"(",
"destination",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"copy_job",
"=",
"job",
".",
"CopyJob",
"(",
"job_ref",
",",
"sources",
",",
"destination",
",",
"client",
"=",
"self",
",",
"job_config",
"=",
"job_config",
")",
"copy_job",
".",
"_begin",
"(",
"retry",
"=",
"retry",
")",
"return",
"copy_job"
] | Copy one or more tables to another table.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.copy
Arguments:
sources (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
Sequence[ \
Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
] \
], \
]):
Table or tables to be copied.
destination (Union[
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
Table into which data is to be copied.
Keyword Arguments:
job_id (str): (Optional) The ID of the job.
job_id_prefix (str)
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of any
source table as well as the destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.CopyJobConfig):
(Optional) Extra configuration options for the job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.job.CopyJob: A new copy job instance. | [
"Copy",
"one",
"or",
"more",
"tables",
"to",
"another",
"table",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1420-L1509 |
28,041 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.extract_table | def extract_table(
self,
source,
destination_uris,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
retry=DEFAULT_RETRY,
):
"""Start a job to extract a table into Cloud Storage files.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.extract
Arguments:
source (Union[ \
:class:`google.cloud.bigquery.table.Table`, \
:class:`google.cloud.bigquery.table.TableReference`, \
src, \
]):
Table to be extracted.
destination_uris (Union[str, Sequence[str]]):
URIs of Cloud Storage file(s) into which table data is to be
extracted; in format
``gs://<bucket_name>/<object_name_or_glob>``.
Keyword Arguments:
job_id (str): (Optional) The ID of the job.
job_id_prefix (str)
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
source table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.ExtractJobConfig):
(Optional) Extra configuration options for the job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
:type source: :class:`google.cloud.bigquery.table.TableReference`
:param source: table to be extracted.
Returns:
google.cloud.bigquery.job.ExtractJob: A new extract job instance.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
job_ref = job._JobReference(job_id, project=project, location=location)
source = _table_arg_to_table_ref(source, default_project=self.project)
if isinstance(destination_uris, six.string_types):
destination_uris = [destination_uris]
extract_job = job.ExtractJob(
job_ref, source, destination_uris, client=self, job_config=job_config
)
extract_job._begin(retry=retry)
return extract_job | python | def extract_table(
self,
source,
destination_uris,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
retry=DEFAULT_RETRY,
):
"""Start a job to extract a table into Cloud Storage files.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.extract
Arguments:
source (Union[ \
:class:`google.cloud.bigquery.table.Table`, \
:class:`google.cloud.bigquery.table.TableReference`, \
src, \
]):
Table to be extracted.
destination_uris (Union[str, Sequence[str]]):
URIs of Cloud Storage file(s) into which table data is to be
extracted; in format
``gs://<bucket_name>/<object_name_or_glob>``.
Keyword Arguments:
job_id (str): (Optional) The ID of the job.
job_id_prefix (str)
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
source table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.ExtractJobConfig):
(Optional) Extra configuration options for the job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
:type source: :class:`google.cloud.bigquery.table.TableReference`
:param source: table to be extracted.
Returns:
google.cloud.bigquery.job.ExtractJob: A new extract job instance.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
job_ref = job._JobReference(job_id, project=project, location=location)
source = _table_arg_to_table_ref(source, default_project=self.project)
if isinstance(destination_uris, six.string_types):
destination_uris = [destination_uris]
extract_job = job.ExtractJob(
job_ref, source, destination_uris, client=self, job_config=job_config
)
extract_job._begin(retry=retry)
return extract_job | [
"def",
"extract_table",
"(",
"self",
",",
"source",
",",
"destination_uris",
",",
"job_id",
"=",
"None",
",",
"job_id_prefix",
"=",
"None",
",",
"location",
"=",
"None",
",",
"project",
"=",
"None",
",",
"job_config",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY",
",",
")",
":",
"job_id",
"=",
"_make_job_id",
"(",
"job_id",
",",
"job_id_prefix",
")",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"if",
"location",
"is",
"None",
":",
"location",
"=",
"self",
".",
"location",
"job_ref",
"=",
"job",
".",
"_JobReference",
"(",
"job_id",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
")",
"source",
"=",
"_table_arg_to_table_ref",
"(",
"source",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"if",
"isinstance",
"(",
"destination_uris",
",",
"six",
".",
"string_types",
")",
":",
"destination_uris",
"=",
"[",
"destination_uris",
"]",
"extract_job",
"=",
"job",
".",
"ExtractJob",
"(",
"job_ref",
",",
"source",
",",
"destination_uris",
",",
"client",
"=",
"self",
",",
"job_config",
"=",
"job_config",
")",
"extract_job",
".",
"_begin",
"(",
"retry",
"=",
"retry",
")",
"return",
"extract_job"
] | Start a job to extract a table into Cloud Storage files.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.extract
Arguments:
source (Union[ \
:class:`google.cloud.bigquery.table.Table`, \
:class:`google.cloud.bigquery.table.TableReference`, \
src, \
]):
Table to be extracted.
destination_uris (Union[str, Sequence[str]]):
URIs of Cloud Storage file(s) into which table data is to be
extracted; in format
``gs://<bucket_name>/<object_name_or_glob>``.
Keyword Arguments:
job_id (str): (Optional) The ID of the job.
job_id_prefix (str)
(Optional) the user-provided prefix for a randomly generated
job ID. This parameter will be ignored if a ``job_id`` is
also given.
location (str):
Location where to run the job. Must match the location of the
source table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
job_config (google.cloud.bigquery.job.ExtractJobConfig):
(Optional) Extra configuration options for the job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
:type source: :class:`google.cloud.bigquery.table.TableReference`
:param source: table to be extracted.
Returns:
google.cloud.bigquery.job.ExtractJob: A new extract job instance. | [
"Start",
"a",
"job",
"to",
"extract",
"a",
"table",
"into",
"Cloud",
"Storage",
"files",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1511-L1581 |
28,042 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.query | def query(
self,
query,
job_config=None,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
retry=DEFAULT_RETRY,
):
"""Run a SQL query.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query
Arguments:
query (str):
SQL query to be executed. Defaults to the standard SQL
dialect. Use the ``job_config`` parameter to change dialects.
Keyword Arguments:
job_config (google.cloud.bigquery.job.QueryJobConfig):
(Optional) Extra configuration options for the job.
To override any options that were previously set in
the ``default_query_job_config`` given to the
``Client`` constructor, manually set those options to ``None``,
or whatever value is preferred.
job_id (str): (Optional) ID to use for the query job.
job_id_prefix (str):
(Optional) The prefix to use for a randomly generated job ID.
This parameter will be ignored if a ``job_id`` is also given.
location (str):
Location where to run the job. Must match the location of the
any table used in the query as well as the destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.job.QueryJob: A new query job instance.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
if self._default_query_job_config:
if job_config:
# anything that's not defined on the incoming
# that is in the default,
# should be filled in with the default
# the incoming therefore has precedence
job_config = job_config._fill_from_default(
self._default_query_job_config
)
else:
job_config = self._default_query_job_config
job_ref = job._JobReference(job_id, project=project, location=location)
query_job = job.QueryJob(job_ref, query, client=self, job_config=job_config)
query_job._begin(retry=retry)
return query_job | python | def query(
self,
query,
job_config=None,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
retry=DEFAULT_RETRY,
):
"""Run a SQL query.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query
Arguments:
query (str):
SQL query to be executed. Defaults to the standard SQL
dialect. Use the ``job_config`` parameter to change dialects.
Keyword Arguments:
job_config (google.cloud.bigquery.job.QueryJobConfig):
(Optional) Extra configuration options for the job.
To override any options that were previously set in
the ``default_query_job_config`` given to the
``Client`` constructor, manually set those options to ``None``,
or whatever value is preferred.
job_id (str): (Optional) ID to use for the query job.
job_id_prefix (str):
(Optional) The prefix to use for a randomly generated job ID.
This parameter will be ignored if a ``job_id`` is also given.
location (str):
Location where to run the job. Must match the location of the
any table used in the query as well as the destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.job.QueryJob: A new query job instance.
"""
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
if self._default_query_job_config:
if job_config:
# anything that's not defined on the incoming
# that is in the default,
# should be filled in with the default
# the incoming therefore has precedence
job_config = job_config._fill_from_default(
self._default_query_job_config
)
else:
job_config = self._default_query_job_config
job_ref = job._JobReference(job_id, project=project, location=location)
query_job = job.QueryJob(job_ref, query, client=self, job_config=job_config)
query_job._begin(retry=retry)
return query_job | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"job_config",
"=",
"None",
",",
"job_id",
"=",
"None",
",",
"job_id_prefix",
"=",
"None",
",",
"location",
"=",
"None",
",",
"project",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY",
",",
")",
":",
"job_id",
"=",
"_make_job_id",
"(",
"job_id",
",",
"job_id_prefix",
")",
"if",
"project",
"is",
"None",
":",
"project",
"=",
"self",
".",
"project",
"if",
"location",
"is",
"None",
":",
"location",
"=",
"self",
".",
"location",
"if",
"self",
".",
"_default_query_job_config",
":",
"if",
"job_config",
":",
"# anything that's not defined on the incoming",
"# that is in the default,",
"# should be filled in with the default",
"# the incoming therefore has precedence",
"job_config",
"=",
"job_config",
".",
"_fill_from_default",
"(",
"self",
".",
"_default_query_job_config",
")",
"else",
":",
"job_config",
"=",
"self",
".",
"_default_query_job_config",
"job_ref",
"=",
"job",
".",
"_JobReference",
"(",
"job_id",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
")",
"query_job",
"=",
"job",
".",
"QueryJob",
"(",
"job_ref",
",",
"query",
",",
"client",
"=",
"self",
",",
"job_config",
"=",
"job_config",
")",
"query_job",
".",
"_begin",
"(",
"retry",
"=",
"retry",
")",
"return",
"query_job"
] | Run a SQL query.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query
Arguments:
query (str):
SQL query to be executed. Defaults to the standard SQL
dialect. Use the ``job_config`` parameter to change dialects.
Keyword Arguments:
job_config (google.cloud.bigquery.job.QueryJobConfig):
(Optional) Extra configuration options for the job.
To override any options that were previously set in
the ``default_query_job_config`` given to the
``Client`` constructor, manually set those options to ``None``,
or whatever value is preferred.
job_id (str): (Optional) ID to use for the query job.
job_id_prefix (str):
(Optional) The prefix to use for a randomly generated job ID.
This parameter will be ignored if a ``job_id`` is also given.
location (str):
Location where to run the job. Must match the location of the
any table used in the query as well as the destination table.
project (str):
Project ID of the project of where to run the job. Defaults
to the client's project.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.job.QueryJob: A new query job instance. | [
"Run",
"a",
"SQL",
"query",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1583-L1650 |
28,043 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.insert_rows | def insert_rows(self, table, rows, selected_fields=None, **kwargs):
"""Insert rows into a table via the streaming API.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/insertAll
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The destination table for the row data, or a reference to it.
rows (Union[ \
Sequence[Tuple], \
Sequence[dict], \
]):
Row data to be inserted. If a list of tuples is given, each
tuple should contain data for each schema field on the
current table and in the same order as the schema fields. If
a list of dictionaries is given, the keys must include all
required fields in the schema. Keys which do not correspond
to a field in the schema are ignored.
selected_fields (Sequence[ \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
]):
The fields to return. Required if ``table`` is a
:class:`~google.cloud.bigquery.table.TableReference`.
kwargs (dict):
Keyword arguments to
:meth:`~google.cloud.bigquery.client.Client.insert_rows_json`.
Returns:
Sequence[Mappings]:
One mapping per row with insert errors: the "index" key
identifies the row, and the "errors" key contains a list of
the mappings describing one or more problems with the row.
Raises:
ValueError: if table's schema is not set
"""
table = _table_arg_to_table(table, default_project=self.project)
if not isinstance(table, Table):
raise TypeError(_NEED_TABLE_ARGUMENT)
schema = table.schema
# selected_fields can override the table schema.
if selected_fields is not None:
schema = selected_fields
if len(schema) == 0:
raise ValueError(
(
"Could not determine schema for table '{}'. Call client.get_table() "
"or pass in a list of schema fields to the selected_fields argument."
).format(table)
)
json_rows = [_record_field_to_json(schema, row) for row in rows]
return self.insert_rows_json(table, json_rows, **kwargs) | python | def insert_rows(self, table, rows, selected_fields=None, **kwargs):
"""Insert rows into a table via the streaming API.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/insertAll
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The destination table for the row data, or a reference to it.
rows (Union[ \
Sequence[Tuple], \
Sequence[dict], \
]):
Row data to be inserted. If a list of tuples is given, each
tuple should contain data for each schema field on the
current table and in the same order as the schema fields. If
a list of dictionaries is given, the keys must include all
required fields in the schema. Keys which do not correspond
to a field in the schema are ignored.
selected_fields (Sequence[ \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
]):
The fields to return. Required if ``table`` is a
:class:`~google.cloud.bigquery.table.TableReference`.
kwargs (dict):
Keyword arguments to
:meth:`~google.cloud.bigquery.client.Client.insert_rows_json`.
Returns:
Sequence[Mappings]:
One mapping per row with insert errors: the "index" key
identifies the row, and the "errors" key contains a list of
the mappings describing one or more problems with the row.
Raises:
ValueError: if table's schema is not set
"""
table = _table_arg_to_table(table, default_project=self.project)
if not isinstance(table, Table):
raise TypeError(_NEED_TABLE_ARGUMENT)
schema = table.schema
# selected_fields can override the table schema.
if selected_fields is not None:
schema = selected_fields
if len(schema) == 0:
raise ValueError(
(
"Could not determine schema for table '{}'. Call client.get_table() "
"or pass in a list of schema fields to the selected_fields argument."
).format(table)
)
json_rows = [_record_field_to_json(schema, row) for row in rows]
return self.insert_rows_json(table, json_rows, **kwargs) | [
"def",
"insert_rows",
"(",
"self",
",",
"table",
",",
"rows",
",",
"selected_fields",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"table",
"=",
"_table_arg_to_table",
"(",
"table",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"if",
"not",
"isinstance",
"(",
"table",
",",
"Table",
")",
":",
"raise",
"TypeError",
"(",
"_NEED_TABLE_ARGUMENT",
")",
"schema",
"=",
"table",
".",
"schema",
"# selected_fields can override the table schema.",
"if",
"selected_fields",
"is",
"not",
"None",
":",
"schema",
"=",
"selected_fields",
"if",
"len",
"(",
"schema",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"(",
"\"Could not determine schema for table '{}'. Call client.get_table() \"",
"\"or pass in a list of schema fields to the selected_fields argument.\"",
")",
".",
"format",
"(",
"table",
")",
")",
"json_rows",
"=",
"[",
"_record_field_to_json",
"(",
"schema",
",",
"row",
")",
"for",
"row",
"in",
"rows",
"]",
"return",
"self",
".",
"insert_rows_json",
"(",
"table",
",",
"json_rows",
",",
"*",
"*",
"kwargs",
")"
] | Insert rows into a table via the streaming API.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/insertAll
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The destination table for the row data, or a reference to it.
rows (Union[ \
Sequence[Tuple], \
Sequence[dict], \
]):
Row data to be inserted. If a list of tuples is given, each
tuple should contain data for each schema field on the
current table and in the same order as the schema fields. If
a list of dictionaries is given, the keys must include all
required fields in the schema. Keys which do not correspond
to a field in the schema are ignored.
selected_fields (Sequence[ \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
]):
The fields to return. Required if ``table`` is a
:class:`~google.cloud.bigquery.table.TableReference`.
kwargs (dict):
Keyword arguments to
:meth:`~google.cloud.bigquery.client.Client.insert_rows_json`.
Returns:
Sequence[Mappings]:
One mapping per row with insert errors: the "index" key
identifies the row, and the "errors" key contains a list of
the mappings describing one or more problems with the row.
Raises:
ValueError: if table's schema is not set | [
"Insert",
"rows",
"into",
"a",
"table",
"via",
"the",
"streaming",
"API",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1652-L1714 |
28,044 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.insert_rows_json | def insert_rows_json(
self,
table,
json_rows,
row_ids=None,
skip_invalid_rows=None,
ignore_unknown_values=None,
template_suffix=None,
retry=DEFAULT_RETRY,
):
"""Insert rows into a table without applying local type conversions.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/insertAll
table (Union[ \
:class:`~google.cloud.bigquery.table.Table` \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The destination table for the row data, or a reference to it.
json_rows (Sequence[dict]):
Row data to be inserted. Keys must match the table schema fields
and values must be JSON-compatible representations.
row_ids (Sequence[str]):
(Optional) Unique ids, one per row being inserted. If omitted,
unique IDs are created.
skip_invalid_rows (bool):
(Optional) Insert all valid rows of a request, even if invalid
rows exist. The default value is False, which causes the entire
request to fail if any invalid rows exist.
ignore_unknown_values (bool):
(Optional) Accept rows that contain values that do not match the
schema. The unknown values are ignored. Default is False, which
treats unknown values as errors.
template_suffix (str):
(Optional) treat ``name`` as a template table and provide a suffix.
BigQuery will create the table ``<name> + <template_suffix>`` based
on the schema of the template table. See
https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
Sequence[Mappings]:
One mapping per row with insert errors: the "index" key
identifies the row, and the "errors" key contains a list of
the mappings describing one or more problems with the row.
"""
# Convert table to just a reference because unlike insert_rows,
# insert_rows_json doesn't need the table schema. It's not doing any
# type conversions.
table = _table_arg_to_table_ref(table, default_project=self.project)
rows_info = []
data = {"rows": rows_info}
for index, row in enumerate(json_rows):
info = {"json": row}
if row_ids is not None:
info["insertId"] = row_ids[index]
else:
info["insertId"] = str(uuid.uuid4())
rows_info.append(info)
if skip_invalid_rows is not None:
data["skipInvalidRows"] = skip_invalid_rows
if ignore_unknown_values is not None:
data["ignoreUnknownValues"] = ignore_unknown_values
if template_suffix is not None:
data["templateSuffix"] = template_suffix
# We can always retry, because every row has an insert ID.
response = self._call_api(
retry, method="POST", path="%s/insertAll" % table.path, data=data
)
errors = []
for error in response.get("insertErrors", ()):
errors.append({"index": int(error["index"]), "errors": error["errors"]})
return errors | python | def insert_rows_json(
self,
table,
json_rows,
row_ids=None,
skip_invalid_rows=None,
ignore_unknown_values=None,
template_suffix=None,
retry=DEFAULT_RETRY,
):
"""Insert rows into a table without applying local type conversions.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/insertAll
table (Union[ \
:class:`~google.cloud.bigquery.table.Table` \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The destination table for the row data, or a reference to it.
json_rows (Sequence[dict]):
Row data to be inserted. Keys must match the table schema fields
and values must be JSON-compatible representations.
row_ids (Sequence[str]):
(Optional) Unique ids, one per row being inserted. If omitted,
unique IDs are created.
skip_invalid_rows (bool):
(Optional) Insert all valid rows of a request, even if invalid
rows exist. The default value is False, which causes the entire
request to fail if any invalid rows exist.
ignore_unknown_values (bool):
(Optional) Accept rows that contain values that do not match the
schema. The unknown values are ignored. Default is False, which
treats unknown values as errors.
template_suffix (str):
(Optional) treat ``name`` as a template table and provide a suffix.
BigQuery will create the table ``<name> + <template_suffix>`` based
on the schema of the template table. See
https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
Sequence[Mappings]:
One mapping per row with insert errors: the "index" key
identifies the row, and the "errors" key contains a list of
the mappings describing one or more problems with the row.
"""
# Convert table to just a reference because unlike insert_rows,
# insert_rows_json doesn't need the table schema. It's not doing any
# type conversions.
table = _table_arg_to_table_ref(table, default_project=self.project)
rows_info = []
data = {"rows": rows_info}
for index, row in enumerate(json_rows):
info = {"json": row}
if row_ids is not None:
info["insertId"] = row_ids[index]
else:
info["insertId"] = str(uuid.uuid4())
rows_info.append(info)
if skip_invalid_rows is not None:
data["skipInvalidRows"] = skip_invalid_rows
if ignore_unknown_values is not None:
data["ignoreUnknownValues"] = ignore_unknown_values
if template_suffix is not None:
data["templateSuffix"] = template_suffix
# We can always retry, because every row has an insert ID.
response = self._call_api(
retry, method="POST", path="%s/insertAll" % table.path, data=data
)
errors = []
for error in response.get("insertErrors", ()):
errors.append({"index": int(error["index"]), "errors": error["errors"]})
return errors | [
"def",
"insert_rows_json",
"(",
"self",
",",
"table",
",",
"json_rows",
",",
"row_ids",
"=",
"None",
",",
"skip_invalid_rows",
"=",
"None",
",",
"ignore_unknown_values",
"=",
"None",
",",
"template_suffix",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY",
",",
")",
":",
"# Convert table to just a reference because unlike insert_rows,",
"# insert_rows_json doesn't need the table schema. It's not doing any",
"# type conversions.",
"table",
"=",
"_table_arg_to_table_ref",
"(",
"table",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"rows_info",
"=",
"[",
"]",
"data",
"=",
"{",
"\"rows\"",
":",
"rows_info",
"}",
"for",
"index",
",",
"row",
"in",
"enumerate",
"(",
"json_rows",
")",
":",
"info",
"=",
"{",
"\"json\"",
":",
"row",
"}",
"if",
"row_ids",
"is",
"not",
"None",
":",
"info",
"[",
"\"insertId\"",
"]",
"=",
"row_ids",
"[",
"index",
"]",
"else",
":",
"info",
"[",
"\"insertId\"",
"]",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"rows_info",
".",
"append",
"(",
"info",
")",
"if",
"skip_invalid_rows",
"is",
"not",
"None",
":",
"data",
"[",
"\"skipInvalidRows\"",
"]",
"=",
"skip_invalid_rows",
"if",
"ignore_unknown_values",
"is",
"not",
"None",
":",
"data",
"[",
"\"ignoreUnknownValues\"",
"]",
"=",
"ignore_unknown_values",
"if",
"template_suffix",
"is",
"not",
"None",
":",
"data",
"[",
"\"templateSuffix\"",
"]",
"=",
"template_suffix",
"# We can always retry, because every row has an insert ID.",
"response",
"=",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"\"%s/insertAll\"",
"%",
"table",
".",
"path",
",",
"data",
"=",
"data",
")",
"errors",
"=",
"[",
"]",
"for",
"error",
"in",
"response",
".",
"get",
"(",
"\"insertErrors\"",
",",
"(",
")",
")",
":",
"errors",
".",
"append",
"(",
"{",
"\"index\"",
":",
"int",
"(",
"error",
"[",
"\"index\"",
"]",
")",
",",
"\"errors\"",
":",
"error",
"[",
"\"errors\"",
"]",
"}",
")",
"return",
"errors"
] | Insert rows into a table without applying local type conversions.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/insertAll
table (Union[ \
:class:`~google.cloud.bigquery.table.Table` \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The destination table for the row data, or a reference to it.
json_rows (Sequence[dict]):
Row data to be inserted. Keys must match the table schema fields
and values must be JSON-compatible representations.
row_ids (Sequence[str]):
(Optional) Unique ids, one per row being inserted. If omitted,
unique IDs are created.
skip_invalid_rows (bool):
(Optional) Insert all valid rows of a request, even if invalid
rows exist. The default value is False, which causes the entire
request to fail if any invalid rows exist.
ignore_unknown_values (bool):
(Optional) Accept rows that contain values that do not match the
schema. The unknown values are ignored. Default is False, which
treats unknown values as errors.
template_suffix (str):
(Optional) treat ``name`` as a template table and provide a suffix.
BigQuery will create the table ``<name> + <template_suffix>`` based
on the schema of the template table. See
https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
Sequence[Mappings]:
One mapping per row with insert errors: the "index" key
identifies the row, and the "errors" key contains a list of
the mappings describing one or more problems with the row. | [
"Insert",
"rows",
"into",
"a",
"table",
"without",
"applying",
"local",
"type",
"conversions",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1716-L1798 |
28,045 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.list_partitions | def list_partitions(self, table, retry=DEFAULT_RETRY):
"""List the partitions in a table.
Arguments:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The table or reference from which to get partition info
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
List[str]:
A list of the partition ids present in the partitioned table
"""
table = _table_arg_to_table_ref(table, default_project=self.project)
meta_table = self.get_table(
TableReference(
self.dataset(table.dataset_id, project=table.project),
"%s$__PARTITIONS_SUMMARY__" % table.table_id,
)
)
subset = [col for col in meta_table.schema if col.name == "partition_id"]
return [
row[0]
for row in self.list_rows(meta_table, selected_fields=subset, retry=retry)
] | python | def list_partitions(self, table, retry=DEFAULT_RETRY):
"""List the partitions in a table.
Arguments:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The table or reference from which to get partition info
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
List[str]:
A list of the partition ids present in the partitioned table
"""
table = _table_arg_to_table_ref(table, default_project=self.project)
meta_table = self.get_table(
TableReference(
self.dataset(table.dataset_id, project=table.project),
"%s$__PARTITIONS_SUMMARY__" % table.table_id,
)
)
subset = [col for col in meta_table.schema if col.name == "partition_id"]
return [
row[0]
for row in self.list_rows(meta_table, selected_fields=subset, retry=retry)
] | [
"def",
"list_partitions",
"(",
"self",
",",
"table",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"table",
"=",
"_table_arg_to_table_ref",
"(",
"table",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"meta_table",
"=",
"self",
".",
"get_table",
"(",
"TableReference",
"(",
"self",
".",
"dataset",
"(",
"table",
".",
"dataset_id",
",",
"project",
"=",
"table",
".",
"project",
")",
",",
"\"%s$__PARTITIONS_SUMMARY__\"",
"%",
"table",
".",
"table_id",
",",
")",
")",
"subset",
"=",
"[",
"col",
"for",
"col",
"in",
"meta_table",
".",
"schema",
"if",
"col",
".",
"name",
"==",
"\"partition_id\"",
"]",
"return",
"[",
"row",
"[",
"0",
"]",
"for",
"row",
"in",
"self",
".",
"list_rows",
"(",
"meta_table",
",",
"selected_fields",
"=",
"subset",
",",
"retry",
"=",
"retry",
")",
"]"
] | List the partitions in a table.
Arguments:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The table or reference from which to get partition info
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
Returns:
List[str]:
A list of the partition ids present in the partitioned table | [
"List",
"the",
"partitions",
"in",
"a",
"table",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1800-L1829 |
28,046 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.list_rows | def list_rows(
self,
table,
selected_fields=None,
max_results=None,
page_token=None,
start_index=None,
page_size=None,
retry=DEFAULT_RETRY,
):
"""List the rows of the table.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/list
.. note::
This method assumes that the provided schema is up-to-date with the
schema as defined on the back-end: if the two schemas are not
identical, the values returned may be incomplete. To ensure that the
local copy of the schema is up-to-date, call ``client.get_table``.
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableListItem`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The table to list, or a reference to it. When the table
object does not contain a schema and ``selected_fields`` is
not supplied, this method calls ``get_table`` to fetch the
table schema.
selected_fields (Sequence[ \
:class:`~google.cloud.bigquery.schema.SchemaField` \
]):
The fields to return. If not supplied, data for all columns
are downloaded.
max_results (int):
(Optional) maximum number of rows to return.
page_token (str):
(Optional) Token representing a cursor into the table's rows.
If not passed, the API will return the first page of the
rows. The token marks the beginning of the iterator to be
returned and the value of the ``page_token`` can be accessed
at ``next_page_token`` of the
:class:`~google.cloud.bigquery.table.RowIterator`.
start_index (int):
(Optional) The zero-based index of the starting row to read.
page_size (int):
Optional. The maximum number of rows in each page of results
from this request. Non-positive values are ignored. Defaults
to a sensible value set by the API.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.table.RowIterator:
Iterator of row data
:class:`~google.cloud.bigquery.table.Row`-s. During each
page, the iterator will have the ``total_rows`` attribute
set, which counts the total number of rows **in the table**
(this is distinct from the total number of rows in the
current page: ``iterator.page.num_items``).
"""
table = _table_arg_to_table(table, default_project=self.project)
if not isinstance(table, Table):
raise TypeError(_NEED_TABLE_ARGUMENT)
schema = table.schema
# selected_fields can override the table schema.
if selected_fields is not None:
schema = selected_fields
# No schema, but no selected_fields. Assume the developer wants all
# columns, so get the table resource for them rather than failing.
elif len(schema) == 0:
table = self.get_table(table.reference, retry=retry)
schema = table.schema
params = {}
if selected_fields is not None:
params["selectedFields"] = ",".join(field.name for field in selected_fields)
if start_index is not None:
params["startIndex"] = start_index
row_iterator = RowIterator(
client=self,
api_request=functools.partial(self._call_api, retry),
path="%s/data" % (table.path,),
schema=schema,
page_token=page_token,
max_results=max_results,
page_size=page_size,
extra_params=params,
table=table,
# Pass in selected_fields separately from schema so that full
# tables can be fetched without a column filter.
selected_fields=selected_fields,
)
return row_iterator | python | def list_rows(
self,
table,
selected_fields=None,
max_results=None,
page_token=None,
start_index=None,
page_size=None,
retry=DEFAULT_RETRY,
):
"""List the rows of the table.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/list
.. note::
This method assumes that the provided schema is up-to-date with the
schema as defined on the back-end: if the two schemas are not
identical, the values returned may be incomplete. To ensure that the
local copy of the schema is up-to-date, call ``client.get_table``.
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableListItem`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The table to list, or a reference to it. When the table
object does not contain a schema and ``selected_fields`` is
not supplied, this method calls ``get_table`` to fetch the
table schema.
selected_fields (Sequence[ \
:class:`~google.cloud.bigquery.schema.SchemaField` \
]):
The fields to return. If not supplied, data for all columns
are downloaded.
max_results (int):
(Optional) maximum number of rows to return.
page_token (str):
(Optional) Token representing a cursor into the table's rows.
If not passed, the API will return the first page of the
rows. The token marks the beginning of the iterator to be
returned and the value of the ``page_token`` can be accessed
at ``next_page_token`` of the
:class:`~google.cloud.bigquery.table.RowIterator`.
start_index (int):
(Optional) The zero-based index of the starting row to read.
page_size (int):
Optional. The maximum number of rows in each page of results
from this request. Non-positive values are ignored. Defaults
to a sensible value set by the API.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.table.RowIterator:
Iterator of row data
:class:`~google.cloud.bigquery.table.Row`-s. During each
page, the iterator will have the ``total_rows`` attribute
set, which counts the total number of rows **in the table**
(this is distinct from the total number of rows in the
current page: ``iterator.page.num_items``).
"""
table = _table_arg_to_table(table, default_project=self.project)
if not isinstance(table, Table):
raise TypeError(_NEED_TABLE_ARGUMENT)
schema = table.schema
# selected_fields can override the table schema.
if selected_fields is not None:
schema = selected_fields
# No schema, but no selected_fields. Assume the developer wants all
# columns, so get the table resource for them rather than failing.
elif len(schema) == 0:
table = self.get_table(table.reference, retry=retry)
schema = table.schema
params = {}
if selected_fields is not None:
params["selectedFields"] = ",".join(field.name for field in selected_fields)
if start_index is not None:
params["startIndex"] = start_index
row_iterator = RowIterator(
client=self,
api_request=functools.partial(self._call_api, retry),
path="%s/data" % (table.path,),
schema=schema,
page_token=page_token,
max_results=max_results,
page_size=page_size,
extra_params=params,
table=table,
# Pass in selected_fields separately from schema so that full
# tables can be fetched without a column filter.
selected_fields=selected_fields,
)
return row_iterator | [
"def",
"list_rows",
"(",
"self",
",",
"table",
",",
"selected_fields",
"=",
"None",
",",
"max_results",
"=",
"None",
",",
"page_token",
"=",
"None",
",",
"start_index",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY",
",",
")",
":",
"table",
"=",
"_table_arg_to_table",
"(",
"table",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"if",
"not",
"isinstance",
"(",
"table",
",",
"Table",
")",
":",
"raise",
"TypeError",
"(",
"_NEED_TABLE_ARGUMENT",
")",
"schema",
"=",
"table",
".",
"schema",
"# selected_fields can override the table schema.",
"if",
"selected_fields",
"is",
"not",
"None",
":",
"schema",
"=",
"selected_fields",
"# No schema, but no selected_fields. Assume the developer wants all",
"# columns, so get the table resource for them rather than failing.",
"elif",
"len",
"(",
"schema",
")",
"==",
"0",
":",
"table",
"=",
"self",
".",
"get_table",
"(",
"table",
".",
"reference",
",",
"retry",
"=",
"retry",
")",
"schema",
"=",
"table",
".",
"schema",
"params",
"=",
"{",
"}",
"if",
"selected_fields",
"is",
"not",
"None",
":",
"params",
"[",
"\"selectedFields\"",
"]",
"=",
"\",\"",
".",
"join",
"(",
"field",
".",
"name",
"for",
"field",
"in",
"selected_fields",
")",
"if",
"start_index",
"is",
"not",
"None",
":",
"params",
"[",
"\"startIndex\"",
"]",
"=",
"start_index",
"row_iterator",
"=",
"RowIterator",
"(",
"client",
"=",
"self",
",",
"api_request",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_call_api",
",",
"retry",
")",
",",
"path",
"=",
"\"%s/data\"",
"%",
"(",
"table",
".",
"path",
",",
")",
",",
"schema",
"=",
"schema",
",",
"page_token",
"=",
"page_token",
",",
"max_results",
"=",
"max_results",
",",
"page_size",
"=",
"page_size",
",",
"extra_params",
"=",
"params",
",",
"table",
"=",
"table",
",",
"# Pass in selected_fields separately from schema so that full",
"# tables can be fetched without a column filter.",
"selected_fields",
"=",
"selected_fields",
",",
")",
"return",
"row_iterator"
] | List the rows of the table.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/list
.. note::
This method assumes that the provided schema is up-to-date with the
schema as defined on the back-end: if the two schemas are not
identical, the values returned may be incomplete. To ensure that the
local copy of the schema is up-to-date, call ``client.get_table``.
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableListItem`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
The table to list, or a reference to it. When the table
object does not contain a schema and ``selected_fields`` is
not supplied, this method calls ``get_table`` to fetch the
table schema.
selected_fields (Sequence[ \
:class:`~google.cloud.bigquery.schema.SchemaField` \
]):
The fields to return. If not supplied, data for all columns
are downloaded.
max_results (int):
(Optional) maximum number of rows to return.
page_token (str):
(Optional) Token representing a cursor into the table's rows.
If not passed, the API will return the first page of the
rows. The token marks the beginning of the iterator to be
returned and the value of the ``page_token`` can be accessed
at ``next_page_token`` of the
:class:`~google.cloud.bigquery.table.RowIterator`.
start_index (int):
(Optional) The zero-based index of the starting row to read.
page_size (int):
Optional. The maximum number of rows in each page of results
from this request. Non-positive values are ignored. Defaults
to a sensible value set by the API.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.table.RowIterator:
Iterator of row data
:class:`~google.cloud.bigquery.table.Row`-s. During each
page, the iterator will have the ``total_rows`` attribute
set, which counts the total number of rows **in the table**
(this is distinct from the total number of rows in the
current page: ``iterator.page.num_items``). | [
"List",
"the",
"rows",
"of",
"the",
"table",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1831-L1933 |
28,047 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client._schema_from_json_file_object | def _schema_from_json_file_object(self, file_obj):
"""Helper function for schema_from_json that takes a
file object that describes a table schema.
Returns:
List of schema field objects.
"""
json_data = json.load(file_obj)
return [SchemaField.from_api_repr(field) for field in json_data] | python | def _schema_from_json_file_object(self, file_obj):
"""Helper function for schema_from_json that takes a
file object that describes a table schema.
Returns:
List of schema field objects.
"""
json_data = json.load(file_obj)
return [SchemaField.from_api_repr(field) for field in json_data] | [
"def",
"_schema_from_json_file_object",
"(",
"self",
",",
"file_obj",
")",
":",
"json_data",
"=",
"json",
".",
"load",
"(",
"file_obj",
")",
"return",
"[",
"SchemaField",
".",
"from_api_repr",
"(",
"field",
")",
"for",
"field",
"in",
"json_data",
"]"
] | Helper function for schema_from_json that takes a
file object that describes a table schema.
Returns:
List of schema field objects. | [
"Helper",
"function",
"for",
"schema_from_json",
"that",
"takes",
"a",
"file",
"object",
"that",
"describes",
"a",
"table",
"schema",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1935-L1943 |
28,048 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client._schema_to_json_file_object | def _schema_to_json_file_object(self, schema_list, file_obj):
"""Helper function for schema_to_json that takes a schema list and file
object and writes the schema list to the file object with json.dump
"""
json.dump(schema_list, file_obj, indent=2, sort_keys=True) | python | def _schema_to_json_file_object(self, schema_list, file_obj):
"""Helper function for schema_to_json that takes a schema list and file
object and writes the schema list to the file object with json.dump
"""
json.dump(schema_list, file_obj, indent=2, sort_keys=True) | [
"def",
"_schema_to_json_file_object",
"(",
"self",
",",
"schema_list",
",",
"file_obj",
")",
":",
"json",
".",
"dump",
"(",
"schema_list",
",",
"file_obj",
",",
"indent",
"=",
"2",
",",
"sort_keys",
"=",
"True",
")"
] | Helper function for schema_to_json that takes a schema list and file
object and writes the schema list to the file object with json.dump | [
"Helper",
"function",
"for",
"schema_to_json",
"that",
"takes",
"a",
"schema",
"list",
"and",
"file",
"object",
"and",
"writes",
"the",
"schema",
"list",
"to",
"the",
"file",
"object",
"with",
"json",
".",
"dump"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1945-L1949 |
28,049 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.schema_from_json | def schema_from_json(self, file_or_path):
"""Takes a file object or file path that contains json that describes
a table schema.
Returns:
List of schema field objects.
"""
if isinstance(file_or_path, io.IOBase):
return self._schema_from_json_file_object(file_or_path)
with open(file_or_path) as file_obj:
return self._schema_from_json_file_object(file_obj) | python | def schema_from_json(self, file_or_path):
"""Takes a file object or file path that contains json that describes
a table schema.
Returns:
List of schema field objects.
"""
if isinstance(file_or_path, io.IOBase):
return self._schema_from_json_file_object(file_or_path)
with open(file_or_path) as file_obj:
return self._schema_from_json_file_object(file_obj) | [
"def",
"schema_from_json",
"(",
"self",
",",
"file_or_path",
")",
":",
"if",
"isinstance",
"(",
"file_or_path",
",",
"io",
".",
"IOBase",
")",
":",
"return",
"self",
".",
"_schema_from_json_file_object",
"(",
"file_or_path",
")",
"with",
"open",
"(",
"file_or_path",
")",
"as",
"file_obj",
":",
"return",
"self",
".",
"_schema_from_json_file_object",
"(",
"file_obj",
")"
] | Takes a file object or file path that contains json that describes
a table schema.
Returns:
List of schema field objects. | [
"Takes",
"a",
"file",
"object",
"or",
"file",
"path",
"that",
"contains",
"json",
"that",
"describes",
"a",
"table",
"schema",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1951-L1962 |
28,050 | googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | Client.schema_to_json | def schema_to_json(self, schema_list, destination):
"""Takes a list of schema field objects.
Serializes the list of schema field objects as json to a file.
Destination is a file path or a file object.
"""
json_schema_list = [f.to_api_repr() for f in schema_list]
if isinstance(destination, io.IOBase):
return self._schema_to_json_file_object(json_schema_list, destination)
with open(destination, mode="w") as file_obj:
return self._schema_to_json_file_object(json_schema_list, file_obj) | python | def schema_to_json(self, schema_list, destination):
"""Takes a list of schema field objects.
Serializes the list of schema field objects as json to a file.
Destination is a file path or a file object.
"""
json_schema_list = [f.to_api_repr() for f in schema_list]
if isinstance(destination, io.IOBase):
return self._schema_to_json_file_object(json_schema_list, destination)
with open(destination, mode="w") as file_obj:
return self._schema_to_json_file_object(json_schema_list, file_obj) | [
"def",
"schema_to_json",
"(",
"self",
",",
"schema_list",
",",
"destination",
")",
":",
"json_schema_list",
"=",
"[",
"f",
".",
"to_api_repr",
"(",
")",
"for",
"f",
"in",
"schema_list",
"]",
"if",
"isinstance",
"(",
"destination",
",",
"io",
".",
"IOBase",
")",
":",
"return",
"self",
".",
"_schema_to_json_file_object",
"(",
"json_schema_list",
",",
"destination",
")",
"with",
"open",
"(",
"destination",
",",
"mode",
"=",
"\"w\"",
")",
"as",
"file_obj",
":",
"return",
"self",
".",
"_schema_to_json_file_object",
"(",
"json_schema_list",
",",
"file_obj",
")"
] | Takes a list of schema field objects.
Serializes the list of schema field objects as json to a file.
Destination is a file path or a file object. | [
"Takes",
"a",
"list",
"of",
"schema",
"field",
"objects",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1964-L1977 |
28,051 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/instance.py | Instance._update_from_pb | def _update_from_pb(self, instance_pb):
"""Refresh self from the server-provided protobuf.
Helper for :meth:`from_pb` and :meth:`reload`.
"""
if not instance_pb.display_name: # Simple field (string)
raise ValueError("Instance protobuf does not contain display_name")
self.display_name = instance_pb.display_name
self.configuration_name = instance_pb.config
self.node_count = instance_pb.node_count | python | def _update_from_pb(self, instance_pb):
"""Refresh self from the server-provided protobuf.
Helper for :meth:`from_pb` and :meth:`reload`.
"""
if not instance_pb.display_name: # Simple field (string)
raise ValueError("Instance protobuf does not contain display_name")
self.display_name = instance_pb.display_name
self.configuration_name = instance_pb.config
self.node_count = instance_pb.node_count | [
"def",
"_update_from_pb",
"(",
"self",
",",
"instance_pb",
")",
":",
"if",
"not",
"instance_pb",
".",
"display_name",
":",
"# Simple field (string)",
"raise",
"ValueError",
"(",
"\"Instance protobuf does not contain display_name\"",
")",
"self",
".",
"display_name",
"=",
"instance_pb",
".",
"display_name",
"self",
".",
"configuration_name",
"=",
"instance_pb",
".",
"config",
"self",
".",
"node_count",
"=",
"instance_pb",
".",
"node_count"
] | Refresh self from the server-provided protobuf.
Helper for :meth:`from_pb` and :meth:`reload`. | [
"Refresh",
"self",
"from",
"the",
"server",
"-",
"provided",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/instance.py#L86-L95 |
28,052 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/instance.py | Instance.from_pb | def from_pb(cls, instance_pb, client):
"""Creates an instance from a protobuf.
:type instance_pb:
:class:`google.spanner.v2.spanner_instance_admin_pb2.Instance`
:param instance_pb: A instance protobuf object.
:type client: :class:`~google.cloud.spanner_v1.client.Client`
:param client: The client that owns the instance.
:rtype: :class:`Instance`
:returns: The instance parsed from the protobuf response.
:raises ValueError:
if the instance name does not match
``projects/{project}/instances/{instance_id}`` or if the parsed
project ID does not match the project ID on the client.
"""
match = _INSTANCE_NAME_RE.match(instance_pb.name)
if match is None:
raise ValueError(
"Instance protobuf name was not in the " "expected format.",
instance_pb.name,
)
if match.group("project") != client.project:
raise ValueError(
"Project ID on instance does not match the " "project ID on the client"
)
instance_id = match.group("instance_id")
configuration_name = instance_pb.config
result = cls(instance_id, client, configuration_name)
result._update_from_pb(instance_pb)
return result | python | def from_pb(cls, instance_pb, client):
"""Creates an instance from a protobuf.
:type instance_pb:
:class:`google.spanner.v2.spanner_instance_admin_pb2.Instance`
:param instance_pb: A instance protobuf object.
:type client: :class:`~google.cloud.spanner_v1.client.Client`
:param client: The client that owns the instance.
:rtype: :class:`Instance`
:returns: The instance parsed from the protobuf response.
:raises ValueError:
if the instance name does not match
``projects/{project}/instances/{instance_id}`` or if the parsed
project ID does not match the project ID on the client.
"""
match = _INSTANCE_NAME_RE.match(instance_pb.name)
if match is None:
raise ValueError(
"Instance protobuf name was not in the " "expected format.",
instance_pb.name,
)
if match.group("project") != client.project:
raise ValueError(
"Project ID on instance does not match the " "project ID on the client"
)
instance_id = match.group("instance_id")
configuration_name = instance_pb.config
result = cls(instance_id, client, configuration_name)
result._update_from_pb(instance_pb)
return result | [
"def",
"from_pb",
"(",
"cls",
",",
"instance_pb",
",",
"client",
")",
":",
"match",
"=",
"_INSTANCE_NAME_RE",
".",
"match",
"(",
"instance_pb",
".",
"name",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Instance protobuf name was not in the \"",
"\"expected format.\"",
",",
"instance_pb",
".",
"name",
",",
")",
"if",
"match",
".",
"group",
"(",
"\"project\"",
")",
"!=",
"client",
".",
"project",
":",
"raise",
"ValueError",
"(",
"\"Project ID on instance does not match the \"",
"\"project ID on the client\"",
")",
"instance_id",
"=",
"match",
".",
"group",
"(",
"\"instance_id\"",
")",
"configuration_name",
"=",
"instance_pb",
".",
"config",
"result",
"=",
"cls",
"(",
"instance_id",
",",
"client",
",",
"configuration_name",
")",
"result",
".",
"_update_from_pb",
"(",
"instance_pb",
")",
"return",
"result"
] | Creates an instance from a protobuf.
:type instance_pb:
:class:`google.spanner.v2.spanner_instance_admin_pb2.Instance`
:param instance_pb: A instance protobuf object.
:type client: :class:`~google.cloud.spanner_v1.client.Client`
:param client: The client that owns the instance.
:rtype: :class:`Instance`
:returns: The instance parsed from the protobuf response.
:raises ValueError:
if the instance name does not match
``projects/{project}/instances/{instance_id}`` or if the parsed
project ID does not match the project ID on the client. | [
"Creates",
"an",
"instance",
"from",
"a",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/instance.py#L98-L130 |
28,053 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/instance.py | Instance.copy | def copy(self):
"""Make a copy of this instance.
Copies the local data stored as simple types and copies the client
attached to this instance.
:rtype: :class:`~google.cloud.spanner_v1.instance.Instance`
:returns: A copy of the current instance.
"""
new_client = self._client.copy()
return self.__class__(
self.instance_id,
new_client,
self.configuration_name,
node_count=self.node_count,
display_name=self.display_name,
) | python | def copy(self):
"""Make a copy of this instance.
Copies the local data stored as simple types and copies the client
attached to this instance.
:rtype: :class:`~google.cloud.spanner_v1.instance.Instance`
:returns: A copy of the current instance.
"""
new_client = self._client.copy()
return self.__class__(
self.instance_id,
new_client,
self.configuration_name,
node_count=self.node_count,
display_name=self.display_name,
) | [
"def",
"copy",
"(",
"self",
")",
":",
"new_client",
"=",
"self",
".",
"_client",
".",
"copy",
"(",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"instance_id",
",",
"new_client",
",",
"self",
".",
"configuration_name",
",",
"node_count",
"=",
"self",
".",
"node_count",
",",
"display_name",
"=",
"self",
".",
"display_name",
",",
")"
] | Make a copy of this instance.
Copies the local data stored as simple types and copies the client
attached to this instance.
:rtype: :class:`~google.cloud.spanner_v1.instance.Instance`
:returns: A copy of the current instance. | [
"Make",
"a",
"copy",
"of",
"this",
"instance",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/instance.py#L164-L180 |
28,054 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/instance.py | Instance.exists | def exists(self):
"""Test whether this instance exists.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig
:rtype: bool
:returns: True if the instance exists, else false
"""
api = self._client.instance_admin_api
metadata = _metadata_with_prefix(self.name)
try:
api.get_instance(self.name, metadata=metadata)
except NotFound:
return False
return True | python | def exists(self):
"""Test whether this instance exists.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig
:rtype: bool
:returns: True if the instance exists, else false
"""
api = self._client.instance_admin_api
metadata = _metadata_with_prefix(self.name)
try:
api.get_instance(self.name, metadata=metadata)
except NotFound:
return False
return True | [
"def",
"exists",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"_client",
".",
"instance_admin_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"try",
":",
"api",
".",
"get_instance",
"(",
"self",
".",
"name",
",",
"metadata",
"=",
"metadata",
")",
"except",
"NotFound",
":",
"return",
"False",
"return",
"True"
] | Test whether this instance exists.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig
:rtype: bool
:returns: True if the instance exists, else false | [
"Test",
"whether",
"this",
"instance",
"exists",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/instance.py#L223-L240 |
28,055 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/instance.py | Instance.update | def update(self):
"""Update this instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance
.. note::
Updates the ``display_name`` and ``node_count``. To change those
values before updating, set them via
.. code:: python
instance.display_name = 'New display name'
instance.node_count = 5
before calling :meth:`update`.
:rtype: :class:`google.api_core.operation.Operation`
:returns: an operation instance
:raises NotFound: if the instance does not exist
"""
api = self._client.instance_admin_api
instance_pb = admin_v1_pb2.Instance(
name=self.name,
config=self.configuration_name,
display_name=self.display_name,
node_count=self.node_count,
)
field_mask = FieldMask(paths=["config", "display_name", "node_count"])
metadata = _metadata_with_prefix(self.name)
future = api.update_instance(
instance=instance_pb, field_mask=field_mask, metadata=metadata
)
return future | python | def update(self):
"""Update this instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance
.. note::
Updates the ``display_name`` and ``node_count``. To change those
values before updating, set them via
.. code:: python
instance.display_name = 'New display name'
instance.node_count = 5
before calling :meth:`update`.
:rtype: :class:`google.api_core.operation.Operation`
:returns: an operation instance
:raises NotFound: if the instance does not exist
"""
api = self._client.instance_admin_api
instance_pb = admin_v1_pb2.Instance(
name=self.name,
config=self.configuration_name,
display_name=self.display_name,
node_count=self.node_count,
)
field_mask = FieldMask(paths=["config", "display_name", "node_count"])
metadata = _metadata_with_prefix(self.name)
future = api.update_instance(
instance=instance_pb, field_mask=field_mask, metadata=metadata
)
return future | [
"def",
"update",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"_client",
".",
"instance_admin_api",
"instance_pb",
"=",
"admin_v1_pb2",
".",
"Instance",
"(",
"name",
"=",
"self",
".",
"name",
",",
"config",
"=",
"self",
".",
"configuration_name",
",",
"display_name",
"=",
"self",
".",
"display_name",
",",
"node_count",
"=",
"self",
".",
"node_count",
",",
")",
"field_mask",
"=",
"FieldMask",
"(",
"paths",
"=",
"[",
"\"config\"",
",",
"\"display_name\"",
",",
"\"node_count\"",
"]",
")",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"future",
"=",
"api",
".",
"update_instance",
"(",
"instance",
"=",
"instance_pb",
",",
"field_mask",
"=",
"field_mask",
",",
"metadata",
"=",
"metadata",
")",
"return",
"future"
] | Update this instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance
.. note::
Updates the ``display_name`` and ``node_count``. To change those
values before updating, set them via
.. code:: python
instance.display_name = 'New display name'
instance.node_count = 5
before calling :meth:`update`.
:rtype: :class:`google.api_core.operation.Operation`
:returns: an operation instance
:raises NotFound: if the instance does not exist | [
"Update",
"this",
"instance",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/instance.py#L257-L293 |
28,056 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/instance.py | Instance.delete | def delete(self):
"""Mark an instance and all of its databases for permanent deletion.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstance
Immediately upon completion of the request:
* Billing will cease for all of the instance's reserved resources.
Soon afterward:
* The instance and all databases within the instance will be deleteed.
All data in the databases will be permanently deleted.
"""
api = self._client.instance_admin_api
metadata = _metadata_with_prefix(self.name)
api.delete_instance(self.name, metadata=metadata) | python | def delete(self):
"""Mark an instance and all of its databases for permanent deletion.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstance
Immediately upon completion of the request:
* Billing will cease for all of the instance's reserved resources.
Soon afterward:
* The instance and all databases within the instance will be deleteed.
All data in the databases will be permanently deleted.
"""
api = self._client.instance_admin_api
metadata = _metadata_with_prefix(self.name)
api.delete_instance(self.name, metadata=metadata) | [
"def",
"delete",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"_client",
".",
"instance_admin_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"api",
".",
"delete_instance",
"(",
"self",
".",
"name",
",",
"metadata",
"=",
"metadata",
")"
] | Mark an instance and all of its databases for permanent deletion.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstance
Immediately upon completion of the request:
* Billing will cease for all of the instance's reserved resources.
Soon afterward:
* The instance and all databases within the instance will be deleteed.
All data in the databases will be permanently deleted. | [
"Mark",
"an",
"instance",
"and",
"all",
"of",
"its",
"databases",
"for",
"permanent",
"deletion",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/instance.py#L295-L313 |
28,057 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/instance.py | Instance.database | def database(self, database_id, ddl_statements=(), pool=None):
"""Factory to create a database within this instance.
:type database_id: str
:param database_id: The ID of the instance.
:type ddl_statements: list of string
:param ddl_statements: (Optional) DDL statements, excluding the
'CREATE DATABSE' statement.
:type pool: concrete subclass of
:class:`~google.cloud.spanner_v1.pool.AbstractSessionPool`.
:param pool: (Optional) session pool to be used by database.
:rtype: :class:`~google.cloud.spanner_v1.database.Database`
:returns: a database owned by this instance.
"""
return Database(database_id, self, ddl_statements=ddl_statements, pool=pool) | python | def database(self, database_id, ddl_statements=(), pool=None):
"""Factory to create a database within this instance.
:type database_id: str
:param database_id: The ID of the instance.
:type ddl_statements: list of string
:param ddl_statements: (Optional) DDL statements, excluding the
'CREATE DATABSE' statement.
:type pool: concrete subclass of
:class:`~google.cloud.spanner_v1.pool.AbstractSessionPool`.
:param pool: (Optional) session pool to be used by database.
:rtype: :class:`~google.cloud.spanner_v1.database.Database`
:returns: a database owned by this instance.
"""
return Database(database_id, self, ddl_statements=ddl_statements, pool=pool) | [
"def",
"database",
"(",
"self",
",",
"database_id",
",",
"ddl_statements",
"=",
"(",
")",
",",
"pool",
"=",
"None",
")",
":",
"return",
"Database",
"(",
"database_id",
",",
"self",
",",
"ddl_statements",
"=",
"ddl_statements",
",",
"pool",
"=",
"pool",
")"
] | Factory to create a database within this instance.
:type database_id: str
:param database_id: The ID of the instance.
:type ddl_statements: list of string
:param ddl_statements: (Optional) DDL statements, excluding the
'CREATE DATABSE' statement.
:type pool: concrete subclass of
:class:`~google.cloud.spanner_v1.pool.AbstractSessionPool`.
:param pool: (Optional) session pool to be used by database.
:rtype: :class:`~google.cloud.spanner_v1.database.Database`
:returns: a database owned by this instance. | [
"Factory",
"to",
"create",
"a",
"database",
"within",
"this",
"instance",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/instance.py#L315-L332 |
28,058 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/instance.py | Instance.list_databases | def list_databases(self, page_size=None, page_token=None):
"""List databases for the instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases
:type page_size: int
:param page_size:
Optional. The maximum number of databases 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 databases, 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.
:rtype: :class:`~google.api._ore.page_iterator.Iterator`
:returns:
Iterator of :class:`~google.cloud.spanner_v1.database.Database`
resources within the current instance.
"""
metadata = _metadata_with_prefix(self.name)
page_iter = self._client.database_admin_api.list_databases(
self.name, page_size=page_size, metadata=metadata
)
page_iter.next_page_token = page_token
page_iter.item_to_value = self._item_to_database
return page_iter | python | def list_databases(self, page_size=None, page_token=None):
"""List databases for the instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases
:type page_size: int
:param page_size:
Optional. The maximum number of databases 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 databases, 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.
:rtype: :class:`~google.api._ore.page_iterator.Iterator`
:returns:
Iterator of :class:`~google.cloud.spanner_v1.database.Database`
resources within the current instance.
"""
metadata = _metadata_with_prefix(self.name)
page_iter = self._client.database_admin_api.list_databases(
self.name, page_size=page_size, metadata=metadata
)
page_iter.next_page_token = page_token
page_iter.item_to_value = self._item_to_database
return page_iter | [
"def",
"list_databases",
"(",
"self",
",",
"page_size",
"=",
"None",
",",
"page_token",
"=",
"None",
")",
":",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"page_iter",
"=",
"self",
".",
"_client",
".",
"database_admin_api",
".",
"list_databases",
"(",
"self",
".",
"name",
",",
"page_size",
"=",
"page_size",
",",
"metadata",
"=",
"metadata",
")",
"page_iter",
".",
"next_page_token",
"=",
"page_token",
"page_iter",
".",
"item_to_value",
"=",
"self",
".",
"_item_to_database",
"return",
"page_iter"
] | List databases for the instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases
:type page_size: int
:param page_size:
Optional. The maximum number of databases 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 databases, 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.
:rtype: :class:`~google.api._ore.page_iterator.Iterator`
:returns:
Iterator of :class:`~google.cloud.spanner_v1.database.Database`
resources within the current instance. | [
"List",
"databases",
"for",
"the",
"instance",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/instance.py#L334-L365 |
28,059 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/instance.py | Instance._item_to_database | def _item_to_database(self, iterator, database_pb):
"""Convert a database protobuf to the native object.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type database_pb: :class:`~google.spanner.admin.database.v1.Database`
:param database_pb: A database returned from the API.
:rtype: :class:`~google.cloud.spanner_v1.database.Database`
:returns: The next database in the page.
"""
return Database.from_pb(database_pb, self, pool=BurstyPool()) | python | def _item_to_database(self, iterator, database_pb):
"""Convert a database protobuf to the native object.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type database_pb: :class:`~google.spanner.admin.database.v1.Database`
:param database_pb: A database returned from the API.
:rtype: :class:`~google.cloud.spanner_v1.database.Database`
:returns: The next database in the page.
"""
return Database.from_pb(database_pb, self, pool=BurstyPool()) | [
"def",
"_item_to_database",
"(",
"self",
",",
"iterator",
",",
"database_pb",
")",
":",
"return",
"Database",
".",
"from_pb",
"(",
"database_pb",
",",
"self",
",",
"pool",
"=",
"BurstyPool",
"(",
")",
")"
] | Convert a database protobuf to the native object.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type database_pb: :class:`~google.spanner.admin.database.v1.Database`
:param database_pb: A database returned from the API.
:rtype: :class:`~google.cloud.spanner_v1.database.Database`
:returns: The next database in the page. | [
"Convert",
"a",
"database",
"protobuf",
"to",
"the",
"native",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/instance.py#L367-L379 |
28,060 | googleapis/google-cloud-python | api_core/google/api_core/future/polling.py | PollingFuture._blocking_poll | def _blocking_poll(self, timeout=None):
"""Poll and wait for the Future to be resolved.
Args:
timeout (int):
How long (in seconds) to wait for the operation to complete.
If None, wait indefinitely.
"""
if self._result_set:
return
retry_ = self._retry.with_deadline(timeout)
try:
retry_(self._done_or_raise)()
except exceptions.RetryError:
raise concurrent.futures.TimeoutError(
"Operation did not complete within the designated " "timeout."
) | python | def _blocking_poll(self, timeout=None):
"""Poll and wait for the Future to be resolved.
Args:
timeout (int):
How long (in seconds) to wait for the operation to complete.
If None, wait indefinitely.
"""
if self._result_set:
return
retry_ = self._retry.with_deadline(timeout)
try:
retry_(self._done_or_raise)()
except exceptions.RetryError:
raise concurrent.futures.TimeoutError(
"Operation did not complete within the designated " "timeout."
) | [
"def",
"_blocking_poll",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"_result_set",
":",
"return",
"retry_",
"=",
"self",
".",
"_retry",
".",
"with_deadline",
"(",
"timeout",
")",
"try",
":",
"retry_",
"(",
"self",
".",
"_done_or_raise",
")",
"(",
")",
"except",
"exceptions",
".",
"RetryError",
":",
"raise",
"concurrent",
".",
"futures",
".",
"TimeoutError",
"(",
"\"Operation did not complete within the designated \"",
"\"timeout.\"",
")"
] | Poll and wait for the Future to be resolved.
Args:
timeout (int):
How long (in seconds) to wait for the operation to complete.
If None, wait indefinitely. | [
"Poll",
"and",
"wait",
"for",
"the",
"Future",
"to",
"be",
"resolved",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/future/polling.py#L87-L105 |
28,061 | googleapis/google-cloud-python | api_core/google/api_core/future/polling.py | PollingFuture.result | def result(self, timeout=None):
"""Get the result of the operation, blocking if necessary.
Args:
timeout (int):
How long (in seconds) to wait for the operation to complete.
If None, wait indefinitely.
Returns:
google.protobuf.Message: The Operation's result.
Raises:
google.api_core.GoogleAPICallError: If the operation errors or if
the timeout is reached before the operation completes.
"""
self._blocking_poll(timeout=timeout)
if self._exception is not None:
# pylint: disable=raising-bad-type
# Pylint doesn't recognize that this is valid in this case.
raise self._exception
return self._result | python | def result(self, timeout=None):
"""Get the result of the operation, blocking if necessary.
Args:
timeout (int):
How long (in seconds) to wait for the operation to complete.
If None, wait indefinitely.
Returns:
google.protobuf.Message: The Operation's result.
Raises:
google.api_core.GoogleAPICallError: If the operation errors or if
the timeout is reached before the operation completes.
"""
self._blocking_poll(timeout=timeout)
if self._exception is not None:
# pylint: disable=raising-bad-type
# Pylint doesn't recognize that this is valid in this case.
raise self._exception
return self._result | [
"def",
"result",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_blocking_poll",
"(",
"timeout",
"=",
"timeout",
")",
"if",
"self",
".",
"_exception",
"is",
"not",
"None",
":",
"# pylint: disable=raising-bad-type",
"# Pylint doesn't recognize that this is valid in this case.",
"raise",
"self",
".",
"_exception",
"return",
"self",
".",
"_result"
] | Get the result of the operation, blocking if necessary.
Args:
timeout (int):
How long (in seconds) to wait for the operation to complete.
If None, wait indefinitely.
Returns:
google.protobuf.Message: The Operation's result.
Raises:
google.api_core.GoogleAPICallError: If the operation errors or if
the timeout is reached before the operation completes. | [
"Get",
"the",
"result",
"of",
"the",
"operation",
"blocking",
"if",
"necessary",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/future/polling.py#L107-L129 |
28,062 | googleapis/google-cloud-python | api_core/google/api_core/future/polling.py | PollingFuture.add_done_callback | def add_done_callback(self, fn):
"""Add a callback to be executed when the operation is complete.
If the operation is not already complete, this will start a helper
thread to poll for the status of the operation in the background.
Args:
fn (Callable[Future]): The callback to execute when the operation
is complete.
"""
if self._result_set:
_helpers.safe_invoke_callback(fn, self)
return
self._done_callbacks.append(fn)
if self._polling_thread is None:
# The polling thread will exit on its own as soon as the operation
# is done.
self._polling_thread = _helpers.start_daemon_thread(
target=self._blocking_poll
) | python | def add_done_callback(self, fn):
"""Add a callback to be executed when the operation is complete.
If the operation is not already complete, this will start a helper
thread to poll for the status of the operation in the background.
Args:
fn (Callable[Future]): The callback to execute when the operation
is complete.
"""
if self._result_set:
_helpers.safe_invoke_callback(fn, self)
return
self._done_callbacks.append(fn)
if self._polling_thread is None:
# The polling thread will exit on its own as soon as the operation
# is done.
self._polling_thread = _helpers.start_daemon_thread(
target=self._blocking_poll
) | [
"def",
"add_done_callback",
"(",
"self",
",",
"fn",
")",
":",
"if",
"self",
".",
"_result_set",
":",
"_helpers",
".",
"safe_invoke_callback",
"(",
"fn",
",",
"self",
")",
"return",
"self",
".",
"_done_callbacks",
".",
"append",
"(",
"fn",
")",
"if",
"self",
".",
"_polling_thread",
"is",
"None",
":",
"# The polling thread will exit on its own as soon as the operation",
"# is done.",
"self",
".",
"_polling_thread",
"=",
"_helpers",
".",
"start_daemon_thread",
"(",
"target",
"=",
"self",
".",
"_blocking_poll",
")"
] | Add a callback to be executed when the operation is complete.
If the operation is not already complete, this will start a helper
thread to poll for the status of the operation in the background.
Args:
fn (Callable[Future]): The callback to execute when the operation
is complete. | [
"Add",
"a",
"callback",
"to",
"be",
"executed",
"when",
"the",
"operation",
"is",
"complete",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/future/polling.py#L145-L166 |
28,063 | googleapis/google-cloud-python | api_core/google/api_core/future/polling.py | PollingFuture._invoke_callbacks | def _invoke_callbacks(self, *args, **kwargs):
"""Invoke all done callbacks."""
for callback in self._done_callbacks:
_helpers.safe_invoke_callback(callback, *args, **kwargs) | python | def _invoke_callbacks(self, *args, **kwargs):
"""Invoke all done callbacks."""
for callback in self._done_callbacks:
_helpers.safe_invoke_callback(callback, *args, **kwargs) | [
"def",
"_invoke_callbacks",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"callback",
"in",
"self",
".",
"_done_callbacks",
":",
"_helpers",
".",
"safe_invoke_callback",
"(",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Invoke all done callbacks. | [
"Invoke",
"all",
"done",
"callbacks",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/future/polling.py#L168-L171 |
28,064 | googleapis/google-cloud-python | api_core/google/api_core/future/polling.py | PollingFuture.set_result | def set_result(self, result):
"""Set the Future's result."""
self._result = result
self._result_set = True
self._invoke_callbacks(self) | python | def set_result(self, result):
"""Set the Future's result."""
self._result = result
self._result_set = True
self._invoke_callbacks(self) | [
"def",
"set_result",
"(",
"self",
",",
"result",
")",
":",
"self",
".",
"_result",
"=",
"result",
"self",
".",
"_result_set",
"=",
"True",
"self",
".",
"_invoke_callbacks",
"(",
"self",
")"
] | Set the Future's result. | [
"Set",
"the",
"Future",
"s",
"result",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/future/polling.py#L173-L177 |
28,065 | googleapis/google-cloud-python | api_core/google/api_core/future/polling.py | PollingFuture.set_exception | def set_exception(self, exception):
"""Set the Future's exception."""
self._exception = exception
self._result_set = True
self._invoke_callbacks(self) | python | def set_exception(self, exception):
"""Set the Future's exception."""
self._exception = exception
self._result_set = True
self._invoke_callbacks(self) | [
"def",
"set_exception",
"(",
"self",
",",
"exception",
")",
":",
"self",
".",
"_exception",
"=",
"exception",
"self",
".",
"_result_set",
"=",
"True",
"self",
".",
"_invoke_callbacks",
"(",
"self",
")"
] | Set the Future's exception. | [
"Set",
"the",
"Future",
"s",
"exception",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/future/polling.py#L179-L183 |
28,066 | googleapis/google-cloud-python | logging/docs/snippets.py | instantiate_client | def instantiate_client(_unused_client, _unused_to_delete):
"""Instantiate client."""
# [START client_create_default]
from google.cloud import logging
client = logging.Client()
# [END client_create_default]
credentials = object()
# [START client_create_explicit]
from google.cloud import logging
client = logging.Client(project="my-project", credentials=credentials) | python | def instantiate_client(_unused_client, _unused_to_delete):
"""Instantiate client."""
# [START client_create_default]
from google.cloud import logging
client = logging.Client()
# [END client_create_default]
credentials = object()
# [START client_create_explicit]
from google.cloud import logging
client = logging.Client(project="my-project", credentials=credentials) | [
"def",
"instantiate_client",
"(",
"_unused_client",
",",
"_unused_to_delete",
")",
":",
"# [START client_create_default]",
"from",
"google",
".",
"cloud",
"import",
"logging",
"client",
"=",
"logging",
".",
"Client",
"(",
")",
"# [END client_create_default]",
"credentials",
"=",
"object",
"(",
")",
"# [START client_create_explicit]",
"from",
"google",
".",
"cloud",
"import",
"logging",
"client",
"=",
"logging",
".",
"Client",
"(",
"project",
"=",
"\"my-project\"",
",",
"credentials",
"=",
"credentials",
")"
] | Instantiate client. | [
"Instantiate",
"client",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/docs/snippets.py#L47-L60 |
28,067 | googleapis/google-cloud-python | logging/docs/snippets.py | client_list_entries | def client_list_entries(client, to_delete): # pylint: disable=unused-argument
"""List entries via client."""
# [START client_list_entries_default]
for entry in client.list_entries(): # API call(s)
do_something_with(entry)
# [END client_list_entries_default]
# [START client_list_entries_filter]
FILTER = "logName:log_name AND textPayload:simple"
for entry in client.list_entries(filter_=FILTER): # API call(s)
do_something_with(entry)
# [END client_list_entries_filter]
# [START client_list_entries_order_by]
from google.cloud.logging import DESCENDING
for entry in client.list_entries(order_by=DESCENDING): # API call(s)
do_something_with(entry)
# [END client_list_entries_order_by]
# [START client_list_entries_paged]
iterator = client.list_entries()
pages = iterator.pages
page1 = next(pages) # API call
for entry in page1:
do_something_with(entry)
page2 = next(pages) # API call
for entry in page2:
do_something_with(entry) | python | def client_list_entries(client, to_delete): # pylint: disable=unused-argument
"""List entries via client."""
# [START client_list_entries_default]
for entry in client.list_entries(): # API call(s)
do_something_with(entry)
# [END client_list_entries_default]
# [START client_list_entries_filter]
FILTER = "logName:log_name AND textPayload:simple"
for entry in client.list_entries(filter_=FILTER): # API call(s)
do_something_with(entry)
# [END client_list_entries_filter]
# [START client_list_entries_order_by]
from google.cloud.logging import DESCENDING
for entry in client.list_entries(order_by=DESCENDING): # API call(s)
do_something_with(entry)
# [END client_list_entries_order_by]
# [START client_list_entries_paged]
iterator = client.list_entries()
pages = iterator.pages
page1 = next(pages) # API call
for entry in page1:
do_something_with(entry)
page2 = next(pages) # API call
for entry in page2:
do_something_with(entry) | [
"def",
"client_list_entries",
"(",
"client",
",",
"to_delete",
")",
":",
"# pylint: disable=unused-argument",
"# [START client_list_entries_default]",
"for",
"entry",
"in",
"client",
".",
"list_entries",
"(",
")",
":",
"# API call(s)",
"do_something_with",
"(",
"entry",
")",
"# [END client_list_entries_default]",
"# [START client_list_entries_filter]",
"FILTER",
"=",
"\"logName:log_name AND textPayload:simple\"",
"for",
"entry",
"in",
"client",
".",
"list_entries",
"(",
"filter_",
"=",
"FILTER",
")",
":",
"# API call(s)",
"do_something_with",
"(",
"entry",
")",
"# [END client_list_entries_filter]",
"# [START client_list_entries_order_by]",
"from",
"google",
".",
"cloud",
".",
"logging",
"import",
"DESCENDING",
"for",
"entry",
"in",
"client",
".",
"list_entries",
"(",
"order_by",
"=",
"DESCENDING",
")",
":",
"# API call(s)",
"do_something_with",
"(",
"entry",
")",
"# [END client_list_entries_order_by]",
"# [START client_list_entries_paged]",
"iterator",
"=",
"client",
".",
"list_entries",
"(",
")",
"pages",
"=",
"iterator",
".",
"pages",
"page1",
"=",
"next",
"(",
"pages",
")",
"# API call",
"for",
"entry",
"in",
"page1",
":",
"do_something_with",
"(",
"entry",
")",
"page2",
"=",
"next",
"(",
"pages",
")",
"# API call",
"for",
"entry",
"in",
"page2",
":",
"do_something_with",
"(",
"entry",
")"
] | List entries via client. | [
"List",
"entries",
"via",
"client",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/docs/snippets.py#L68-L99 |
28,068 | googleapis/google-cloud-python | logging/docs/snippets.py | client_list_entries_multi_project | def client_list_entries_multi_project(
client, to_delete
): # pylint: disable=unused-argument
"""List entries via client across multiple projects."""
# [START client_list_entries_multi_project]
PROJECT_IDS = ["one-project", "another-project"]
for entry in client.list_entries(project_ids=PROJECT_IDS): # API call(s)
do_something_with(entry) | python | def client_list_entries_multi_project(
client, to_delete
): # pylint: disable=unused-argument
"""List entries via client across multiple projects."""
# [START client_list_entries_multi_project]
PROJECT_IDS = ["one-project", "another-project"]
for entry in client.list_entries(project_ids=PROJECT_IDS): # API call(s)
do_something_with(entry) | [
"def",
"client_list_entries_multi_project",
"(",
"client",
",",
"to_delete",
")",
":",
"# pylint: disable=unused-argument",
"# [START client_list_entries_multi_project]",
"PROJECT_IDS",
"=",
"[",
"\"one-project\"",
",",
"\"another-project\"",
"]",
"for",
"entry",
"in",
"client",
".",
"list_entries",
"(",
"project_ids",
"=",
"PROJECT_IDS",
")",
":",
"# API call(s)",
"do_something_with",
"(",
"entry",
")"
] | List entries via client across multiple projects. | [
"List",
"entries",
"via",
"client",
"across",
"multiple",
"projects",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/docs/snippets.py#L104-L112 |
28,069 | googleapis/google-cloud-python | logging/docs/snippets.py | logger_usage | def logger_usage(client, to_delete):
"""Logger usage."""
LOG_NAME = "logger_usage_%d" % (_millis())
# [START logger_create]
logger = client.logger(LOG_NAME)
# [END logger_create]
to_delete.append(logger)
# [START logger_log_text]
logger.log_text("A simple entry") # API call
# [END logger_log_text]
# [START logger_log_struct]
logger.log_struct(
{"message": "My second entry", "weather": "partly cloudy"}
) # API call
# [END logger_log_struct]
# [START logger_log_resource_text]
from google.cloud.logging.resource import Resource
res = Resource(
type="generic_node",
labels={
"location": "us-central1-a",
"namespace": "default",
"node_id": "10.10.10.1",
},
)
logger.log_struct(
{"message": "My first entry", "weather": "partly cloudy"}, resource=res
)
# [END logger_log_resource_text]
# [START logger_list_entries]
from google.cloud.logging import DESCENDING
for entry in logger.list_entries(order_by=DESCENDING): # API call(s)
do_something_with(entry)
# [END logger_list_entries]
def _logger_delete():
# [START logger_delete]
logger.delete() # API call
# [END logger_delete]
_backoff_not_found(_logger_delete)
to_delete.remove(logger) | python | def logger_usage(client, to_delete):
"""Logger usage."""
LOG_NAME = "logger_usage_%d" % (_millis())
# [START logger_create]
logger = client.logger(LOG_NAME)
# [END logger_create]
to_delete.append(logger)
# [START logger_log_text]
logger.log_text("A simple entry") # API call
# [END logger_log_text]
# [START logger_log_struct]
logger.log_struct(
{"message": "My second entry", "weather": "partly cloudy"}
) # API call
# [END logger_log_struct]
# [START logger_log_resource_text]
from google.cloud.logging.resource import Resource
res = Resource(
type="generic_node",
labels={
"location": "us-central1-a",
"namespace": "default",
"node_id": "10.10.10.1",
},
)
logger.log_struct(
{"message": "My first entry", "weather": "partly cloudy"}, resource=res
)
# [END logger_log_resource_text]
# [START logger_list_entries]
from google.cloud.logging import DESCENDING
for entry in logger.list_entries(order_by=DESCENDING): # API call(s)
do_something_with(entry)
# [END logger_list_entries]
def _logger_delete():
# [START logger_delete]
logger.delete() # API call
# [END logger_delete]
_backoff_not_found(_logger_delete)
to_delete.remove(logger) | [
"def",
"logger_usage",
"(",
"client",
",",
"to_delete",
")",
":",
"LOG_NAME",
"=",
"\"logger_usage_%d\"",
"%",
"(",
"_millis",
"(",
")",
")",
"# [START logger_create]",
"logger",
"=",
"client",
".",
"logger",
"(",
"LOG_NAME",
")",
"# [END logger_create]",
"to_delete",
".",
"append",
"(",
"logger",
")",
"# [START logger_log_text]",
"logger",
".",
"log_text",
"(",
"\"A simple entry\"",
")",
"# API call",
"# [END logger_log_text]",
"# [START logger_log_struct]",
"logger",
".",
"log_struct",
"(",
"{",
"\"message\"",
":",
"\"My second entry\"",
",",
"\"weather\"",
":",
"\"partly cloudy\"",
"}",
")",
"# API call",
"# [END logger_log_struct]",
"# [START logger_log_resource_text]",
"from",
"google",
".",
"cloud",
".",
"logging",
".",
"resource",
"import",
"Resource",
"res",
"=",
"Resource",
"(",
"type",
"=",
"\"generic_node\"",
",",
"labels",
"=",
"{",
"\"location\"",
":",
"\"us-central1-a\"",
",",
"\"namespace\"",
":",
"\"default\"",
",",
"\"node_id\"",
":",
"\"10.10.10.1\"",
",",
"}",
",",
")",
"logger",
".",
"log_struct",
"(",
"{",
"\"message\"",
":",
"\"My first entry\"",
",",
"\"weather\"",
":",
"\"partly cloudy\"",
"}",
",",
"resource",
"=",
"res",
")",
"# [END logger_log_resource_text]",
"# [START logger_list_entries]",
"from",
"google",
".",
"cloud",
".",
"logging",
"import",
"DESCENDING",
"for",
"entry",
"in",
"logger",
".",
"list_entries",
"(",
"order_by",
"=",
"DESCENDING",
")",
":",
"# API call(s)",
"do_something_with",
"(",
"entry",
")",
"# [END logger_list_entries]",
"def",
"_logger_delete",
"(",
")",
":",
"# [START logger_delete]",
"logger",
".",
"delete",
"(",
")",
"# API call",
"# [END logger_delete]",
"_backoff_not_found",
"(",
"_logger_delete",
")",
"to_delete",
".",
"remove",
"(",
"logger",
")"
] | Logger usage. | [
"Logger",
"usage",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/docs/snippets.py#L117-L165 |
28,070 | googleapis/google-cloud-python | logging/docs/snippets.py | metric_crud | def metric_crud(client, to_delete):
"""Metric CRUD."""
METRIC_NAME = "robots-%d" % (_millis(),)
DESCRIPTION = "Robots all up in your server"
FILTER = "logName:apache-access AND textPayload:robot"
UPDATED_FILTER = "textPayload:robot"
UPDATED_DESCRIPTION = "Danger, Will Robinson!"
# [START client_list_metrics]
for metric in client.list_metrics(): # API call(s)
do_something_with(metric)
# [END client_list_metrics]
# [START metric_create]
metric = client.metric(METRIC_NAME, filter_=FILTER, description=DESCRIPTION)
assert not metric.exists() # API call
metric.create() # API call
assert metric.exists() # API call
# [END metric_create]
to_delete.append(metric)
# [START metric_reload]
existing_metric = client.metric(METRIC_NAME)
existing_metric.reload() # API call
# [END metric_reload]
assert existing_metric.filter_ == FILTER
assert existing_metric.description == DESCRIPTION
# [START metric_update]
existing_metric.filter_ = UPDATED_FILTER
existing_metric.description = UPDATED_DESCRIPTION
existing_metric.update() # API call
# [END metric_update]
existing_metric.reload()
assert existing_metric.filter_ == UPDATED_FILTER
assert existing_metric.description == UPDATED_DESCRIPTION
def _metric_delete():
# [START metric_delete]
metric.delete()
# [END metric_delete]
_backoff_not_found(_metric_delete)
to_delete.remove(metric) | python | def metric_crud(client, to_delete):
"""Metric CRUD."""
METRIC_NAME = "robots-%d" % (_millis(),)
DESCRIPTION = "Robots all up in your server"
FILTER = "logName:apache-access AND textPayload:robot"
UPDATED_FILTER = "textPayload:robot"
UPDATED_DESCRIPTION = "Danger, Will Robinson!"
# [START client_list_metrics]
for metric in client.list_metrics(): # API call(s)
do_something_with(metric)
# [END client_list_metrics]
# [START metric_create]
metric = client.metric(METRIC_NAME, filter_=FILTER, description=DESCRIPTION)
assert not metric.exists() # API call
metric.create() # API call
assert metric.exists() # API call
# [END metric_create]
to_delete.append(metric)
# [START metric_reload]
existing_metric = client.metric(METRIC_NAME)
existing_metric.reload() # API call
# [END metric_reload]
assert existing_metric.filter_ == FILTER
assert existing_metric.description == DESCRIPTION
# [START metric_update]
existing_metric.filter_ = UPDATED_FILTER
existing_metric.description = UPDATED_DESCRIPTION
existing_metric.update() # API call
# [END metric_update]
existing_metric.reload()
assert existing_metric.filter_ == UPDATED_FILTER
assert existing_metric.description == UPDATED_DESCRIPTION
def _metric_delete():
# [START metric_delete]
metric.delete()
# [END metric_delete]
_backoff_not_found(_metric_delete)
to_delete.remove(metric) | [
"def",
"metric_crud",
"(",
"client",
",",
"to_delete",
")",
":",
"METRIC_NAME",
"=",
"\"robots-%d\"",
"%",
"(",
"_millis",
"(",
")",
",",
")",
"DESCRIPTION",
"=",
"\"Robots all up in your server\"",
"FILTER",
"=",
"\"logName:apache-access AND textPayload:robot\"",
"UPDATED_FILTER",
"=",
"\"textPayload:robot\"",
"UPDATED_DESCRIPTION",
"=",
"\"Danger, Will Robinson!\"",
"# [START client_list_metrics]",
"for",
"metric",
"in",
"client",
".",
"list_metrics",
"(",
")",
":",
"# API call(s)",
"do_something_with",
"(",
"metric",
")",
"# [END client_list_metrics]",
"# [START metric_create]",
"metric",
"=",
"client",
".",
"metric",
"(",
"METRIC_NAME",
",",
"filter_",
"=",
"FILTER",
",",
"description",
"=",
"DESCRIPTION",
")",
"assert",
"not",
"metric",
".",
"exists",
"(",
")",
"# API call",
"metric",
".",
"create",
"(",
")",
"# API call",
"assert",
"metric",
".",
"exists",
"(",
")",
"# API call",
"# [END metric_create]",
"to_delete",
".",
"append",
"(",
"metric",
")",
"# [START metric_reload]",
"existing_metric",
"=",
"client",
".",
"metric",
"(",
"METRIC_NAME",
")",
"existing_metric",
".",
"reload",
"(",
")",
"# API call",
"# [END metric_reload]",
"assert",
"existing_metric",
".",
"filter_",
"==",
"FILTER",
"assert",
"existing_metric",
".",
"description",
"==",
"DESCRIPTION",
"# [START metric_update]",
"existing_metric",
".",
"filter_",
"=",
"UPDATED_FILTER",
"existing_metric",
".",
"description",
"=",
"UPDATED_DESCRIPTION",
"existing_metric",
".",
"update",
"(",
")",
"# API call",
"# [END metric_update]",
"existing_metric",
".",
"reload",
"(",
")",
"assert",
"existing_metric",
".",
"filter_",
"==",
"UPDATED_FILTER",
"assert",
"existing_metric",
".",
"description",
"==",
"UPDATED_DESCRIPTION",
"def",
"_metric_delete",
"(",
")",
":",
"# [START metric_delete]",
"metric",
".",
"delete",
"(",
")",
"# [END metric_delete]",
"_backoff_not_found",
"(",
"_metric_delete",
")",
"to_delete",
".",
"remove",
"(",
"metric",
")"
] | Metric CRUD. | [
"Metric",
"CRUD",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/docs/snippets.py#L169-L212 |
28,071 | googleapis/google-cloud-python | logging/docs/snippets.py | sink_storage | def sink_storage(client, to_delete):
"""Sink log entries to storage."""
bucket = _sink_storage_setup(client)
to_delete.append(bucket)
SINK_NAME = "robots-storage-%d" % (_millis(),)
FILTER = "textPayload:robot"
# [START sink_storage_create]
DESTINATION = "storage.googleapis.com/%s" % (bucket.name,)
sink = client.sink(SINK_NAME, filter_=FILTER, destination=DESTINATION)
assert not sink.exists() # API call
sink.create() # API call
assert sink.exists() # API call
# [END sink_storage_create]
to_delete.insert(0, sink) | python | def sink_storage(client, to_delete):
"""Sink log entries to storage."""
bucket = _sink_storage_setup(client)
to_delete.append(bucket)
SINK_NAME = "robots-storage-%d" % (_millis(),)
FILTER = "textPayload:robot"
# [START sink_storage_create]
DESTINATION = "storage.googleapis.com/%s" % (bucket.name,)
sink = client.sink(SINK_NAME, filter_=FILTER, destination=DESTINATION)
assert not sink.exists() # API call
sink.create() # API call
assert sink.exists() # API call
# [END sink_storage_create]
to_delete.insert(0, sink) | [
"def",
"sink_storage",
"(",
"client",
",",
"to_delete",
")",
":",
"bucket",
"=",
"_sink_storage_setup",
"(",
"client",
")",
"to_delete",
".",
"append",
"(",
"bucket",
")",
"SINK_NAME",
"=",
"\"robots-storage-%d\"",
"%",
"(",
"_millis",
"(",
")",
",",
")",
"FILTER",
"=",
"\"textPayload:robot\"",
"# [START sink_storage_create]",
"DESTINATION",
"=",
"\"storage.googleapis.com/%s\"",
"%",
"(",
"bucket",
".",
"name",
",",
")",
"sink",
"=",
"client",
".",
"sink",
"(",
"SINK_NAME",
",",
"filter_",
"=",
"FILTER",
",",
"destination",
"=",
"DESTINATION",
")",
"assert",
"not",
"sink",
".",
"exists",
"(",
")",
"# API call",
"sink",
".",
"create",
"(",
")",
"# API call",
"assert",
"sink",
".",
"exists",
"(",
")",
"# API call",
"# [END sink_storage_create]",
"to_delete",
".",
"insert",
"(",
"0",
",",
"sink",
")"
] | Sink log entries to storage. | [
"Sink",
"log",
"entries",
"to",
"storage",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/docs/snippets.py#L235-L249 |
28,072 | googleapis/google-cloud-python | logging/docs/snippets.py | sink_bigquery | def sink_bigquery(client, to_delete):
"""Sink log entries to bigquery."""
dataset = _sink_bigquery_setup(client)
to_delete.append(dataset)
SINK_NAME = "robots-bigquery-%d" % (_millis(),)
FILTER = "textPayload:robot"
# [START sink_bigquery_create]
DESTINATION = "bigquery.googleapis.com%s" % (dataset.path,)
sink = client.sink(SINK_NAME, filter_=FILTER, destination=DESTINATION)
assert not sink.exists() # API call
sink.create() # API call
assert sink.exists() # API call
# [END sink_bigquery_create]
to_delete.insert(0, sink) | python | def sink_bigquery(client, to_delete):
"""Sink log entries to bigquery."""
dataset = _sink_bigquery_setup(client)
to_delete.append(dataset)
SINK_NAME = "robots-bigquery-%d" % (_millis(),)
FILTER = "textPayload:robot"
# [START sink_bigquery_create]
DESTINATION = "bigquery.googleapis.com%s" % (dataset.path,)
sink = client.sink(SINK_NAME, filter_=FILTER, destination=DESTINATION)
assert not sink.exists() # API call
sink.create() # API call
assert sink.exists() # API call
# [END sink_bigquery_create]
to_delete.insert(0, sink) | [
"def",
"sink_bigquery",
"(",
"client",
",",
"to_delete",
")",
":",
"dataset",
"=",
"_sink_bigquery_setup",
"(",
"client",
")",
"to_delete",
".",
"append",
"(",
"dataset",
")",
"SINK_NAME",
"=",
"\"robots-bigquery-%d\"",
"%",
"(",
"_millis",
"(",
")",
",",
")",
"FILTER",
"=",
"\"textPayload:robot\"",
"# [START sink_bigquery_create]",
"DESTINATION",
"=",
"\"bigquery.googleapis.com%s\"",
"%",
"(",
"dataset",
".",
"path",
",",
")",
"sink",
"=",
"client",
".",
"sink",
"(",
"SINK_NAME",
",",
"filter_",
"=",
"FILTER",
",",
"destination",
"=",
"DESTINATION",
")",
"assert",
"not",
"sink",
".",
"exists",
"(",
")",
"# API call",
"sink",
".",
"create",
"(",
")",
"# API call",
"assert",
"sink",
".",
"exists",
"(",
")",
"# API call",
"# [END sink_bigquery_create]",
"to_delete",
".",
"insert",
"(",
"0",
",",
"sink",
")"
] | Sink log entries to bigquery. | [
"Sink",
"log",
"entries",
"to",
"bigquery",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/docs/snippets.py#L274-L288 |
28,073 | googleapis/google-cloud-python | logging/docs/snippets.py | sink_pubsub | def sink_pubsub(client, to_delete):
"""Sink log entries to pubsub."""
topic = _sink_pubsub_setup(client)
to_delete.append(topic)
SINK_NAME = "robots-pubsub-%d" % (_millis(),)
FILTER = "logName:apache-access AND textPayload:robot"
UPDATED_FILTER = "textPayload:robot"
# [START sink_pubsub_create]
DESTINATION = "pubsub.googleapis.com/%s" % (topic.full_name,)
sink = client.sink(SINK_NAME, filter_=FILTER, destination=DESTINATION)
assert not sink.exists() # API call
sink.create() # API call
assert sink.exists() # API call
# [END sink_pubsub_create]
to_delete.insert(0, sink) # delete sink before topic
# [START client_list_sinks]
for sink in client.list_sinks(): # API call(s)
do_something_with(sink)
# [END client_list_sinks]
# [START sink_reload]
existing_sink = client.sink(SINK_NAME)
existing_sink.reload()
# [END sink_reload]
assert existing_sink.filter_ == FILTER
assert existing_sink.destination == DESTINATION
# [START sink_update]
existing_sink.filter_ = UPDATED_FILTER
existing_sink.update()
# [END sink_update]
existing_sink.reload()
assert existing_sink.filter_ == UPDATED_FILTER
# [START sink_delete]
sink.delete()
# [END sink_delete]
to_delete.pop(0) | python | def sink_pubsub(client, to_delete):
"""Sink log entries to pubsub."""
topic = _sink_pubsub_setup(client)
to_delete.append(topic)
SINK_NAME = "robots-pubsub-%d" % (_millis(),)
FILTER = "logName:apache-access AND textPayload:robot"
UPDATED_FILTER = "textPayload:robot"
# [START sink_pubsub_create]
DESTINATION = "pubsub.googleapis.com/%s" % (topic.full_name,)
sink = client.sink(SINK_NAME, filter_=FILTER, destination=DESTINATION)
assert not sink.exists() # API call
sink.create() # API call
assert sink.exists() # API call
# [END sink_pubsub_create]
to_delete.insert(0, sink) # delete sink before topic
# [START client_list_sinks]
for sink in client.list_sinks(): # API call(s)
do_something_with(sink)
# [END client_list_sinks]
# [START sink_reload]
existing_sink = client.sink(SINK_NAME)
existing_sink.reload()
# [END sink_reload]
assert existing_sink.filter_ == FILTER
assert existing_sink.destination == DESTINATION
# [START sink_update]
existing_sink.filter_ = UPDATED_FILTER
existing_sink.update()
# [END sink_update]
existing_sink.reload()
assert existing_sink.filter_ == UPDATED_FILTER
# [START sink_delete]
sink.delete()
# [END sink_delete]
to_delete.pop(0) | [
"def",
"sink_pubsub",
"(",
"client",
",",
"to_delete",
")",
":",
"topic",
"=",
"_sink_pubsub_setup",
"(",
"client",
")",
"to_delete",
".",
"append",
"(",
"topic",
")",
"SINK_NAME",
"=",
"\"robots-pubsub-%d\"",
"%",
"(",
"_millis",
"(",
")",
",",
")",
"FILTER",
"=",
"\"logName:apache-access AND textPayload:robot\"",
"UPDATED_FILTER",
"=",
"\"textPayload:robot\"",
"# [START sink_pubsub_create]",
"DESTINATION",
"=",
"\"pubsub.googleapis.com/%s\"",
"%",
"(",
"topic",
".",
"full_name",
",",
")",
"sink",
"=",
"client",
".",
"sink",
"(",
"SINK_NAME",
",",
"filter_",
"=",
"FILTER",
",",
"destination",
"=",
"DESTINATION",
")",
"assert",
"not",
"sink",
".",
"exists",
"(",
")",
"# API call",
"sink",
".",
"create",
"(",
")",
"# API call",
"assert",
"sink",
".",
"exists",
"(",
")",
"# API call",
"# [END sink_pubsub_create]",
"to_delete",
".",
"insert",
"(",
"0",
",",
"sink",
")",
"# delete sink before topic",
"# [START client_list_sinks]",
"for",
"sink",
"in",
"client",
".",
"list_sinks",
"(",
")",
":",
"# API call(s)",
"do_something_with",
"(",
"sink",
")",
"# [END client_list_sinks]",
"# [START sink_reload]",
"existing_sink",
"=",
"client",
".",
"sink",
"(",
"SINK_NAME",
")",
"existing_sink",
".",
"reload",
"(",
")",
"# [END sink_reload]",
"assert",
"existing_sink",
".",
"filter_",
"==",
"FILTER",
"assert",
"existing_sink",
".",
"destination",
"==",
"DESTINATION",
"# [START sink_update]",
"existing_sink",
".",
"filter_",
"=",
"UPDATED_FILTER",
"existing_sink",
".",
"update",
"(",
")",
"# [END sink_update]",
"existing_sink",
".",
"reload",
"(",
")",
"assert",
"existing_sink",
".",
"filter_",
"==",
"UPDATED_FILTER",
"# [START sink_delete]",
"sink",
".",
"delete",
"(",
")",
"# [END sink_delete]",
"to_delete",
".",
"pop",
"(",
"0",
")"
] | Sink log entries to pubsub. | [
"Sink",
"log",
"entries",
"to",
"pubsub",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/docs/snippets.py#L309-L348 |
28,074 | googleapis/google-cloud-python | core/google/cloud/obsolete.py | complain | def complain(distribution_name):
"""Issue a warning if `distribution_name` is installed.
In a future release, this method will be updated to raise ImportError
rather than just send a warning.
Args:
distribution_name (str): The name of the obsolete distribution.
"""
try:
pkg_resources.get_distribution(distribution_name)
warnings.warn(
"The {pkg} distribution is now obsolete. "
"Please `pip uninstall {pkg}`. "
"In the future, this warning will become an ImportError.".format(
pkg=distribution_name
),
DeprecationWarning,
)
except pkg_resources.DistributionNotFound:
pass | python | def complain(distribution_name):
"""Issue a warning if `distribution_name` is installed.
In a future release, this method will be updated to raise ImportError
rather than just send a warning.
Args:
distribution_name (str): The name of the obsolete distribution.
"""
try:
pkg_resources.get_distribution(distribution_name)
warnings.warn(
"The {pkg} distribution is now obsolete. "
"Please `pip uninstall {pkg}`. "
"In the future, this warning will become an ImportError.".format(
pkg=distribution_name
),
DeprecationWarning,
)
except pkg_resources.DistributionNotFound:
pass | [
"def",
"complain",
"(",
"distribution_name",
")",
":",
"try",
":",
"pkg_resources",
".",
"get_distribution",
"(",
"distribution_name",
")",
"warnings",
".",
"warn",
"(",
"\"The {pkg} distribution is now obsolete. \"",
"\"Please `pip uninstall {pkg}`. \"",
"\"In the future, this warning will become an ImportError.\"",
".",
"format",
"(",
"pkg",
"=",
"distribution_name",
")",
",",
"DeprecationWarning",
",",
")",
"except",
"pkg_resources",
".",
"DistributionNotFound",
":",
"pass"
] | Issue a warning if `distribution_name` is installed.
In a future release, this method will be updated to raise ImportError
rather than just send a warning.
Args:
distribution_name (str): The name of the obsolete distribution. | [
"Issue",
"a",
"warning",
"if",
"distribution_name",
"is",
"installed",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/obsolete.py#L22-L42 |
28,075 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | _get_encryption_headers | def _get_encryption_headers(key, source=False):
"""Builds customer encryption key headers
:type key: bytes
:param key: 32 byte key to build request key and hash.
:type source: bool
:param source: If true, return headers for the "source" blob; otherwise,
return headers for the "destination" blob.
:rtype: dict
:returns: dict of HTTP headers being sent in request.
"""
if key is None:
return {}
key = _to_bytes(key)
key_hash = hashlib.sha256(key).digest()
key_hash = base64.b64encode(key_hash)
key = base64.b64encode(key)
if source:
prefix = "X-Goog-Copy-Source-Encryption-"
else:
prefix = "X-Goog-Encryption-"
return {
prefix + "Algorithm": "AES256",
prefix + "Key": _bytes_to_unicode(key),
prefix + "Key-Sha256": _bytes_to_unicode(key_hash),
} | python | def _get_encryption_headers(key, source=False):
"""Builds customer encryption key headers
:type key: bytes
:param key: 32 byte key to build request key and hash.
:type source: bool
:param source: If true, return headers for the "source" blob; otherwise,
return headers for the "destination" blob.
:rtype: dict
:returns: dict of HTTP headers being sent in request.
"""
if key is None:
return {}
key = _to_bytes(key)
key_hash = hashlib.sha256(key).digest()
key_hash = base64.b64encode(key_hash)
key = base64.b64encode(key)
if source:
prefix = "X-Goog-Copy-Source-Encryption-"
else:
prefix = "X-Goog-Encryption-"
return {
prefix + "Algorithm": "AES256",
prefix + "Key": _bytes_to_unicode(key),
prefix + "Key-Sha256": _bytes_to_unicode(key_hash),
} | [
"def",
"_get_encryption_headers",
"(",
"key",
",",
"source",
"=",
"False",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"{",
"}",
"key",
"=",
"_to_bytes",
"(",
"key",
")",
"key_hash",
"=",
"hashlib",
".",
"sha256",
"(",
"key",
")",
".",
"digest",
"(",
")",
"key_hash",
"=",
"base64",
".",
"b64encode",
"(",
"key_hash",
")",
"key",
"=",
"base64",
".",
"b64encode",
"(",
"key",
")",
"if",
"source",
":",
"prefix",
"=",
"\"X-Goog-Copy-Source-Encryption-\"",
"else",
":",
"prefix",
"=",
"\"X-Goog-Encryption-\"",
"return",
"{",
"prefix",
"+",
"\"Algorithm\"",
":",
"\"AES256\"",
",",
"prefix",
"+",
"\"Key\"",
":",
"_bytes_to_unicode",
"(",
"key",
")",
",",
"prefix",
"+",
"\"Key-Sha256\"",
":",
"_bytes_to_unicode",
"(",
"key_hash",
")",
",",
"}"
] | Builds customer encryption key headers
:type key: bytes
:param key: 32 byte key to build request key and hash.
:type source: bool
:param source: If true, return headers for the "source" blob; otherwise,
return headers for the "destination" blob.
:rtype: dict
:returns: dict of HTTP headers being sent in request. | [
"Builds",
"customer",
"encryption",
"key",
"headers"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1953-L1983 |
28,076 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | _raise_from_invalid_response | def _raise_from_invalid_response(error):
"""Re-wrap and raise an ``InvalidResponse`` exception.
:type error: :exc:`google.resumable_media.InvalidResponse`
:param error: A caught exception from the ``google-resumable-media``
library.
:raises: :class:`~google.cloud.exceptions.GoogleCloudError` corresponding
to the failed status code
"""
response = error.response
error_message = str(error)
message = u"{method} {url}: {error}".format(
method=response.request.method, url=response.request.url, error=error_message
)
raise exceptions.from_http_status(response.status_code, message, response=response) | python | def _raise_from_invalid_response(error):
"""Re-wrap and raise an ``InvalidResponse`` exception.
:type error: :exc:`google.resumable_media.InvalidResponse`
:param error: A caught exception from the ``google-resumable-media``
library.
:raises: :class:`~google.cloud.exceptions.GoogleCloudError` corresponding
to the failed status code
"""
response = error.response
error_message = str(error)
message = u"{method} {url}: {error}".format(
method=response.request.method, url=response.request.url, error=error_message
)
raise exceptions.from_http_status(response.status_code, message, response=response) | [
"def",
"_raise_from_invalid_response",
"(",
"error",
")",
":",
"response",
"=",
"error",
".",
"response",
"error_message",
"=",
"str",
"(",
"error",
")",
"message",
"=",
"u\"{method} {url}: {error}\"",
".",
"format",
"(",
"method",
"=",
"response",
".",
"request",
".",
"method",
",",
"url",
"=",
"response",
".",
"request",
".",
"url",
",",
"error",
"=",
"error_message",
")",
"raise",
"exceptions",
".",
"from_http_status",
"(",
"response",
".",
"status_code",
",",
"message",
",",
"response",
"=",
"response",
")"
] | Re-wrap and raise an ``InvalidResponse`` exception.
:type error: :exc:`google.resumable_media.InvalidResponse`
:param error: A caught exception from the ``google-resumable-media``
library.
:raises: :class:`~google.cloud.exceptions.GoogleCloudError` corresponding
to the failed status code | [
"Re",
"-",
"wrap",
"and",
"raise",
"an",
"InvalidResponse",
"exception",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L2017-L2034 |
28,077 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | _add_query_parameters | def _add_query_parameters(base_url, name_value_pairs):
"""Add one query parameter to a base URL.
:type base_url: string
:param base_url: Base URL (may already contain query parameters)
:type name_value_pairs: list of (string, string) tuples.
:param name_value_pairs: Names and values of the query parameters to add
:rtype: string
:returns: URL with additional query strings appended.
"""
if len(name_value_pairs) == 0:
return base_url
scheme, netloc, path, query, frag = urlsplit(base_url)
query = parse_qsl(query)
query.extend(name_value_pairs)
return urlunsplit((scheme, netloc, path, urlencode(query), frag)) | python | def _add_query_parameters(base_url, name_value_pairs):
"""Add one query parameter to a base URL.
:type base_url: string
:param base_url: Base URL (may already contain query parameters)
:type name_value_pairs: list of (string, string) tuples.
:param name_value_pairs: Names and values of the query parameters to add
:rtype: string
:returns: URL with additional query strings appended.
"""
if len(name_value_pairs) == 0:
return base_url
scheme, netloc, path, query, frag = urlsplit(base_url)
query = parse_qsl(query)
query.extend(name_value_pairs)
return urlunsplit((scheme, netloc, path, urlencode(query), frag)) | [
"def",
"_add_query_parameters",
"(",
"base_url",
",",
"name_value_pairs",
")",
":",
"if",
"len",
"(",
"name_value_pairs",
")",
"==",
"0",
":",
"return",
"base_url",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"frag",
"=",
"urlsplit",
"(",
"base_url",
")",
"query",
"=",
"parse_qsl",
"(",
"query",
")",
"query",
".",
"extend",
"(",
"name_value_pairs",
")",
"return",
"urlunsplit",
"(",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"urlencode",
"(",
"query",
")",
",",
"frag",
")",
")"
] | Add one query parameter to a base URL.
:type base_url: string
:param base_url: Base URL (may already contain query parameters)
:type name_value_pairs: list of (string, string) tuples.
:param name_value_pairs: Names and values of the query parameters to add
:rtype: string
:returns: URL with additional query strings appended. | [
"Add",
"one",
"query",
"parameter",
"to",
"a",
"base",
"URL",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L2037-L2055 |
28,078 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.chunk_size | def chunk_size(self, value):
"""Set the blob's default chunk size.
:type value: int
:param value: (Optional) The current blob's chunk size, if it is set.
:raises: :class:`ValueError` if ``value`` is not ``None`` and is not a
multiple of 256 KB.
"""
if value is not None and value > 0 and value % self._CHUNK_SIZE_MULTIPLE != 0:
raise ValueError(
"Chunk size must be a multiple of %d." % (self._CHUNK_SIZE_MULTIPLE,)
)
self._chunk_size = value | python | def chunk_size(self, value):
"""Set the blob's default chunk size.
:type value: int
:param value: (Optional) The current blob's chunk size, if it is set.
:raises: :class:`ValueError` if ``value`` is not ``None`` and is not a
multiple of 256 KB.
"""
if value is not None and value > 0 and value % self._CHUNK_SIZE_MULTIPLE != 0:
raise ValueError(
"Chunk size must be a multiple of %d." % (self._CHUNK_SIZE_MULTIPLE,)
)
self._chunk_size = value | [
"def",
"chunk_size",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
"and",
"value",
">",
"0",
"and",
"value",
"%",
"self",
".",
"_CHUNK_SIZE_MULTIPLE",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Chunk size must be a multiple of %d.\"",
"%",
"(",
"self",
".",
"_CHUNK_SIZE_MULTIPLE",
",",
")",
")",
"self",
".",
"_chunk_size",
"=",
"value"
] | Set the blob's default chunk size.
:type value: int
:param value: (Optional) The current blob's chunk size, if it is set.
:raises: :class:`ValueError` if ``value`` is not ``None`` and is not a
multiple of 256 KB. | [
"Set",
"the",
"blob",
"s",
"default",
"chunk",
"size",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L200-L213 |
28,079 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.path | def path(self):
"""Getter property for the URL path to this Blob.
:rtype: str
:returns: The URL path to this Blob.
"""
if not self.name:
raise ValueError("Cannot determine path without a blob name.")
return self.path_helper(self.bucket.path, self.name) | python | def path(self):
"""Getter property for the URL path to this Blob.
:rtype: str
:returns: The URL path to this Blob.
"""
if not self.name:
raise ValueError("Cannot determine path without a blob name.")
return self.path_helper(self.bucket.path, self.name) | [
"def",
"path",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"name",
":",
"raise",
"ValueError",
"(",
"\"Cannot determine path without a blob name.\"",
")",
"return",
"self",
".",
"path_helper",
"(",
"self",
".",
"bucket",
".",
"path",
",",
"self",
".",
"name",
")"
] | Getter property for the URL path to this Blob.
:rtype: str
:returns: The URL path to this Blob. | [
"Getter",
"property",
"for",
"the",
"URL",
"path",
"to",
"this",
"Blob",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L244-L253 |
28,080 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob._query_params | def _query_params(self):
"""Default query parameters."""
params = {}
if self.generation is not None:
params["generation"] = self.generation
if self.user_project is not None:
params["userProject"] = self.user_project
return params | python | def _query_params(self):
"""Default query parameters."""
params = {}
if self.generation is not None:
params["generation"] = self.generation
if self.user_project is not None:
params["userProject"] = self.user_project
return params | [
"def",
"_query_params",
"(",
"self",
")",
":",
"params",
"=",
"{",
"}",
"if",
"self",
".",
"generation",
"is",
"not",
"None",
":",
"params",
"[",
"\"generation\"",
"]",
"=",
"self",
".",
"generation",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"params",
"[",
"\"userProject\"",
"]",
"=",
"self",
".",
"user_project",
"return",
"params"
] | Default query parameters. | [
"Default",
"query",
"parameters",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L279-L286 |
28,081 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.public_url | def public_url(self):
"""The public URL for this blob.
Use :meth:`make_public` to enable anonymous access via the returned
URL.
:rtype: `string`
:returns: The public URL for this blob.
"""
return "{storage_base_url}/{bucket_name}/{quoted_name}".format(
storage_base_url=_API_ACCESS_ENDPOINT,
bucket_name=self.bucket.name,
quoted_name=quote(self.name.encode("utf-8")),
) | python | def public_url(self):
"""The public URL for this blob.
Use :meth:`make_public` to enable anonymous access via the returned
URL.
:rtype: `string`
:returns: The public URL for this blob.
"""
return "{storage_base_url}/{bucket_name}/{quoted_name}".format(
storage_base_url=_API_ACCESS_ENDPOINT,
bucket_name=self.bucket.name,
quoted_name=quote(self.name.encode("utf-8")),
) | [
"def",
"public_url",
"(",
"self",
")",
":",
"return",
"\"{storage_base_url}/{bucket_name}/{quoted_name}\"",
".",
"format",
"(",
"storage_base_url",
"=",
"_API_ACCESS_ENDPOINT",
",",
"bucket_name",
"=",
"self",
".",
"bucket",
".",
"name",
",",
"quoted_name",
"=",
"quote",
"(",
"self",
".",
"name",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
",",
")"
] | The public URL for this blob.
Use :meth:`make_public` to enable anonymous access via the returned
URL.
:rtype: `string`
:returns: The public URL for this blob. | [
"The",
"public",
"URL",
"for",
"this",
"blob",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L289-L302 |
28,082 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.generate_signed_url | def generate_signed_url(
self,
expiration=None,
api_access_endpoint=_API_ACCESS_ENDPOINT,
method="GET",
content_md5=None,
content_type=None,
response_disposition=None,
response_type=None,
generation=None,
headers=None,
query_parameters=None,
client=None,
credentials=None,
version=None,
):
"""Generates a signed URL for this blob.
.. 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 blob 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 blobs, 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 content_md5: str
:param content_md5: (Optional) The MD5 hash of the object referenced by
``resource``.
:type content_type: str
:param content_type: (Optional) The content type of the object
referenced by ``resource``.
:type response_disposition: str
:param response_disposition: (Optional) Content disposition of
responses to requests for the signed URL.
For example, to enable the signed URL
to initiate a file of ``blog.png``, use
the value
``'attachment; filename=blob.png'``.
:type response_type: str
:param response_type: (Optional) Content type of responses to requests
for the signed URL. Used to over-ride the content
type of the underlying blob/object.
:type generation: str
:param generation: (Optional) A value that indicates which generation
of the resource to fetch.
:type headers: dict
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
: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}/{quoted_name}".format(
bucket_name=self.bucket.name, quoted_name=quote(self.name.encode("utf-8"))
)
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(),
content_md5=content_md5,
content_type=content_type,
response_type=response_type,
response_disposition=response_disposition,
generation=generation,
headers=headers,
query_parameters=query_parameters,
) | python | def generate_signed_url(
self,
expiration=None,
api_access_endpoint=_API_ACCESS_ENDPOINT,
method="GET",
content_md5=None,
content_type=None,
response_disposition=None,
response_type=None,
generation=None,
headers=None,
query_parameters=None,
client=None,
credentials=None,
version=None,
):
"""Generates a signed URL for this blob.
.. 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 blob 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 blobs, 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 content_md5: str
:param content_md5: (Optional) The MD5 hash of the object referenced by
``resource``.
:type content_type: str
:param content_type: (Optional) The content type of the object
referenced by ``resource``.
:type response_disposition: str
:param response_disposition: (Optional) Content disposition of
responses to requests for the signed URL.
For example, to enable the signed URL
to initiate a file of ``blog.png``, use
the value
``'attachment; filename=blob.png'``.
:type response_type: str
:param response_type: (Optional) Content type of responses to requests
for the signed URL. Used to over-ride the content
type of the underlying blob/object.
:type generation: str
:param generation: (Optional) A value that indicates which generation
of the resource to fetch.
:type headers: dict
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
: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}/{quoted_name}".format(
bucket_name=self.bucket.name, quoted_name=quote(self.name.encode("utf-8"))
)
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(),
content_md5=content_md5,
content_type=content_type,
response_type=response_type,
response_disposition=response_disposition,
generation=generation,
headers=headers,
query_parameters=query_parameters,
) | [
"def",
"generate_signed_url",
"(",
"self",
",",
"expiration",
"=",
"None",
",",
"api_access_endpoint",
"=",
"_API_ACCESS_ENDPOINT",
",",
"method",
"=",
"\"GET\"",
",",
"content_md5",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"response_disposition",
"=",
"None",
",",
"response_type",
"=",
"None",
",",
"generation",
"=",
"None",
",",
"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}/{quoted_name}\"",
".",
"format",
"(",
"bucket_name",
"=",
"self",
".",
"bucket",
".",
"name",
",",
"quoted_name",
"=",
"quote",
"(",
"self",
".",
"name",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
")",
"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",
"(",
")",
",",
"content_md5",
"=",
"content_md5",
",",
"content_type",
"=",
"content_type",
",",
"response_type",
"=",
"response_type",
",",
"response_disposition",
"=",
"response_disposition",
",",
"generation",
"=",
"generation",
",",
"headers",
"=",
"headers",
",",
"query_parameters",
"=",
"query_parameters",
",",
")"
] | Generates a signed URL for this blob.
.. 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 blob 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 blobs, 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 content_md5: str
:param content_md5: (Optional) The MD5 hash of the object referenced by
``resource``.
:type content_type: str
:param content_type: (Optional) The content type of the object
referenced by ``resource``.
:type response_disposition: str
:param response_disposition: (Optional) Content disposition of
responses to requests for the signed URL.
For example, to enable the signed URL
to initiate a file of ``blog.png``, use
the value
``'attachment; filename=blob.png'``.
:type response_type: str
:param response_type: (Optional) Content type of responses to requests
for the signed URL. Used to over-ride the content
type of the underlying blob/object.
:type generation: str
:param generation: (Optional) A value that indicates which generation
of the resource to fetch.
:type headers: dict
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query paramtersto be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
: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",
"blob",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L304-L445 |
28,083 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.exists | def exists(self, client=None):
"""Determines whether or not this blob exists.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: bool
:returns: True if the blob exists in Cloud Storage.
"""
client = self._require_client(client)
# We only need the status code (200 or not) so we seek to
# minimize the returned payload.
query_params = self._query_params
query_params["fields"] = "name"
try:
# We intentionally pass `_target_object=None` since fields=name
# would limit the local properties.
client._connection.api_request(
method="GET",
path=self.path,
query_params=query_params,
_target_object=None,
)
# NOTE: This will not fail immediately in a batch. However, when
# Batch.finish() is called, the resulting `NotFound` will be
# raised.
return True
except NotFound:
return False | python | def exists(self, client=None):
"""Determines whether or not this blob exists.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: bool
:returns: True if the blob exists in Cloud Storage.
"""
client = self._require_client(client)
# We only need the status code (200 or not) so we seek to
# minimize the returned payload.
query_params = self._query_params
query_params["fields"] = "name"
try:
# We intentionally pass `_target_object=None` since fields=name
# would limit the local properties.
client._connection.api_request(
method="GET",
path=self.path,
query_params=query_params,
_target_object=None,
)
# NOTE: This will not fail immediately in a batch. However, when
# Batch.finish() is called, the resulting `NotFound` will be
# raised.
return True
except NotFound:
return False | [
"def",
"exists",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"# We only need the status code (200 or not) so we seek to",
"# minimize the returned payload.",
"query_params",
"=",
"self",
".",
"_query_params",
"query_params",
"[",
"\"fields\"",
"]",
"=",
"\"name\"",
"try",
":",
"# We intentionally pass `_target_object=None` since fields=name",
"# would limit the local properties.",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"self",
".",
"path",
",",
"query_params",
"=",
"query_params",
",",
"_target_object",
"=",
"None",
",",
")",
"# NOTE: This will not fail immediately in a batch. However, when",
"# Batch.finish() is called, the resulting `NotFound` will be",
"# raised.",
"return",
"True",
"except",
"NotFound",
":",
"return",
"False"
] | Determines whether or not this blob exists.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: bool
:returns: True if the blob exists in Cloud Storage. | [
"Determines",
"whether",
"or",
"not",
"this",
"blob",
"exists",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L447-L481 |
28,084 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.delete | def delete(self, client=None):
"""Deletes a blob from Cloud Storage.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: :class:`Blob`
:returns: The blob that was just deleted.
:raises: :class:`google.cloud.exceptions.NotFound`
(propagated from
:meth:`google.cloud.storage.bucket.Bucket.delete_blob`).
"""
return self.bucket.delete_blob(
self.name, client=client, generation=self.generation
) | python | def delete(self, client=None):
"""Deletes a blob from Cloud Storage.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: :class:`Blob`
:returns: The blob that was just deleted.
:raises: :class:`google.cloud.exceptions.NotFound`
(propagated from
:meth:`google.cloud.storage.bucket.Bucket.delete_blob`).
"""
return self.bucket.delete_blob(
self.name, client=client, generation=self.generation
) | [
"def",
"delete",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"return",
"self",
".",
"bucket",
".",
"delete_blob",
"(",
"self",
".",
"name",
",",
"client",
"=",
"client",
",",
"generation",
"=",
"self",
".",
"generation",
")"
] | Deletes a blob from Cloud Storage.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: :class:`Blob`
:returns: The blob that was just deleted.
:raises: :class:`google.cloud.exceptions.NotFound`
(propagated from
:meth:`google.cloud.storage.bucket.Bucket.delete_blob`). | [
"Deletes",
"a",
"blob",
"from",
"Cloud",
"Storage",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L483-L502 |
28,085 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob._get_download_url | def _get_download_url(self):
"""Get the download URL for the current blob.
If the ``media_link`` has been loaded, it will be used, otherwise
the URL will be constructed from the current blob's path (and possibly
generation) to avoid a round trip.
:rtype: str
:returns: The download URL for the current blob.
"""
name_value_pairs = []
if self.media_link is None:
base_url = _DOWNLOAD_URL_TEMPLATE.format(path=self.path)
if self.generation is not None:
name_value_pairs.append(("generation", "{:d}".format(self.generation)))
else:
base_url = self.media_link
if self.user_project is not None:
name_value_pairs.append(("userProject", self.user_project))
return _add_query_parameters(base_url, name_value_pairs) | python | def _get_download_url(self):
"""Get the download URL for the current blob.
If the ``media_link`` has been loaded, it will be used, otherwise
the URL will be constructed from the current blob's path (and possibly
generation) to avoid a round trip.
:rtype: str
:returns: The download URL for the current blob.
"""
name_value_pairs = []
if self.media_link is None:
base_url = _DOWNLOAD_URL_TEMPLATE.format(path=self.path)
if self.generation is not None:
name_value_pairs.append(("generation", "{:d}".format(self.generation)))
else:
base_url = self.media_link
if self.user_project is not None:
name_value_pairs.append(("userProject", self.user_project))
return _add_query_parameters(base_url, name_value_pairs) | [
"def",
"_get_download_url",
"(",
"self",
")",
":",
"name_value_pairs",
"=",
"[",
"]",
"if",
"self",
".",
"media_link",
"is",
"None",
":",
"base_url",
"=",
"_DOWNLOAD_URL_TEMPLATE",
".",
"format",
"(",
"path",
"=",
"self",
".",
"path",
")",
"if",
"self",
".",
"generation",
"is",
"not",
"None",
":",
"name_value_pairs",
".",
"append",
"(",
"(",
"\"generation\"",
",",
"\"{:d}\"",
".",
"format",
"(",
"self",
".",
"generation",
")",
")",
")",
"else",
":",
"base_url",
"=",
"self",
".",
"media_link",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"name_value_pairs",
".",
"append",
"(",
"(",
"\"userProject\"",
",",
"self",
".",
"user_project",
")",
")",
"return",
"_add_query_parameters",
"(",
"base_url",
",",
"name_value_pairs",
")"
] | Get the download URL for the current blob.
If the ``media_link`` has been loaded, it will be used, otherwise
the URL will be constructed from the current blob's path (and possibly
generation) to avoid a round trip.
:rtype: str
:returns: The download URL for the current blob. | [
"Get",
"the",
"download",
"URL",
"for",
"the",
"current",
"blob",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L519-L540 |
28,086 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob._do_download | def _do_download(
self, transport, file_obj, download_url, headers, start=None, end=None
):
"""Perform a download without any error handling.
This is intended to be called by :meth:`download_to_file` so it can
be wrapped with error handling / remapping.
:type transport:
:class:`~google.auth.transport.requests.AuthorizedSession`
:param transport: The transport (with credentials) that will
make authenticated requests.
:type file_obj: file
:param file_obj: A file handle to which to write the blob's data.
:type download_url: str
:param download_url: The URL where the media can be accessed.
:type headers: dict
:param headers: Optional headers to be sent with the request(s).
:type start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded.
"""
if self.chunk_size is None:
download = Download(
download_url, stream=file_obj, headers=headers, start=start, end=end
)
download.consume(transport)
else:
download = ChunkedDownload(
download_url,
self.chunk_size,
file_obj,
headers=headers,
start=start if start else 0,
end=end,
)
while not download.finished:
download.consume_next_chunk(transport) | python | def _do_download(
self, transport, file_obj, download_url, headers, start=None, end=None
):
"""Perform a download without any error handling.
This is intended to be called by :meth:`download_to_file` so it can
be wrapped with error handling / remapping.
:type transport:
:class:`~google.auth.transport.requests.AuthorizedSession`
:param transport: The transport (with credentials) that will
make authenticated requests.
:type file_obj: file
:param file_obj: A file handle to which to write the blob's data.
:type download_url: str
:param download_url: The URL where the media can be accessed.
:type headers: dict
:param headers: Optional headers to be sent with the request(s).
:type start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded.
"""
if self.chunk_size is None:
download = Download(
download_url, stream=file_obj, headers=headers, start=start, end=end
)
download.consume(transport)
else:
download = ChunkedDownload(
download_url,
self.chunk_size,
file_obj,
headers=headers,
start=start if start else 0,
end=end,
)
while not download.finished:
download.consume_next_chunk(transport) | [
"def",
"_do_download",
"(",
"self",
",",
"transport",
",",
"file_obj",
",",
"download_url",
",",
"headers",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"if",
"self",
".",
"chunk_size",
"is",
"None",
":",
"download",
"=",
"Download",
"(",
"download_url",
",",
"stream",
"=",
"file_obj",
",",
"headers",
"=",
"headers",
",",
"start",
"=",
"start",
",",
"end",
"=",
"end",
")",
"download",
".",
"consume",
"(",
"transport",
")",
"else",
":",
"download",
"=",
"ChunkedDownload",
"(",
"download_url",
",",
"self",
".",
"chunk_size",
",",
"file_obj",
",",
"headers",
"=",
"headers",
",",
"start",
"=",
"start",
"if",
"start",
"else",
"0",
",",
"end",
"=",
"end",
",",
")",
"while",
"not",
"download",
".",
"finished",
":",
"download",
".",
"consume_next_chunk",
"(",
"transport",
")"
] | Perform a download without any error handling.
This is intended to be called by :meth:`download_to_file` so it can
be wrapped with error handling / remapping.
:type transport:
:class:`~google.auth.transport.requests.AuthorizedSession`
:param transport: The transport (with credentials) that will
make authenticated requests.
:type file_obj: file
:param file_obj: A file handle to which to write the blob's data.
:type download_url: str
:param download_url: The URL where the media can be accessed.
:type headers: dict
:param headers: Optional headers to be sent with the request(s).
:type start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded. | [
"Perform",
"a",
"download",
"without",
"any",
"error",
"handling",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L542-L586 |
28,087 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.download_to_file | def download_to_file(self, file_obj, client=None, start=None, end=None):
"""Download the contents of this blob into a file-like object.
.. note::
If the server-set property, :attr:`media_link`, is not yet
initialized, makes an additional API request to load it.
Downloading a file that has been encrypted with a `customer-supplied`_
encryption key:
.. literalinclude:: snippets.py
:start-after: [START download_to_file]
:end-before: [END download_to_file]
:dedent: 4
The ``encryption_key`` should be a str or bytes with a length of at
least 32.
For more fine-grained control over the download process, check out
`google-resumable-media`_. For example, this library allows
downloading **parts** of a blob rather than the whole thing.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type file_obj: file
:param file_obj: A file handle to which to write the blob's data.
: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 start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded.
:raises: :class:`google.cloud.exceptions.NotFound`
"""
download_url = self._get_download_url()
headers = _get_encryption_headers(self._encryption_key)
headers["accept-encoding"] = "gzip"
transport = self._get_transport(client)
try:
self._do_download(transport, file_obj, download_url, headers, start, end)
except resumable_media.InvalidResponse as exc:
_raise_from_invalid_response(exc) | python | def download_to_file(self, file_obj, client=None, start=None, end=None):
"""Download the contents of this blob into a file-like object.
.. note::
If the server-set property, :attr:`media_link`, is not yet
initialized, makes an additional API request to load it.
Downloading a file that has been encrypted with a `customer-supplied`_
encryption key:
.. literalinclude:: snippets.py
:start-after: [START download_to_file]
:end-before: [END download_to_file]
:dedent: 4
The ``encryption_key`` should be a str or bytes with a length of at
least 32.
For more fine-grained control over the download process, check out
`google-resumable-media`_. For example, this library allows
downloading **parts** of a blob rather than the whole thing.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type file_obj: file
:param file_obj: A file handle to which to write the blob's data.
: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 start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded.
:raises: :class:`google.cloud.exceptions.NotFound`
"""
download_url = self._get_download_url()
headers = _get_encryption_headers(self._encryption_key)
headers["accept-encoding"] = "gzip"
transport = self._get_transport(client)
try:
self._do_download(transport, file_obj, download_url, headers, start, end)
except resumable_media.InvalidResponse as exc:
_raise_from_invalid_response(exc) | [
"def",
"download_to_file",
"(",
"self",
",",
"file_obj",
",",
"client",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"download_url",
"=",
"self",
".",
"_get_download_url",
"(",
")",
"headers",
"=",
"_get_encryption_headers",
"(",
"self",
".",
"_encryption_key",
")",
"headers",
"[",
"\"accept-encoding\"",
"]",
"=",
"\"gzip\"",
"transport",
"=",
"self",
".",
"_get_transport",
"(",
"client",
")",
"try",
":",
"self",
".",
"_do_download",
"(",
"transport",
",",
"file_obj",
",",
"download_url",
",",
"headers",
",",
"start",
",",
"end",
")",
"except",
"resumable_media",
".",
"InvalidResponse",
"as",
"exc",
":",
"_raise_from_invalid_response",
"(",
"exc",
")"
] | Download the contents of this blob into a file-like object.
.. note::
If the server-set property, :attr:`media_link`, is not yet
initialized, makes an additional API request to load it.
Downloading a file that has been encrypted with a `customer-supplied`_
encryption key:
.. literalinclude:: snippets.py
:start-after: [START download_to_file]
:end-before: [END download_to_file]
:dedent: 4
The ``encryption_key`` should be a str or bytes with a length of at
least 32.
For more fine-grained control over the download process, check out
`google-resumable-media`_. For example, this library allows
downloading **parts** of a blob rather than the whole thing.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type file_obj: file
:param file_obj: A file handle to which to write the blob's data.
: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 start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded.
:raises: :class:`google.cloud.exceptions.NotFound` | [
"Download",
"the",
"contents",
"of",
"this",
"blob",
"into",
"a",
"file",
"-",
"like",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L588-L638 |
28,088 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.download_to_filename | def download_to_filename(self, filename, client=None, start=None, end=None):
"""Download the contents of this blob into a named file.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type filename: str
:param filename: A filename to be passed to ``open``.
: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 start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded.
:raises: :class:`google.cloud.exceptions.NotFound`
"""
try:
with open(filename, "wb") as file_obj:
self.download_to_file(file_obj, client=client, start=start, end=end)
except resumable_media.DataCorruption:
# Delete the corrupt downloaded file.
os.remove(filename)
raise
updated = self.updated
if updated is not None:
mtime = time.mktime(updated.timetuple())
os.utime(file_obj.name, (mtime, mtime)) | python | def download_to_filename(self, filename, client=None, start=None, end=None):
"""Download the contents of this blob into a named file.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type filename: str
:param filename: A filename to be passed to ``open``.
: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 start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded.
:raises: :class:`google.cloud.exceptions.NotFound`
"""
try:
with open(filename, "wb") as file_obj:
self.download_to_file(file_obj, client=client, start=start, end=end)
except resumable_media.DataCorruption:
# Delete the corrupt downloaded file.
os.remove(filename)
raise
updated = self.updated
if updated is not None:
mtime = time.mktime(updated.timetuple())
os.utime(file_obj.name, (mtime, mtime)) | [
"def",
"download_to_filename",
"(",
"self",
",",
"filename",
",",
"client",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"as",
"file_obj",
":",
"self",
".",
"download_to_file",
"(",
"file_obj",
",",
"client",
"=",
"client",
",",
"start",
"=",
"start",
",",
"end",
"=",
"end",
")",
"except",
"resumable_media",
".",
"DataCorruption",
":",
"# Delete the corrupt downloaded file.",
"os",
".",
"remove",
"(",
"filename",
")",
"raise",
"updated",
"=",
"self",
".",
"updated",
"if",
"updated",
"is",
"not",
"None",
":",
"mtime",
"=",
"time",
".",
"mktime",
"(",
"updated",
".",
"timetuple",
"(",
")",
")",
"os",
".",
"utime",
"(",
"file_obj",
".",
"name",
",",
"(",
"mtime",
",",
"mtime",
")",
")"
] | Download the contents of this blob into a named file.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type filename: str
:param filename: A filename to be passed to ``open``.
: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 start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded.
:raises: :class:`google.cloud.exceptions.NotFound` | [
"Download",
"the",
"contents",
"of",
"this",
"blob",
"into",
"a",
"named",
"file",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L640-L673 |
28,089 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.download_as_string | def download_as_string(self, client=None, start=None, end=None):
"""Download the contents of this blob as a string.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:type start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded.
:rtype: bytes
:returns: The data stored in this blob.
:raises: :class:`google.cloud.exceptions.NotFound`
"""
string_buffer = BytesIO()
self.download_to_file(string_buffer, client=client, start=start, end=end)
return string_buffer.getvalue() | python | def download_as_string(self, client=None, start=None, end=None):
"""Download the contents of this blob as a string.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:type start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded.
:rtype: bytes
:returns: The data stored in this blob.
:raises: :class:`google.cloud.exceptions.NotFound`
"""
string_buffer = BytesIO()
self.download_to_file(string_buffer, client=client, start=start, end=end)
return string_buffer.getvalue() | [
"def",
"download_as_string",
"(",
"self",
",",
"client",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"string_buffer",
"=",
"BytesIO",
"(",
")",
"self",
".",
"download_to_file",
"(",
"string_buffer",
",",
"client",
"=",
"client",
",",
"start",
"=",
"start",
",",
"end",
"=",
"end",
")",
"return",
"string_buffer",
".",
"getvalue",
"(",
")"
] | Download the contents of this blob as a string.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:type start: int
:param start: Optional, the first byte in a range to be downloaded.
:type end: int
:param end: Optional, The last byte in a range to be downloaded.
:rtype: bytes
:returns: The data stored in this blob.
:raises: :class:`google.cloud.exceptions.NotFound` | [
"Download",
"the",
"contents",
"of",
"this",
"blob",
"as",
"a",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L675-L698 |
28,090 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob._get_content_type | def _get_content_type(self, content_type, filename=None):
"""Determine the content type from the current object.
The return value will be determined in order of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
:type content_type: str
:param content_type: (Optional) type of content.
:type filename: str
:param filename: (Optional) The name of the file where the content
is stored.
:rtype: str
:returns: Type of content gathered from the object.
"""
if content_type is None:
content_type = self.content_type
if content_type is None and filename is not None:
content_type, _ = mimetypes.guess_type(filename)
if content_type is None:
content_type = _DEFAULT_CONTENT_TYPE
return content_type | python | def _get_content_type(self, content_type, filename=None):
"""Determine the content type from the current object.
The return value will be determined in order of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
:type content_type: str
:param content_type: (Optional) type of content.
:type filename: str
:param filename: (Optional) The name of the file where the content
is stored.
:rtype: str
:returns: Type of content gathered from the object.
"""
if content_type is None:
content_type = self.content_type
if content_type is None and filename is not None:
content_type, _ = mimetypes.guess_type(filename)
if content_type is None:
content_type = _DEFAULT_CONTENT_TYPE
return content_type | [
"def",
"_get_content_type",
"(",
"self",
",",
"content_type",
",",
"filename",
"=",
"None",
")",
":",
"if",
"content_type",
"is",
"None",
":",
"content_type",
"=",
"self",
".",
"content_type",
"if",
"content_type",
"is",
"None",
"and",
"filename",
"is",
"not",
"None",
":",
"content_type",
",",
"_",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"if",
"content_type",
"is",
"None",
":",
"content_type",
"=",
"_DEFAULT_CONTENT_TYPE",
"return",
"content_type"
] | Determine the content type from the current object.
The return value will be determined in order of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
:type content_type: str
:param content_type: (Optional) type of content.
:type filename: str
:param filename: (Optional) The name of the file where the content
is stored.
:rtype: str
:returns: Type of content gathered from the object. | [
"Determine",
"the",
"content",
"type",
"from",
"the",
"current",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L700-L728 |
28,091 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob._get_upload_arguments | def _get_upload_arguments(self, content_type):
"""Get required arguments for performing an upload.
The content type returned will be determined in order of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
:type content_type: str
:param content_type: Type of content being uploaded (or :data:`None`).
:rtype: tuple
:returns: A triple of
* A header dictionary
* An object metadata dictionary
* The ``content_type`` as a string (according to precedence)
"""
headers = _get_encryption_headers(self._encryption_key)
object_metadata = self._get_writable_metadata()
content_type = self._get_content_type(content_type)
return headers, object_metadata, content_type | python | def _get_upload_arguments(self, content_type):
"""Get required arguments for performing an upload.
The content type returned will be determined in order of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
:type content_type: str
:param content_type: Type of content being uploaded (or :data:`None`).
:rtype: tuple
:returns: A triple of
* A header dictionary
* An object metadata dictionary
* The ``content_type`` as a string (according to precedence)
"""
headers = _get_encryption_headers(self._encryption_key)
object_metadata = self._get_writable_metadata()
content_type = self._get_content_type(content_type)
return headers, object_metadata, content_type | [
"def",
"_get_upload_arguments",
"(",
"self",
",",
"content_type",
")",
":",
"headers",
"=",
"_get_encryption_headers",
"(",
"self",
".",
"_encryption_key",
")",
"object_metadata",
"=",
"self",
".",
"_get_writable_metadata",
"(",
")",
"content_type",
"=",
"self",
".",
"_get_content_type",
"(",
"content_type",
")",
"return",
"headers",
",",
"object_metadata",
",",
"content_type"
] | Get required arguments for performing an upload.
The content type returned will be determined in order of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
:type content_type: str
:param content_type: Type of content being uploaded (or :data:`None`).
:rtype: tuple
:returns: A triple of
* A header dictionary
* An object metadata dictionary
* The ``content_type`` as a string (according to precedence) | [
"Get",
"required",
"arguments",
"for",
"performing",
"an",
"upload",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L761-L783 |
28,092 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob._do_upload | def _do_upload(
self, client, stream, content_type, size, num_retries, predefined_acl
):
"""Determine an upload strategy and then perform the upload.
If the size of the data to be uploaded exceeds 5 MB a resumable media
request will be used, otherwise the content and the metadata will be
uploaded in a single multipart upload request.
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
: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 blob's bucket.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type content_type: str
:param content_type: Type of content being uploaded (or :data:`None`).
:type size: int
:param size: The number of bytes to be uploaded (which will be read
from ``stream``). If not provided, the upload will be
concluded once ``stream`` is exhausted (or :data:`None`).
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:type predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
:rtype: dict
:returns: The parsed JSON from the "200 OK" response. This will be the
**only** response in the multipart case and it will be the
**final** response in the resumable case.
"""
if size is not None and size <= _MAX_MULTIPART_SIZE:
response = self._do_multipart_upload(
client, stream, content_type, size, num_retries, predefined_acl
)
else:
response = self._do_resumable_upload(
client, stream, content_type, size, num_retries, predefined_acl
)
return response.json() | python | def _do_upload(
self, client, stream, content_type, size, num_retries, predefined_acl
):
"""Determine an upload strategy and then perform the upload.
If the size of the data to be uploaded exceeds 5 MB a resumable media
request will be used, otherwise the content and the metadata will be
uploaded in a single multipart upload request.
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
: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 blob's bucket.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type content_type: str
:param content_type: Type of content being uploaded (or :data:`None`).
:type size: int
:param size: The number of bytes to be uploaded (which will be read
from ``stream``). If not provided, the upload will be
concluded once ``stream`` is exhausted (or :data:`None`).
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:type predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
:rtype: dict
:returns: The parsed JSON from the "200 OK" response. This will be the
**only** response in the multipart case and it will be the
**final** response in the resumable case.
"""
if size is not None and size <= _MAX_MULTIPART_SIZE:
response = self._do_multipart_upload(
client, stream, content_type, size, num_retries, predefined_acl
)
else:
response = self._do_resumable_upload(
client, stream, content_type, size, num_retries, predefined_acl
)
return response.json() | [
"def",
"_do_upload",
"(",
"self",
",",
"client",
",",
"stream",
",",
"content_type",
",",
"size",
",",
"num_retries",
",",
"predefined_acl",
")",
":",
"if",
"size",
"is",
"not",
"None",
"and",
"size",
"<=",
"_MAX_MULTIPART_SIZE",
":",
"response",
"=",
"self",
".",
"_do_multipart_upload",
"(",
"client",
",",
"stream",
",",
"content_type",
",",
"size",
",",
"num_retries",
",",
"predefined_acl",
")",
"else",
":",
"response",
"=",
"self",
".",
"_do_resumable_upload",
"(",
"client",
",",
"stream",
",",
"content_type",
",",
"size",
",",
"num_retries",
",",
"predefined_acl",
")",
"return",
"response",
".",
"json",
"(",
")"
] | Determine an upload strategy and then perform the upload.
If the size of the data to be uploaded exceeds 5 MB a resumable media
request will be used, otherwise the content and the metadata will be
uploaded in a single multipart upload request.
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
: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 blob's bucket.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type content_type: str
:param content_type: Type of content being uploaded (or :data:`None`).
:type size: int
:param size: The number of bytes to be uploaded (which will be read
from ``stream``). If not provided, the upload will be
concluded once ``stream`` is exhausted (or :data:`None`).
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:type predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
:rtype: dict
:returns: The parsed JSON from the "200 OK" response. This will be the
**only** response in the multipart case and it will be the
**final** response in the resumable case. | [
"Determine",
"an",
"upload",
"strategy",
"and",
"then",
"perform",
"the",
"upload",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1018-L1070 |
28,093 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.upload_from_file | def upload_from_file(
self,
file_obj,
rewind=False,
size=None,
content_type=None,
num_retries=None,
client=None,
predefined_acl=None,
):
"""Upload the contents of this blob from a file-like object.
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning`_ and `lifecycle`_ API documents
for details.
Uploading a file with a `customer-supplied`_ encryption key:
.. literalinclude:: snippets.py
:start-after: [START upload_from_file]
:end-before: [END upload_from_file]
:dedent: 4
The ``encryption_key`` should be a str or bytes with a length of at
least 32.
For more fine-grained over the upload process, check out
`google-resumable-media`_.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type file_obj: file
:param file_obj: A file handle open for reading.
:type rewind: bool
:param rewind: If True, seek to the beginning of the file handle before
writing the file to Cloud Storage.
:type size: int
:param size: The number of bytes to be uploaded (which will be read
from ``file_obj``). If not provided, the upload will be
concluded once ``file_obj`` is exhausted.
:type content_type: str
:param content_type: Optional type of content being uploaded.
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
: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 blob's bucket.
:type predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
:raises: :class:`~google.cloud.exceptions.GoogleCloudError`
if the upload response returns an error status.
.. _object versioning: https://cloud.google.com/storage/\
docs/object-versioning
.. _lifecycle: https://cloud.google.com/storage/docs/lifecycle
"""
if num_retries is not None:
warnings.warn(_NUM_RETRIES_MESSAGE, DeprecationWarning, stacklevel=2)
_maybe_rewind(file_obj, rewind=rewind)
predefined_acl = ACL.validate_predefined(predefined_acl)
try:
created_json = self._do_upload(
client, file_obj, content_type, size, num_retries, predefined_acl
)
self._set_properties(created_json)
except resumable_media.InvalidResponse as exc:
_raise_from_invalid_response(exc) | python | def upload_from_file(
self,
file_obj,
rewind=False,
size=None,
content_type=None,
num_retries=None,
client=None,
predefined_acl=None,
):
"""Upload the contents of this blob from a file-like object.
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning`_ and `lifecycle`_ API documents
for details.
Uploading a file with a `customer-supplied`_ encryption key:
.. literalinclude:: snippets.py
:start-after: [START upload_from_file]
:end-before: [END upload_from_file]
:dedent: 4
The ``encryption_key`` should be a str or bytes with a length of at
least 32.
For more fine-grained over the upload process, check out
`google-resumable-media`_.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type file_obj: file
:param file_obj: A file handle open for reading.
:type rewind: bool
:param rewind: If True, seek to the beginning of the file handle before
writing the file to Cloud Storage.
:type size: int
:param size: The number of bytes to be uploaded (which will be read
from ``file_obj``). If not provided, the upload will be
concluded once ``file_obj`` is exhausted.
:type content_type: str
:param content_type: Optional type of content being uploaded.
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
: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 blob's bucket.
:type predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
:raises: :class:`~google.cloud.exceptions.GoogleCloudError`
if the upload response returns an error status.
.. _object versioning: https://cloud.google.com/storage/\
docs/object-versioning
.. _lifecycle: https://cloud.google.com/storage/docs/lifecycle
"""
if num_retries is not None:
warnings.warn(_NUM_RETRIES_MESSAGE, DeprecationWarning, stacklevel=2)
_maybe_rewind(file_obj, rewind=rewind)
predefined_acl = ACL.validate_predefined(predefined_acl)
try:
created_json = self._do_upload(
client, file_obj, content_type, size, num_retries, predefined_acl
)
self._set_properties(created_json)
except resumable_media.InvalidResponse as exc:
_raise_from_invalid_response(exc) | [
"def",
"upload_from_file",
"(",
"self",
",",
"file_obj",
",",
"rewind",
"=",
"False",
",",
"size",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"num_retries",
"=",
"None",
",",
"client",
"=",
"None",
",",
"predefined_acl",
"=",
"None",
",",
")",
":",
"if",
"num_retries",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"_NUM_RETRIES_MESSAGE",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"_maybe_rewind",
"(",
"file_obj",
",",
"rewind",
"=",
"rewind",
")",
"predefined_acl",
"=",
"ACL",
".",
"validate_predefined",
"(",
"predefined_acl",
")",
"try",
":",
"created_json",
"=",
"self",
".",
"_do_upload",
"(",
"client",
",",
"file_obj",
",",
"content_type",
",",
"size",
",",
"num_retries",
",",
"predefined_acl",
")",
"self",
".",
"_set_properties",
"(",
"created_json",
")",
"except",
"resumable_media",
".",
"InvalidResponse",
"as",
"exc",
":",
"_raise_from_invalid_response",
"(",
"exc",
")"
] | Upload the contents of this blob from a file-like object.
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning`_ and `lifecycle`_ API documents
for details.
Uploading a file with a `customer-supplied`_ encryption key:
.. literalinclude:: snippets.py
:start-after: [START upload_from_file]
:end-before: [END upload_from_file]
:dedent: 4
The ``encryption_key`` should be a str or bytes with a length of at
least 32.
For more fine-grained over the upload process, check out
`google-resumable-media`_.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type file_obj: file
:param file_obj: A file handle open for reading.
:type rewind: bool
:param rewind: If True, seek to the beginning of the file handle before
writing the file to Cloud Storage.
:type size: int
:param size: The number of bytes to be uploaded (which will be read
from ``file_obj``). If not provided, the upload will be
concluded once ``file_obj`` is exhausted.
:type content_type: str
:param content_type: Optional type of content being uploaded.
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
: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 blob's bucket.
:type predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
:raises: :class:`~google.cloud.exceptions.GoogleCloudError`
if the upload response returns an error status.
.. _object versioning: https://cloud.google.com/storage/\
docs/object-versioning
.. _lifecycle: https://cloud.google.com/storage/docs/lifecycle | [
"Upload",
"the",
"contents",
"of",
"this",
"blob",
"from",
"a",
"file",
"-",
"like",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1072-L1161 |
28,094 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.upload_from_filename | def upload_from_filename(
self, filename, content_type=None, client=None, predefined_acl=None
):
"""Upload this blob's contents from the content of a named file.
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The value given by ``mimetypes.guess_type``
- The default value ('application/octet-stream')
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type filename: str
:param filename: The path to the file.
:type content_type: str
:param content_type: Optional type of content being uploaded.
: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 blob's bucket.
:type predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
"""
content_type = self._get_content_type(content_type, filename=filename)
with open(filename, "rb") as file_obj:
total_bytes = os.fstat(file_obj.fileno()).st_size
self.upload_from_file(
file_obj,
content_type=content_type,
client=client,
size=total_bytes,
predefined_acl=predefined_acl,
) | python | def upload_from_filename(
self, filename, content_type=None, client=None, predefined_acl=None
):
"""Upload this blob's contents from the content of a named file.
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The value given by ``mimetypes.guess_type``
- The default value ('application/octet-stream')
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type filename: str
:param filename: The path to the file.
:type content_type: str
:param content_type: Optional type of content being uploaded.
: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 blob's bucket.
:type predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
"""
content_type = self._get_content_type(content_type, filename=filename)
with open(filename, "rb") as file_obj:
total_bytes = os.fstat(file_obj.fileno()).st_size
self.upload_from_file(
file_obj,
content_type=content_type,
client=client,
size=total_bytes,
predefined_acl=predefined_acl,
) | [
"def",
"upload_from_filename",
"(",
"self",
",",
"filename",
",",
"content_type",
"=",
"None",
",",
"client",
"=",
"None",
",",
"predefined_acl",
"=",
"None",
")",
":",
"content_type",
"=",
"self",
".",
"_get_content_type",
"(",
"content_type",
",",
"filename",
"=",
"filename",
")",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"file_obj",
":",
"total_bytes",
"=",
"os",
".",
"fstat",
"(",
"file_obj",
".",
"fileno",
"(",
")",
")",
".",
"st_size",
"self",
".",
"upload_from_file",
"(",
"file_obj",
",",
"content_type",
"=",
"content_type",
",",
"client",
"=",
"client",
",",
"size",
"=",
"total_bytes",
",",
"predefined_acl",
"=",
"predefined_acl",
",",
")"
] | Upload this blob's contents from the content of a named file.
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The value given by ``mimetypes.guess_type``
- The default value ('application/octet-stream')
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type filename: str
:param filename: The path to the file.
:type content_type: str
:param content_type: Optional type of content being uploaded.
: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 blob's bucket.
:type predefined_acl: str
:param predefined_acl: (Optional) predefined access control list | [
"Upload",
"this",
"blob",
"s",
"contents",
"from",
"the",
"content",
"of",
"a",
"named",
"file",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1163-L1213 |
28,095 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.upload_from_string | def upload_from_string(
self, data, content_type="text/plain", client=None, predefined_acl=None
):
"""Upload contents of this blob from the provided string.
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type data: bytes or str
:param data: The data to store in this blob. If the value is
text, it will be encoded as UTF-8.
:type content_type: str
:param content_type: Optional type of content being uploaded. Defaults
to ``'text/plain'``.
: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 predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
"""
data = _to_bytes(data, encoding="utf-8")
string_buffer = BytesIO(data)
self.upload_from_file(
file_obj=string_buffer,
size=len(data),
content_type=content_type,
client=client,
predefined_acl=predefined_acl,
) | python | def upload_from_string(
self, data, content_type="text/plain", client=None, predefined_acl=None
):
"""Upload contents of this blob from the provided string.
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type data: bytes or str
:param data: The data to store in this blob. If the value is
text, it will be encoded as UTF-8.
:type content_type: str
:param content_type: Optional type of content being uploaded. Defaults
to ``'text/plain'``.
: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 predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
"""
data = _to_bytes(data, encoding="utf-8")
string_buffer = BytesIO(data)
self.upload_from_file(
file_obj=string_buffer,
size=len(data),
content_type=content_type,
client=client,
predefined_acl=predefined_acl,
) | [
"def",
"upload_from_string",
"(",
"self",
",",
"data",
",",
"content_type",
"=",
"\"text/plain\"",
",",
"client",
"=",
"None",
",",
"predefined_acl",
"=",
"None",
")",
":",
"data",
"=",
"_to_bytes",
"(",
"data",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"string_buffer",
"=",
"BytesIO",
"(",
"data",
")",
"self",
".",
"upload_from_file",
"(",
"file_obj",
"=",
"string_buffer",
",",
"size",
"=",
"len",
"(",
"data",
")",
",",
"content_type",
"=",
"content_type",
",",
"client",
"=",
"client",
",",
"predefined_acl",
"=",
"predefined_acl",
",",
")"
] | Upload contents of this blob from the provided string.
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type data: bytes or str
:param data: The data to store in this blob. If the value is
text, it will be encoded as UTF-8.
:type content_type: str
:param content_type: Optional type of content being uploaded. Defaults
to ``'text/plain'``.
: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 predefined_acl: str
:param predefined_acl: (Optional) predefined access control list | [
"Upload",
"contents",
"of",
"this",
"blob",
"from",
"the",
"provided",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1215-L1258 |
28,096 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.create_resumable_upload_session | def create_resumable_upload_session(
self, content_type=None, size=None, origin=None, client=None
):
"""Create a resumable upload session.
Resumable upload sessions allow you to start an upload session from
one client and complete the session in another. This method is called
by the initiator to set the metadata and limits. The initiator then
passes the session URL to the client that will upload the binary data.
The client performs a PUT request on the session URL to complete the
upload. This process allows untrusted clients to upload to an
access-controlled bucket. For more details, see the
`documentation on signed URLs`_.
.. _documentation on signed URLs:
https://cloud.google.com/storage/\
docs/access-control/signed-urls#signing-resumable
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
If :attr:`encryption_key` is set, the blob will be encrypted with
a `customer-supplied`_ encryption key.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type size: int
:param size: (Optional). The maximum number of bytes that can be
uploaded using this session. If the size is not known
when creating the session, this should be left blank.
:type content_type: str
:param content_type: (Optional) Type of content being uploaded.
:type origin: str
:param origin: (Optional) If set, the upload can only be completed
by a user-agent that uploads from the given origin. This
can be useful when passing the session to a web client.
: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 blob's bucket.
:rtype: str
:returns: The resumable upload session URL. The upload can be
completed by making an HTTP PUT request with the
file's contents.
:raises: :class:`google.cloud.exceptions.GoogleCloudError`
if the session creation response returns an error status.
"""
extra_headers = {}
if origin is not None:
# This header is specifically for client-side uploads, it
# determines the origins allowed for CORS.
extra_headers["Origin"] = origin
try:
dummy_stream = BytesIO(b"")
# Send a fake the chunk size which we **know** will be acceptable
# to the `ResumableUpload` constructor. The chunk size only
# matters when **sending** bytes to an upload.
upload, _ = self._initiate_resumable_upload(
client,
dummy_stream,
content_type,
size,
None,
predefined_acl=None,
extra_headers=extra_headers,
chunk_size=self._CHUNK_SIZE_MULTIPLE,
)
return upload.resumable_url
except resumable_media.InvalidResponse as exc:
_raise_from_invalid_response(exc) | python | def create_resumable_upload_session(
self, content_type=None, size=None, origin=None, client=None
):
"""Create a resumable upload session.
Resumable upload sessions allow you to start an upload session from
one client and complete the session in another. This method is called
by the initiator to set the metadata and limits. The initiator then
passes the session URL to the client that will upload the binary data.
The client performs a PUT request on the session URL to complete the
upload. This process allows untrusted clients to upload to an
access-controlled bucket. For more details, see the
`documentation on signed URLs`_.
.. _documentation on signed URLs:
https://cloud.google.com/storage/\
docs/access-control/signed-urls#signing-resumable
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
If :attr:`encryption_key` is set, the blob will be encrypted with
a `customer-supplied`_ encryption key.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type size: int
:param size: (Optional). The maximum number of bytes that can be
uploaded using this session. If the size is not known
when creating the session, this should be left blank.
:type content_type: str
:param content_type: (Optional) Type of content being uploaded.
:type origin: str
:param origin: (Optional) If set, the upload can only be completed
by a user-agent that uploads from the given origin. This
can be useful when passing the session to a web client.
: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 blob's bucket.
:rtype: str
:returns: The resumable upload session URL. The upload can be
completed by making an HTTP PUT request with the
file's contents.
:raises: :class:`google.cloud.exceptions.GoogleCloudError`
if the session creation response returns an error status.
"""
extra_headers = {}
if origin is not None:
# This header is specifically for client-side uploads, it
# determines the origins allowed for CORS.
extra_headers["Origin"] = origin
try:
dummy_stream = BytesIO(b"")
# Send a fake the chunk size which we **know** will be acceptable
# to the `ResumableUpload` constructor. The chunk size only
# matters when **sending** bytes to an upload.
upload, _ = self._initiate_resumable_upload(
client,
dummy_stream,
content_type,
size,
None,
predefined_acl=None,
extra_headers=extra_headers,
chunk_size=self._CHUNK_SIZE_MULTIPLE,
)
return upload.resumable_url
except resumable_media.InvalidResponse as exc:
_raise_from_invalid_response(exc) | [
"def",
"create_resumable_upload_session",
"(",
"self",
",",
"content_type",
"=",
"None",
",",
"size",
"=",
"None",
",",
"origin",
"=",
"None",
",",
"client",
"=",
"None",
")",
":",
"extra_headers",
"=",
"{",
"}",
"if",
"origin",
"is",
"not",
"None",
":",
"# This header is specifically for client-side uploads, it",
"# determines the origins allowed for CORS.",
"extra_headers",
"[",
"\"Origin\"",
"]",
"=",
"origin",
"try",
":",
"dummy_stream",
"=",
"BytesIO",
"(",
"b\"\"",
")",
"# Send a fake the chunk size which we **know** will be acceptable",
"# to the `ResumableUpload` constructor. The chunk size only",
"# matters when **sending** bytes to an upload.",
"upload",
",",
"_",
"=",
"self",
".",
"_initiate_resumable_upload",
"(",
"client",
",",
"dummy_stream",
",",
"content_type",
",",
"size",
",",
"None",
",",
"predefined_acl",
"=",
"None",
",",
"extra_headers",
"=",
"extra_headers",
",",
"chunk_size",
"=",
"self",
".",
"_CHUNK_SIZE_MULTIPLE",
",",
")",
"return",
"upload",
".",
"resumable_url",
"except",
"resumable_media",
".",
"InvalidResponse",
"as",
"exc",
":",
"_raise_from_invalid_response",
"(",
"exc",
")"
] | Create a resumable upload session.
Resumable upload sessions allow you to start an upload session from
one client and complete the session in another. This method is called
by the initiator to set the metadata and limits. The initiator then
passes the session URL to the client that will upload the binary data.
The client performs a PUT request on the session URL to complete the
upload. This process allows untrusted clients to upload to an
access-controlled bucket. For more details, see the
`documentation on signed URLs`_.
.. _documentation on signed URLs:
https://cloud.google.com/storage/\
docs/access-control/signed-urls#signing-resumable
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The default value ('application/octet-stream')
.. note::
The effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/storage/docs/object-versioning>`_ and
`lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
API documents for details.
If :attr:`encryption_key` is set, the blob will be encrypted with
a `customer-supplied`_ encryption key.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type size: int
:param size: (Optional). The maximum number of bytes that can be
uploaded using this session. If the size is not known
when creating the session, this should be left blank.
:type content_type: str
:param content_type: (Optional) Type of content being uploaded.
:type origin: str
:param origin: (Optional) If set, the upload can only be completed
by a user-agent that uploads from the given origin. This
can be useful when passing the session to a web client.
: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 blob's bucket.
:rtype: str
:returns: The resumable upload session URL. The upload can be
completed by making an HTTP PUT request with the
file's contents.
:raises: :class:`google.cloud.exceptions.GoogleCloudError`
if the session creation response returns an error status. | [
"Create",
"a",
"resumable",
"upload",
"session",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1260-L1351 |
28,097 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.make_public | def make_public(self, client=None):
"""Update blob's ACL, granting read access to anonymous users.
: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.
"""
self.acl.all().grant_read()
self.acl.save(client=client) | python | def make_public(self, client=None):
"""Update blob's ACL, granting read access to anonymous users.
: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.
"""
self.acl.all().grant_read()
self.acl.save(client=client) | [
"def",
"make_public",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"self",
".",
"acl",
".",
"all",
"(",
")",
".",
"grant_read",
"(",
")",
"self",
".",
"acl",
".",
"save",
"(",
"client",
"=",
"client",
")"
] | Update blob's ACL, granting read access to anonymous users.
: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. | [
"Update",
"blob",
"s",
"ACL",
"granting",
"read",
"access",
"to",
"anonymous",
"users",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1474-L1483 |
28,098 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.make_private | def make_private(self, client=None):
"""Update blob's ACL, revoking read access for anonymous users.
: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.
"""
self.acl.all().revoke_read()
self.acl.save(client=client) | python | def make_private(self, client=None):
"""Update blob's ACL, revoking read access for anonymous users.
: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.
"""
self.acl.all().revoke_read()
self.acl.save(client=client) | [
"def",
"make_private",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"self",
".",
"acl",
".",
"all",
"(",
")",
".",
"revoke_read",
"(",
")",
"self",
".",
"acl",
".",
"save",
"(",
"client",
"=",
"client",
")"
] | Update blob's ACL, revoking read access for anonymous users.
: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. | [
"Update",
"blob",
"s",
"ACL",
"revoking",
"read",
"access",
"for",
"anonymous",
"users",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1485-L1494 |
28,099 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.compose | def compose(self, sources, client=None):
"""Concatenate source blobs into this one.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type sources: list of :class:`Blob`
:param sources: blobs whose contents will be composed into 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 blob's bucket.
"""
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
request = {
"sourceObjects": [{"name": source.name} for source in sources],
"destination": self._properties.copy(),
}
api_response = client._connection.api_request(
method="POST",
path=self.path + "/compose",
query_params=query_params,
data=request,
_target_object=self,
)
self._set_properties(api_response) | python | def compose(self, sources, client=None):
"""Concatenate source blobs into this one.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type sources: list of :class:`Blob`
:param sources: blobs whose contents will be composed into 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 blob's bucket.
"""
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
request = {
"sourceObjects": [{"name": source.name} for source in sources],
"destination": self._properties.copy(),
}
api_response = client._connection.api_request(
method="POST",
path=self.path + "/compose",
query_params=query_params,
data=request,
_target_object=self,
)
self._set_properties(api_response) | [
"def",
"compose",
"(",
"self",
",",
"sources",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"query_params",
"=",
"{",
"}",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"query_params",
"[",
"\"userProject\"",
"]",
"=",
"self",
".",
"user_project",
"request",
"=",
"{",
"\"sourceObjects\"",
":",
"[",
"{",
"\"name\"",
":",
"source",
".",
"name",
"}",
"for",
"source",
"in",
"sources",
"]",
",",
"\"destination\"",
":",
"self",
".",
"_properties",
".",
"copy",
"(",
")",
",",
"}",
"api_response",
"=",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"self",
".",
"path",
"+",
"\"/compose\"",
",",
"query_params",
"=",
"query_params",
",",
"data",
"=",
"request",
",",
"_target_object",
"=",
"self",
",",
")",
"self",
".",
"_set_properties",
"(",
"api_response",
")"
] | Concatenate source blobs into this one.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type sources: list of :class:`Blob`
:param sources: blobs whose contents will be composed into 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 blob's bucket. | [
"Concatenate",
"source",
"blobs",
"into",
"this",
"one",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1496-L1527 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.