repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
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
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/client.py
|
Client.create_dataset
|
def create_dataset(self, dataset, exists_ok=False, retry=DEFAULT_RETRY):
"""API call: create the dataset via a POST request.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert
Args:
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A :class:`~google.cloud.bigquery.dataset.Dataset` to create.
If ``dataset`` is a reference, an empty dataset is created
with the specified ID and client's default location.
exists_ok (bool):
Defaults to ``False``. If ``True``, ignore "already exists"
errors when creating the dataset.
retry (google.api_core.retry.Retry):
Optional. How to retry the RPC.
Returns:
google.cloud.bigquery.dataset.Dataset:
A new ``Dataset`` returned from the API.
Example:
>>> from google.cloud import bigquery
>>> client = bigquery.Client()
>>> dataset = bigquery.Dataset(client.dataset('my_dataset'))
>>> dataset = client.create_dataset(dataset)
"""
if isinstance(dataset, str):
dataset = DatasetReference.from_string(
dataset, default_project=self.project
)
if isinstance(dataset, DatasetReference):
dataset = Dataset(dataset)
path = "/projects/%s/datasets" % (dataset.project,)
data = dataset.to_api_repr()
if data.get("location") is None and self.location is not None:
data["location"] = self.location
try:
api_response = self._call_api(retry, method="POST", path=path, data=data)
return Dataset.from_api_repr(api_response)
except google.api_core.exceptions.Conflict:
if not exists_ok:
raise
return self.get_dataset(dataset.reference, retry=retry)
|
python
|
def create_dataset(self, dataset, exists_ok=False, retry=DEFAULT_RETRY):
"""API call: create the dataset via a POST request.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert
Args:
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A :class:`~google.cloud.bigquery.dataset.Dataset` to create.
If ``dataset`` is a reference, an empty dataset is created
with the specified ID and client's default location.
exists_ok (bool):
Defaults to ``False``. If ``True``, ignore "already exists"
errors when creating the dataset.
retry (google.api_core.retry.Retry):
Optional. How to retry the RPC.
Returns:
google.cloud.bigquery.dataset.Dataset:
A new ``Dataset`` returned from the API.
Example:
>>> from google.cloud import bigquery
>>> client = bigquery.Client()
>>> dataset = bigquery.Dataset(client.dataset('my_dataset'))
>>> dataset = client.create_dataset(dataset)
"""
if isinstance(dataset, str):
dataset = DatasetReference.from_string(
dataset, default_project=self.project
)
if isinstance(dataset, DatasetReference):
dataset = Dataset(dataset)
path = "/projects/%s/datasets" % (dataset.project,)
data = dataset.to_api_repr()
if data.get("location") is None and self.location is not None:
data["location"] = self.location
try:
api_response = self._call_api(retry, method="POST", path=path, data=data)
return Dataset.from_api_repr(api_response)
except google.api_core.exceptions.Conflict:
if not exists_ok:
raise
return self.get_dataset(dataset.reference, retry=retry)
|
[
"def",
"create_dataset",
"(",
"self",
",",
"dataset",
",",
"exists_ok",
"=",
"False",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"if",
"isinstance",
"(",
"dataset",
",",
"str",
")",
":",
"dataset",
"=",
"DatasetReference",
".",
"from_string",
"(",
"dataset",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"if",
"isinstance",
"(",
"dataset",
",",
"DatasetReference",
")",
":",
"dataset",
"=",
"Dataset",
"(",
"dataset",
")",
"path",
"=",
"\"/projects/%s/datasets\"",
"%",
"(",
"dataset",
".",
"project",
",",
")",
"data",
"=",
"dataset",
".",
"to_api_repr",
"(",
")",
"if",
"data",
".",
"get",
"(",
"\"location\"",
")",
"is",
"None",
"and",
"self",
".",
"location",
"is",
"not",
"None",
":",
"data",
"[",
"\"location\"",
"]",
"=",
"self",
".",
"location",
"try",
":",
"api_response",
"=",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"path",
",",
"data",
"=",
"data",
")",
"return",
"Dataset",
".",
"from_api_repr",
"(",
"api_response",
")",
"except",
"google",
".",
"api_core",
".",
"exceptions",
".",
"Conflict",
":",
"if",
"not",
"exists_ok",
":",
"raise",
"return",
"self",
".",
"get_dataset",
"(",
"dataset",
".",
"reference",
",",
"retry",
"=",
"retry",
")"
] |
API call: create the dataset via a POST request.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert
Args:
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A :class:`~google.cloud.bigquery.dataset.Dataset` to create.
If ``dataset`` is a reference, an empty dataset is created
with the specified ID and client's default location.
exists_ok (bool):
Defaults to ``False``. If ``True``, ignore "already exists"
errors when creating the dataset.
retry (google.api_core.retry.Retry):
Optional. How to retry the RPC.
Returns:
google.cloud.bigquery.dataset.Dataset:
A new ``Dataset`` returned from the API.
Example:
>>> from google.cloud import bigquery
>>> client = bigquery.Client()
>>> dataset = bigquery.Dataset(client.dataset('my_dataset'))
>>> dataset = client.create_dataset(dataset)
|
[
"API",
"call",
":",
"create",
"the",
"dataset",
"via",
"a",
"POST",
"request",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L311-L363
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/client.py
|
Client.create_table
|
def create_table(self, table, exists_ok=False, retry=DEFAULT_RETRY):
"""API call: create a table via a PUT request
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
A :class:`~google.cloud.bigquery.table.Table` to create.
If ``table`` is a reference, an empty table is created
with the specified ID. The dataset that the table belongs to
must already exist.
exists_ok (bool):
Defaults to ``False``. If ``True``, ignore "already exists"
errors when creating the table.
retry (google.api_core.retry.Retry):
Optional. How to retry the RPC.
Returns:
google.cloud.bigquery.table.Table:
A new ``Table`` returned from the service.
"""
table = _table_arg_to_table(table, default_project=self.project)
path = "/projects/%s/datasets/%s/tables" % (table.project, table.dataset_id)
data = table.to_api_repr()
try:
api_response = self._call_api(retry, method="POST", path=path, data=data)
return Table.from_api_repr(api_response)
except google.api_core.exceptions.Conflict:
if not exists_ok:
raise
return self.get_table(table.reference, retry=retry)
|
python
|
def create_table(self, table, exists_ok=False, retry=DEFAULT_RETRY):
"""API call: create a table via a PUT request
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
A :class:`~google.cloud.bigquery.table.Table` to create.
If ``table`` is a reference, an empty table is created
with the specified ID. The dataset that the table belongs to
must already exist.
exists_ok (bool):
Defaults to ``False``. If ``True``, ignore "already exists"
errors when creating the table.
retry (google.api_core.retry.Retry):
Optional. How to retry the RPC.
Returns:
google.cloud.bigquery.table.Table:
A new ``Table`` returned from the service.
"""
table = _table_arg_to_table(table, default_project=self.project)
path = "/projects/%s/datasets/%s/tables" % (table.project, table.dataset_id)
data = table.to_api_repr()
try:
api_response = self._call_api(retry, method="POST", path=path, data=data)
return Table.from_api_repr(api_response)
except google.api_core.exceptions.Conflict:
if not exists_ok:
raise
return self.get_table(table.reference, retry=retry)
|
[
"def",
"create_table",
"(",
"self",
",",
"table",
",",
"exists_ok",
"=",
"False",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"table",
"=",
"_table_arg_to_table",
"(",
"table",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"path",
"=",
"\"/projects/%s/datasets/%s/tables\"",
"%",
"(",
"table",
".",
"project",
",",
"table",
".",
"dataset_id",
")",
"data",
"=",
"table",
".",
"to_api_repr",
"(",
")",
"try",
":",
"api_response",
"=",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"path",
",",
"data",
"=",
"data",
")",
"return",
"Table",
".",
"from_api_repr",
"(",
"api_response",
")",
"except",
"google",
".",
"api_core",
".",
"exceptions",
".",
"Conflict",
":",
"if",
"not",
"exists_ok",
":",
"raise",
"return",
"self",
".",
"get_table",
"(",
"table",
".",
"reference",
",",
"retry",
"=",
"retry",
")"
] |
API call: create a table via a PUT request
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
A :class:`~google.cloud.bigquery.table.Table` to create.
If ``table`` is a reference, an empty table is created
with the specified ID. The dataset that the table belongs to
must already exist.
exists_ok (bool):
Defaults to ``False``. If ``True``, ignore "already exists"
errors when creating the table.
retry (google.api_core.retry.Retry):
Optional. How to retry the RPC.
Returns:
google.cloud.bigquery.table.Table:
A new ``Table`` returned from the service.
|
[
"API",
"call",
":",
"create",
"a",
"table",
"via",
"a",
"PUT",
"request"
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L365-L401
|
train
|
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
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/client.py
|
Client.get_model
|
def get_model(self, model_ref, retry=DEFAULT_RETRY):
"""[Beta] Fetch the model referenced by ``model_ref``.
Args:
model_ref (Union[ \
:class:`~google.cloud.bigquery.model.ModelReference`, \
str, \
]):
A reference to the model to fetch from the BigQuery API.
If a string is passed in, this method attempts to create a
model reference from a string using
:func:`google.cloud.bigquery.model.ModelReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.model.Model:
A ``Model`` instance.
"""
if isinstance(model_ref, str):
model_ref = ModelReference.from_string(
model_ref, default_project=self.project
)
api_response = self._call_api(retry, method="GET", path=model_ref.path)
return Model.from_api_repr(api_response)
|
python
|
def get_model(self, model_ref, retry=DEFAULT_RETRY):
"""[Beta] Fetch the model referenced by ``model_ref``.
Args:
model_ref (Union[ \
:class:`~google.cloud.bigquery.model.ModelReference`, \
str, \
]):
A reference to the model to fetch from the BigQuery API.
If a string is passed in, this method attempts to create a
model reference from a string using
:func:`google.cloud.bigquery.model.ModelReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.model.Model:
A ``Model`` instance.
"""
if isinstance(model_ref, str):
model_ref = ModelReference.from_string(
model_ref, default_project=self.project
)
api_response = self._call_api(retry, method="GET", path=model_ref.path)
return Model.from_api_repr(api_response)
|
[
"def",
"get_model",
"(",
"self",
",",
"model_ref",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"if",
"isinstance",
"(",
"model_ref",
",",
"str",
")",
":",
"model_ref",
"=",
"ModelReference",
".",
"from_string",
"(",
"model_ref",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"api_response",
"=",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"model_ref",
".",
"path",
")",
"return",
"Model",
".",
"from_api_repr",
"(",
"api_response",
")"
] |
[Beta] Fetch the model referenced by ``model_ref``.
Args:
model_ref (Union[ \
:class:`~google.cloud.bigquery.model.ModelReference`, \
str, \
]):
A reference to the model to fetch from the BigQuery API.
If a string is passed in, this method attempts to create a
model reference from a string using
:func:`google.cloud.bigquery.model.ModelReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.cloud.bigquery.model.Model:
A ``Model`` instance.
|
[
"[",
"Beta",
"]",
"Fetch",
"the",
"model",
"referenced",
"by",
"model_ref",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L436-L461
|
train
|
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
|
train
|
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
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/client.py
|
Client.update_model
|
def update_model(self, model, fields, retry=DEFAULT_RETRY):
"""[Beta] Change some fields of a model.
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 ``model``, it will be deleted.
If ``model.etag`` is not ``None``, the update will only succeed if
the model on the server has the same ETag. Thus reading a model with
``get_model``, changing its fields, and then passing it to
``update_model`` will ensure that the changes will only be saved if
no modifications to the model occurred since the read.
Args:
model (google.cloud.bigquery.model.Model): The model to update.
fields (Sequence[str]):
The fields of ``model`` to change, spelled as the Model
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.model.Model:
The model resource returned from the API call.
"""
partial = model._build_resource(fields)
if model.etag:
headers = {"If-Match": model.etag}
else:
headers = None
api_response = self._call_api(
retry, method="PATCH", path=model.path, data=partial, headers=headers
)
return Model.from_api_repr(api_response)
|
python
|
def update_model(self, model, fields, retry=DEFAULT_RETRY):
"""[Beta] Change some fields of a model.
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 ``model``, it will be deleted.
If ``model.etag`` is not ``None``, the update will only succeed if
the model on the server has the same ETag. Thus reading a model with
``get_model``, changing its fields, and then passing it to
``update_model`` will ensure that the changes will only be saved if
no modifications to the model occurred since the read.
Args:
model (google.cloud.bigquery.model.Model): The model to update.
fields (Sequence[str]):
The fields of ``model`` to change, spelled as the Model
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.model.Model:
The model resource returned from the API call.
"""
partial = model._build_resource(fields)
if model.etag:
headers = {"If-Match": model.etag}
else:
headers = None
api_response = self._call_api(
retry, method="PATCH", path=model.path, data=partial, headers=headers
)
return Model.from_api_repr(api_response)
|
[
"def",
"update_model",
"(",
"self",
",",
"model",
",",
"fields",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"partial",
"=",
"model",
".",
"_build_resource",
"(",
"fields",
")",
"if",
"model",
".",
"etag",
":",
"headers",
"=",
"{",
"\"If-Match\"",
":",
"model",
".",
"etag",
"}",
"else",
":",
"headers",
"=",
"None",
"api_response",
"=",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"PATCH\"",
",",
"path",
"=",
"model",
".",
"path",
",",
"data",
"=",
"partial",
",",
"headers",
"=",
"headers",
")",
"return",
"Model",
".",
"from_api_repr",
"(",
"api_response",
")"
] |
[Beta] Change some fields of a model.
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 ``model``, it will be deleted.
If ``model.etag`` is not ``None``, the update will only succeed if
the model on the server has the same ETag. Thus reading a model with
``get_model``, changing its fields, and then passing it to
``update_model`` will ensure that the changes will only be saved if
no modifications to the model occurred since the read.
Args:
model (google.cloud.bigquery.model.Model): The model to update.
fields (Sequence[str]):
The fields of ``model`` to change, spelled as the Model
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.model.Model:
The model resource returned from the API call.
|
[
"[",
"Beta",
"]",
"Change",
"some",
"fields",
"of",
"a",
"model",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L523-L556
|
train
|
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
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/client.py
|
Client.list_models
|
def list_models(
self, dataset, max_results=None, page_token=None, retry=DEFAULT_RETRY
):
"""[Beta] List models in the dataset.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/models/list
Args:
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A reference to the dataset whose models to list 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`.
max_results (int):
(Optional) Maximum number of models to return. If not passed,
defaults to a value set by the API.
page_token (str):
(Optional) Token representing a cursor into the models. If
not passed, the API will return the first page of models. 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 (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.api_core.page_iterator.Iterator:
Iterator of
:class:`~google.cloud.bigquery.model.Model` contained
within the requested dataset.
"""
if isinstance(dataset, str):
dataset = DatasetReference.from_string(
dataset, default_project=self.project
)
if not isinstance(dataset, (Dataset, DatasetReference)):
raise TypeError("dataset must be a Dataset, DatasetReference, or string")
path = "%s/models" % dataset.path
result = page_iterator.HTTPIterator(
client=self,
api_request=functools.partial(self._call_api, retry),
path=path,
item_to_value=_item_to_model,
items_key="models",
page_token=page_token,
max_results=max_results,
)
result.dataset = dataset
return result
|
python
|
def list_models(
self, dataset, max_results=None, page_token=None, retry=DEFAULT_RETRY
):
"""[Beta] List models in the dataset.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/models/list
Args:
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A reference to the dataset whose models to list 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`.
max_results (int):
(Optional) Maximum number of models to return. If not passed,
defaults to a value set by the API.
page_token (str):
(Optional) Token representing a cursor into the models. If
not passed, the API will return the first page of models. 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 (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.api_core.page_iterator.Iterator:
Iterator of
:class:`~google.cloud.bigquery.model.Model` contained
within the requested dataset.
"""
if isinstance(dataset, str):
dataset = DatasetReference.from_string(
dataset, default_project=self.project
)
if not isinstance(dataset, (Dataset, DatasetReference)):
raise TypeError("dataset must be a Dataset, DatasetReference, or string")
path = "%s/models" % dataset.path
result = page_iterator.HTTPIterator(
client=self,
api_request=functools.partial(self._call_api, retry),
path=path,
item_to_value=_item_to_model,
items_key="models",
page_token=page_token,
max_results=max_results,
)
result.dataset = dataset
return result
|
[
"def",
"list_models",
"(",
"self",
",",
"dataset",
",",
"max_results",
"=",
"None",
",",
"page_token",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"if",
"isinstance",
"(",
"dataset",
",",
"str",
")",
":",
"dataset",
"=",
"DatasetReference",
".",
"from_string",
"(",
"dataset",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"if",
"not",
"isinstance",
"(",
"dataset",
",",
"(",
"Dataset",
",",
"DatasetReference",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"dataset must be a Dataset, DatasetReference, or string\"",
")",
"path",
"=",
"\"%s/models\"",
"%",
"dataset",
".",
"path",
"result",
"=",
"page_iterator",
".",
"HTTPIterator",
"(",
"client",
"=",
"self",
",",
"api_request",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_call_api",
",",
"retry",
")",
",",
"path",
"=",
"path",
",",
"item_to_value",
"=",
"_item_to_model",
",",
"items_key",
"=",
"\"models\"",
",",
"page_token",
"=",
"page_token",
",",
"max_results",
"=",
"max_results",
",",
")",
"result",
".",
"dataset",
"=",
"dataset",
"return",
"result"
] |
[Beta] List models in the dataset.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/models/list
Args:
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A reference to the dataset whose models to list 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`.
max_results (int):
(Optional) Maximum number of models to return. If not passed,
defaults to a value set by the API.
page_token (str):
(Optional) Token representing a cursor into the models. If
not passed, the API will return the first page of models. 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 (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
Returns:
google.api_core.page_iterator.Iterator:
Iterator of
:class:`~google.cloud.bigquery.model.Model` contained
within the requested dataset.
|
[
"[",
"Beta",
"]",
"List",
"models",
"in",
"the",
"dataset",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L593-L649
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/client.py
|
Client.delete_dataset
|
def delete_dataset(
self, dataset, delete_contents=False, retry=DEFAULT_RETRY, not_found_ok=False
):
"""Delete a dataset.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/delete
Args
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A reference to the dataset to delete. 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`.
delete_contents (boolean):
(Optional) If True, delete all the tables in the dataset. If
False and the dataset contains tables, the request will fail.
Default is False.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
not_found_ok (bool):
Defaults to ``False``. If ``True``, ignore "not found" errors
when deleting the dataset.
"""
if isinstance(dataset, str):
dataset = DatasetReference.from_string(
dataset, default_project=self.project
)
if not isinstance(dataset, (Dataset, DatasetReference)):
raise TypeError("dataset must be a Dataset or a DatasetReference")
params = {}
if delete_contents:
params["deleteContents"] = "true"
try:
self._call_api(
retry, method="DELETE", path=dataset.path, query_params=params
)
except google.api_core.exceptions.NotFound:
if not not_found_ok:
raise
|
python
|
def delete_dataset(
self, dataset, delete_contents=False, retry=DEFAULT_RETRY, not_found_ok=False
):
"""Delete a dataset.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/delete
Args
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A reference to the dataset to delete. 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`.
delete_contents (boolean):
(Optional) If True, delete all the tables in the dataset. If
False and the dataset contains tables, the request will fail.
Default is False.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
not_found_ok (bool):
Defaults to ``False``. If ``True``, ignore "not found" errors
when deleting the dataset.
"""
if isinstance(dataset, str):
dataset = DatasetReference.from_string(
dataset, default_project=self.project
)
if not isinstance(dataset, (Dataset, DatasetReference)):
raise TypeError("dataset must be a Dataset or a DatasetReference")
params = {}
if delete_contents:
params["deleteContents"] = "true"
try:
self._call_api(
retry, method="DELETE", path=dataset.path, query_params=params
)
except google.api_core.exceptions.NotFound:
if not not_found_ok:
raise
|
[
"def",
"delete_dataset",
"(",
"self",
",",
"dataset",
",",
"delete_contents",
"=",
"False",
",",
"retry",
"=",
"DEFAULT_RETRY",
",",
"not_found_ok",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"dataset",
",",
"str",
")",
":",
"dataset",
"=",
"DatasetReference",
".",
"from_string",
"(",
"dataset",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"if",
"not",
"isinstance",
"(",
"dataset",
",",
"(",
"Dataset",
",",
"DatasetReference",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"dataset must be a Dataset or a DatasetReference\"",
")",
"params",
"=",
"{",
"}",
"if",
"delete_contents",
":",
"params",
"[",
"\"deleteContents\"",
"]",
"=",
"\"true\"",
"try",
":",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"DELETE\"",
",",
"path",
"=",
"dataset",
".",
"path",
",",
"query_params",
"=",
"params",
")",
"except",
"google",
".",
"api_core",
".",
"exceptions",
".",
"NotFound",
":",
"if",
"not",
"not_found_ok",
":",
"raise"
] |
Delete a dataset.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/delete
Args
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
str, \
]):
A reference to the dataset to delete. 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`.
delete_contents (boolean):
(Optional) If True, delete all the tables in the dataset. If
False and the dataset contains tables, the request will fail.
Default is False.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
not_found_ok (bool):
Defaults to ``False``. If ``True``, ignore "not found" errors
when deleting the dataset.
|
[
"Delete",
"a",
"dataset",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L709-L755
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/client.py
|
Client.delete_model
|
def delete_model(self, model, retry=DEFAULT_RETRY, not_found_ok=False):
"""[Beta] Delete a model
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/models/delete
Args:
model (Union[ \
:class:`~google.cloud.bigquery.model.Model`, \
:class:`~google.cloud.bigquery.model.ModelReference`, \
str, \
]):
A reference to the model to delete. If a string is passed in,
this method attempts to create a model reference from a
string using
:func:`google.cloud.bigquery.model.ModelReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
not_found_ok (bool):
Defaults to ``False``. If ``True``, ignore "not found" errors
when deleting the model.
"""
if isinstance(model, str):
model = ModelReference.from_string(model, default_project=self.project)
if not isinstance(model, (Model, ModelReference)):
raise TypeError("model must be a Model or a ModelReference")
try:
self._call_api(retry, method="DELETE", path=model.path)
except google.api_core.exceptions.NotFound:
if not not_found_ok:
raise
|
python
|
def delete_model(self, model, retry=DEFAULT_RETRY, not_found_ok=False):
"""[Beta] Delete a model
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/models/delete
Args:
model (Union[ \
:class:`~google.cloud.bigquery.model.Model`, \
:class:`~google.cloud.bigquery.model.ModelReference`, \
str, \
]):
A reference to the model to delete. If a string is passed in,
this method attempts to create a model reference from a
string using
:func:`google.cloud.bigquery.model.ModelReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
not_found_ok (bool):
Defaults to ``False``. If ``True``, ignore "not found" errors
when deleting the model.
"""
if isinstance(model, str):
model = ModelReference.from_string(model, default_project=self.project)
if not isinstance(model, (Model, ModelReference)):
raise TypeError("model must be a Model or a ModelReference")
try:
self._call_api(retry, method="DELETE", path=model.path)
except google.api_core.exceptions.NotFound:
if not not_found_ok:
raise
|
[
"def",
"delete_model",
"(",
"self",
",",
"model",
",",
"retry",
"=",
"DEFAULT_RETRY",
",",
"not_found_ok",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"str",
")",
":",
"model",
"=",
"ModelReference",
".",
"from_string",
"(",
"model",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"if",
"not",
"isinstance",
"(",
"model",
",",
"(",
"Model",
",",
"ModelReference",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"model must be a Model or a ModelReference\"",
")",
"try",
":",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"DELETE\"",
",",
"path",
"=",
"model",
".",
"path",
")",
"except",
"google",
".",
"api_core",
".",
"exceptions",
".",
"NotFound",
":",
"if",
"not",
"not_found_ok",
":",
"raise"
] |
[Beta] Delete a model
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/models/delete
Args:
model (Union[ \
:class:`~google.cloud.bigquery.model.Model`, \
:class:`~google.cloud.bigquery.model.ModelReference`, \
str, \
]):
A reference to the model to delete. If a string is passed in,
this method attempts to create a model reference from a
string using
:func:`google.cloud.bigquery.model.ModelReference.from_string`.
retry (:class:`google.api_core.retry.Retry`):
(Optional) How to retry the RPC.
not_found_ok (bool):
Defaults to ``False``. If ``True``, ignore "not found" errors
when deleting the model.
|
[
"[",
"Beta",
"]",
"Delete",
"a",
"model"
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L757-L789
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/client.py
|
Client.delete_table
|
def delete_table(self, table, retry=DEFAULT_RETRY, not_found_ok=False):
"""Delete a table
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/delete
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
A reference to the table to delete. 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.
not_found_ok (bool):
Defaults to ``False``. If ``True``, ignore "not found" errors
when deleting the table.
"""
table = _table_arg_to_table_ref(table, default_project=self.project)
if not isinstance(table, TableReference):
raise TypeError("Unable to get TableReference for table '{}'".format(table))
try:
self._call_api(retry, method="DELETE", path=table.path)
except google.api_core.exceptions.NotFound:
if not not_found_ok:
raise
|
python
|
def delete_table(self, table, retry=DEFAULT_RETRY, not_found_ok=False):
"""Delete a table
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/delete
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
A reference to the table to delete. 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.
not_found_ok (bool):
Defaults to ``False``. If ``True``, ignore "not found" errors
when deleting the table.
"""
table = _table_arg_to_table_ref(table, default_project=self.project)
if not isinstance(table, TableReference):
raise TypeError("Unable to get TableReference for table '{}'".format(table))
try:
self._call_api(retry, method="DELETE", path=table.path)
except google.api_core.exceptions.NotFound:
if not not_found_ok:
raise
|
[
"def",
"delete_table",
"(",
"self",
",",
"table",
",",
"retry",
"=",
"DEFAULT_RETRY",
",",
"not_found_ok",
"=",
"False",
")",
":",
"table",
"=",
"_table_arg_to_table_ref",
"(",
"table",
",",
"default_project",
"=",
"self",
".",
"project",
")",
"if",
"not",
"isinstance",
"(",
"table",
",",
"TableReference",
")",
":",
"raise",
"TypeError",
"(",
"\"Unable to get TableReference for table '{}'\"",
".",
"format",
"(",
"table",
")",
")",
"try",
":",
"self",
".",
"_call_api",
"(",
"retry",
",",
"method",
"=",
"\"DELETE\"",
",",
"path",
"=",
"table",
".",
"path",
")",
"except",
"google",
".",
"api_core",
".",
"exceptions",
".",
"NotFound",
":",
"if",
"not",
"not_found_ok",
":",
"raise"
] |
Delete a table
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/delete
Args:
table (Union[ \
:class:`~google.cloud.bigquery.table.Table`, \
:class:`~google.cloud.bigquery.table.TableReference`, \
str, \
]):
A reference to the table to delete. 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.
not_found_ok (bool):
Defaults to ``False``. If ``True``, ignore "not found" errors
when deleting the table.
|
[
"Delete",
"a",
"table"
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L791-L821
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/client.py
|
Client._do_resumable_upload
|
def _do_resumable_upload(self, stream, metadata, num_retries):
"""Perform a resumable upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:rtype: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the final chunk
is uploaded.
"""
upload, transport = self._initiate_resumable_upload(
stream, metadata, num_retries
)
while not upload.finished:
response = upload.transmit_next_chunk(transport)
return response
|
python
|
def _do_resumable_upload(self, stream, metadata, num_retries):
"""Perform a resumable upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:rtype: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the final chunk
is uploaded.
"""
upload, transport = self._initiate_resumable_upload(
stream, metadata, num_retries
)
while not upload.finished:
response = upload.transmit_next_chunk(transport)
return response
|
[
"def",
"_do_resumable_upload",
"(",
"self",
",",
"stream",
",",
"metadata",
",",
"num_retries",
")",
":",
"upload",
",",
"transport",
"=",
"self",
".",
"_initiate_resumable_upload",
"(",
"stream",
",",
"metadata",
",",
"num_retries",
")",
"while",
"not",
"upload",
".",
"finished",
":",
"response",
"=",
"upload",
".",
"transmit_next_chunk",
"(",
"transport",
")",
"return",
"response"
] |
Perform a resumable upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:rtype: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the final chunk
is uploaded.
|
[
"Perform",
"a",
"resumable",
"upload",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1311-L1335
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/client.py
|
Client._initiate_resumable_upload
|
def _initiate_resumable_upload(self, stream, metadata, num_retries):
"""Initiate a resumable upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:rtype: tuple
:returns:
Pair of
* The :class:`~google.resumable_media.requests.ResumableUpload`
that was created
* The ``transport`` used to initiate the upload.
"""
chunk_size = _DEFAULT_CHUNKSIZE
transport = self._http
headers = _get_upload_headers(self._connection.USER_AGENT)
upload_url = _RESUMABLE_URL_TEMPLATE.format(project=self.project)
# TODO: modify ResumableUpload to take a retry.Retry object
# that it can use for the initial RPC.
upload = ResumableUpload(upload_url, chunk_size, headers=headers)
if num_retries is not None:
upload._retry_strategy = resumable_media.RetryStrategy(
max_retries=num_retries
)
upload.initiate(
transport, stream, metadata, _GENERIC_CONTENT_TYPE, stream_final=False
)
return upload, transport
|
python
|
def _initiate_resumable_upload(self, stream, metadata, num_retries):
"""Initiate a resumable upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:rtype: tuple
:returns:
Pair of
* The :class:`~google.resumable_media.requests.ResumableUpload`
that was created
* The ``transport`` used to initiate the upload.
"""
chunk_size = _DEFAULT_CHUNKSIZE
transport = self._http
headers = _get_upload_headers(self._connection.USER_AGENT)
upload_url = _RESUMABLE_URL_TEMPLATE.format(project=self.project)
# TODO: modify ResumableUpload to take a retry.Retry object
# that it can use for the initial RPC.
upload = ResumableUpload(upload_url, chunk_size, headers=headers)
if num_retries is not None:
upload._retry_strategy = resumable_media.RetryStrategy(
max_retries=num_retries
)
upload.initiate(
transport, stream, metadata, _GENERIC_CONTENT_TYPE, stream_final=False
)
return upload, transport
|
[
"def",
"_initiate_resumable_upload",
"(",
"self",
",",
"stream",
",",
"metadata",
",",
"num_retries",
")",
":",
"chunk_size",
"=",
"_DEFAULT_CHUNKSIZE",
"transport",
"=",
"self",
".",
"_http",
"headers",
"=",
"_get_upload_headers",
"(",
"self",
".",
"_connection",
".",
"USER_AGENT",
")",
"upload_url",
"=",
"_RESUMABLE_URL_TEMPLATE",
".",
"format",
"(",
"project",
"=",
"self",
".",
"project",
")",
"# TODO: modify ResumableUpload to take a retry.Retry object",
"# that it can use for the initial RPC.",
"upload",
"=",
"ResumableUpload",
"(",
"upload_url",
",",
"chunk_size",
",",
"headers",
"=",
"headers",
")",
"if",
"num_retries",
"is",
"not",
"None",
":",
"upload",
".",
"_retry_strategy",
"=",
"resumable_media",
".",
"RetryStrategy",
"(",
"max_retries",
"=",
"num_retries",
")",
"upload",
".",
"initiate",
"(",
"transport",
",",
"stream",
",",
"metadata",
",",
"_GENERIC_CONTENT_TYPE",
",",
"stream_final",
"=",
"False",
")",
"return",
"upload",
",",
"transport"
] |
Initiate a resumable upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:rtype: tuple
:returns:
Pair of
* The :class:`~google.resumable_media.requests.ResumableUpload`
that was created
* The ``transport`` used to initiate the upload.
|
[
"Initiate",
"a",
"resumable",
"upload",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1337-L1375
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/client.py
|
Client._do_multipart_upload
|
def _do_multipart_upload(self, stream, metadata, size, num_retries):
"""Perform a multipart upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
: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.)
:rtype: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the multipart
upload request.
:raises: :exc:`ValueError` if the ``stream`` has fewer than ``size``
bytes remaining.
"""
data = stream.read(size)
if len(data) < size:
msg = _READ_LESS_THAN_SIZE.format(size, len(data))
raise ValueError(msg)
headers = _get_upload_headers(self._connection.USER_AGENT)
upload_url = _MULTIPART_URL_TEMPLATE.format(project=self.project)
upload = MultipartUpload(upload_url, headers=headers)
if num_retries is not None:
upload._retry_strategy = resumable_media.RetryStrategy(
max_retries=num_retries
)
response = upload.transmit(self._http, data, metadata, _GENERIC_CONTENT_TYPE)
return response
|
python
|
def _do_multipart_upload(self, stream, metadata, size, num_retries):
"""Perform a multipart upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
: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.)
:rtype: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the multipart
upload request.
:raises: :exc:`ValueError` if the ``stream`` has fewer than ``size``
bytes remaining.
"""
data = stream.read(size)
if len(data) < size:
msg = _READ_LESS_THAN_SIZE.format(size, len(data))
raise ValueError(msg)
headers = _get_upload_headers(self._connection.USER_AGENT)
upload_url = _MULTIPART_URL_TEMPLATE.format(project=self.project)
upload = MultipartUpload(upload_url, headers=headers)
if num_retries is not None:
upload._retry_strategy = resumable_media.RetryStrategy(
max_retries=num_retries
)
response = upload.transmit(self._http, data, metadata, _GENERIC_CONTENT_TYPE)
return response
|
[
"def",
"_do_multipart_upload",
"(",
"self",
",",
"stream",
",",
"metadata",
",",
"size",
",",
"num_retries",
")",
":",
"data",
"=",
"stream",
".",
"read",
"(",
"size",
")",
"if",
"len",
"(",
"data",
")",
"<",
"size",
":",
"msg",
"=",
"_READ_LESS_THAN_SIZE",
".",
"format",
"(",
"size",
",",
"len",
"(",
"data",
")",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"headers",
"=",
"_get_upload_headers",
"(",
"self",
".",
"_connection",
".",
"USER_AGENT",
")",
"upload_url",
"=",
"_MULTIPART_URL_TEMPLATE",
".",
"format",
"(",
"project",
"=",
"self",
".",
"project",
")",
"upload",
"=",
"MultipartUpload",
"(",
"upload_url",
",",
"headers",
"=",
"headers",
")",
"if",
"num_retries",
"is",
"not",
"None",
":",
"upload",
".",
"_retry_strategy",
"=",
"resumable_media",
".",
"RetryStrategy",
"(",
"max_retries",
"=",
"num_retries",
")",
"response",
"=",
"upload",
".",
"transmit",
"(",
"self",
".",
"_http",
",",
"data",
",",
"metadata",
",",
"_GENERIC_CONTENT_TYPE",
")",
"return",
"response"
] |
Perform a multipart upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
: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.)
:rtype: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the multipart
upload request.
:raises: :exc:`ValueError` if the ``stream`` has fewer than ``size``
bytes remaining.
|
[
"Perform",
"a",
"multipart",
"upload",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L1377-L1418
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/instance.py
|
Instance.create
|
def create(self):
"""Create this instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance
.. note::
Uses the ``project`` and ``instance_id`` on the current
:class:`Instance` in addition to the ``display_name``.
To change them before creating, reset the values via
.. code:: python
instance.display_name = 'New display name'
instance.instance_id = 'i-changed-my-mind'
before calling :meth:`create`.
:rtype: :class:`google.api_core.operation.Operation`
:returns: an operation instance
:raises Conflict: if the instance already exists
"""
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,
)
metadata = _metadata_with_prefix(self.name)
future = api.create_instance(
parent=self._client.project_name,
instance_id=self.instance_id,
instance=instance_pb,
metadata=metadata,
)
return future
|
python
|
def create(self):
"""Create this instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance
.. note::
Uses the ``project`` and ``instance_id`` on the current
:class:`Instance` in addition to the ``display_name``.
To change them before creating, reset the values via
.. code:: python
instance.display_name = 'New display name'
instance.instance_id = 'i-changed-my-mind'
before calling :meth:`create`.
:rtype: :class:`google.api_core.operation.Operation`
:returns: an operation instance
:raises Conflict: if the instance already exists
"""
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,
)
metadata = _metadata_with_prefix(self.name)
future = api.create_instance(
parent=self._client.project_name,
instance_id=self.instance_id,
instance=instance_pb,
metadata=metadata,
)
return future
|
[
"def",
"create",
"(",
"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",
",",
")",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"future",
"=",
"api",
".",
"create_instance",
"(",
"parent",
"=",
"self",
".",
"_client",
".",
"project_name",
",",
"instance_id",
"=",
"self",
".",
"instance_id",
",",
"instance",
"=",
"instance_pb",
",",
"metadata",
"=",
"metadata",
",",
")",
"return",
"future"
] |
Create this instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance
.. note::
Uses the ``project`` and ``instance_id`` on the current
:class:`Instance` in addition to the ``display_name``.
To change them before creating, reset the values via
.. code:: python
instance.display_name = 'New display name'
instance.instance_id = 'i-changed-my-mind'
before calling :meth:`create`.
:rtype: :class:`google.api_core.operation.Operation`
:returns: an operation instance
:raises Conflict: if the instance already exists
|
[
"Create",
"this",
"instance",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/instance.py#L182-L221
|
train
|
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
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/instance.py
|
Instance.reload
|
def reload(self):
"""Reload the metadata for this instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig
:raises NotFound: if the instance does not exist
"""
api = self._client.instance_admin_api
metadata = _metadata_with_prefix(self.name)
instance_pb = api.get_instance(self.name, metadata=metadata)
self._update_from_pb(instance_pb)
|
python
|
def reload(self):
"""Reload the metadata for this instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig
:raises NotFound: if the instance does not exist
"""
api = self._client.instance_admin_api
metadata = _metadata_with_prefix(self.name)
instance_pb = api.get_instance(self.name, metadata=metadata)
self._update_from_pb(instance_pb)
|
[
"def",
"reload",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"_client",
".",
"instance_admin_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"instance_pb",
"=",
"api",
".",
"get_instance",
"(",
"self",
".",
"name",
",",
"metadata",
"=",
"metadata",
")",
"self",
".",
"_update_from_pb",
"(",
"instance_pb",
")"
] |
Reload the metadata for this instance.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig
:raises NotFound: if the instance does not exist
|
[
"Reload",
"the",
"metadata",
"for",
"this",
"instance",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/instance.py#L242-L255
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
googleapis/google-cloud-python
|
error_reporting/google/cloud/error_reporting/util.py
|
build_flask_context
|
def build_flask_context(request):
"""Builds an HTTP context object from a Flask (Werkzeug) request object.
This helper method extracts the relevant HTTP context from a Flask request
object into an object ready to be sent to Error Reporting.
.. code-block:: python
>>> @app.errorhandler(HTTPException)
... def handle_error(exc):
... client.report_exception(
... http_context=build_flask_context(request))
... # rest of error response code here
:type request: :class:`werkzeug.wrappers.request`
:param request: The Flask request object to convert.
:rtype: :class:`~google.cloud.error_reporting.client.HTTPContext`
:returns: An HTTPContext object ready to be sent to the Stackdriver Error
Reporting API.
"""
return HTTPContext(
url=request.url,
method=request.method,
user_agent=request.user_agent.string,
referrer=request.referrer,
remote_ip=request.remote_addr,
)
|
python
|
def build_flask_context(request):
"""Builds an HTTP context object from a Flask (Werkzeug) request object.
This helper method extracts the relevant HTTP context from a Flask request
object into an object ready to be sent to Error Reporting.
.. code-block:: python
>>> @app.errorhandler(HTTPException)
... def handle_error(exc):
... client.report_exception(
... http_context=build_flask_context(request))
... # rest of error response code here
:type request: :class:`werkzeug.wrappers.request`
:param request: The Flask request object to convert.
:rtype: :class:`~google.cloud.error_reporting.client.HTTPContext`
:returns: An HTTPContext object ready to be sent to the Stackdriver Error
Reporting API.
"""
return HTTPContext(
url=request.url,
method=request.method,
user_agent=request.user_agent.string,
referrer=request.referrer,
remote_ip=request.remote_addr,
)
|
[
"def",
"build_flask_context",
"(",
"request",
")",
":",
"return",
"HTTPContext",
"(",
"url",
"=",
"request",
".",
"url",
",",
"method",
"=",
"request",
".",
"method",
",",
"user_agent",
"=",
"request",
".",
"user_agent",
".",
"string",
",",
"referrer",
"=",
"request",
".",
"referrer",
",",
"remote_ip",
"=",
"request",
".",
"remote_addr",
",",
")"
] |
Builds an HTTP context object from a Flask (Werkzeug) request object.
This helper method extracts the relevant HTTP context from a Flask request
object into an object ready to be sent to Error Reporting.
.. code-block:: python
>>> @app.errorhandler(HTTPException)
... def handle_error(exc):
... client.report_exception(
... http_context=build_flask_context(request))
... # rest of error response code here
:type request: :class:`werkzeug.wrappers.request`
:param request: The Flask request object to convert.
:rtype: :class:`~google.cloud.error_reporting.client.HTTPContext`
:returns: An HTTPContext object ready to be sent to the Stackdriver Error
Reporting API.
|
[
"Builds",
"an",
"HTTP",
"context",
"object",
"from",
"a",
"Flask",
"(",
"Werkzeug",
")",
"request",
"object",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/error_reporting/util.py#L20-L47
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/blob.py
|
Blob._get_writable_metadata
|
def _get_writable_metadata(self):
"""Get the object / blob metadata which is writable.
This is intended to be used when creating a new object / blob.
See the `API reference docs`_ for more information, the fields
marked as writable are:
* ``acl``
* ``cacheControl``
* ``contentDisposition``
* ``contentEncoding``
* ``contentLanguage``
* ``contentType``
* ``crc32c``
* ``md5Hash``
* ``metadata``
* ``name``
* ``storageClass``
For now, we don't support ``acl``, access control lists should be
managed directly through :class:`ObjectACL` methods.
"""
# NOTE: This assumes `self.name` is unicode.
object_metadata = {"name": self.name}
for key in self._changes:
if key in _WRITABLE_FIELDS:
object_metadata[key] = self._properties[key]
return object_metadata
|
python
|
def _get_writable_metadata(self):
"""Get the object / blob metadata which is writable.
This is intended to be used when creating a new object / blob.
See the `API reference docs`_ for more information, the fields
marked as writable are:
* ``acl``
* ``cacheControl``
* ``contentDisposition``
* ``contentEncoding``
* ``contentLanguage``
* ``contentType``
* ``crc32c``
* ``md5Hash``
* ``metadata``
* ``name``
* ``storageClass``
For now, we don't support ``acl``, access control lists should be
managed directly through :class:`ObjectACL` methods.
"""
# NOTE: This assumes `self.name` is unicode.
object_metadata = {"name": self.name}
for key in self._changes:
if key in _WRITABLE_FIELDS:
object_metadata[key] = self._properties[key]
return object_metadata
|
[
"def",
"_get_writable_metadata",
"(",
"self",
")",
":",
"# NOTE: This assumes `self.name` is unicode.",
"object_metadata",
"=",
"{",
"\"name\"",
":",
"self",
".",
"name",
"}",
"for",
"key",
"in",
"self",
".",
"_changes",
":",
"if",
"key",
"in",
"_WRITABLE_FIELDS",
":",
"object_metadata",
"[",
"key",
"]",
"=",
"self",
".",
"_properties",
"[",
"key",
"]",
"return",
"object_metadata"
] |
Get the object / blob metadata which is writable.
This is intended to be used when creating a new object / blob.
See the `API reference docs`_ for more information, the fields
marked as writable are:
* ``acl``
* ``cacheControl``
* ``contentDisposition``
* ``contentEncoding``
* ``contentLanguage``
* ``contentType``
* ``crc32c``
* ``md5Hash``
* ``metadata``
* ``name``
* ``storageClass``
For now, we don't support ``acl``, access control lists should be
managed directly through :class:`ObjectACL` methods.
|
[
"Get",
"the",
"object",
"/",
"blob",
"metadata",
"which",
"is",
"writable",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L730-L759
|
train
|
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
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/blob.py
|
Blob._do_multipart_upload
|
def _do_multipart_upload(
self, client, stream, content_type, size, num_retries, predefined_acl
):
"""Perform a multipart upload.
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: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the multipart
upload request.
:raises: :exc:`ValueError` if ``size`` is not :data:`None` but the
``stream`` has fewer than ``size`` bytes remaining.
"""
if size is None:
data = stream.read()
else:
data = stream.read(size)
if len(data) < size:
msg = _READ_LESS_THAN_SIZE.format(size, len(data))
raise ValueError(msg)
transport = self._get_transport(client)
info = self._get_upload_arguments(content_type)
headers, object_metadata, content_type = info
base_url = _MULTIPART_URL_TEMPLATE.format(bucket_path=self.bucket.path)
name_value_pairs = []
if self.user_project is not None:
name_value_pairs.append(("userProject", self.user_project))
if self.kms_key_name is not None:
name_value_pairs.append(("kmsKeyName", self.kms_key_name))
if predefined_acl is not None:
name_value_pairs.append(("predefinedAcl", predefined_acl))
upload_url = _add_query_parameters(base_url, name_value_pairs)
upload = MultipartUpload(upload_url, headers=headers)
if num_retries is not None:
upload._retry_strategy = resumable_media.RetryStrategy(
max_retries=num_retries
)
response = upload.transmit(transport, data, object_metadata, content_type)
return response
|
python
|
def _do_multipart_upload(
self, client, stream, content_type, size, num_retries, predefined_acl
):
"""Perform a multipart upload.
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: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the multipart
upload request.
:raises: :exc:`ValueError` if ``size`` is not :data:`None` but the
``stream`` has fewer than ``size`` bytes remaining.
"""
if size is None:
data = stream.read()
else:
data = stream.read(size)
if len(data) < size:
msg = _READ_LESS_THAN_SIZE.format(size, len(data))
raise ValueError(msg)
transport = self._get_transport(client)
info = self._get_upload_arguments(content_type)
headers, object_metadata, content_type = info
base_url = _MULTIPART_URL_TEMPLATE.format(bucket_path=self.bucket.path)
name_value_pairs = []
if self.user_project is not None:
name_value_pairs.append(("userProject", self.user_project))
if self.kms_key_name is not None:
name_value_pairs.append(("kmsKeyName", self.kms_key_name))
if predefined_acl is not None:
name_value_pairs.append(("predefinedAcl", predefined_acl))
upload_url = _add_query_parameters(base_url, name_value_pairs)
upload = MultipartUpload(upload_url, headers=headers)
if num_retries is not None:
upload._retry_strategy = resumable_media.RetryStrategy(
max_retries=num_retries
)
response = upload.transmit(transport, data, object_metadata, content_type)
return response
|
[
"def",
"_do_multipart_upload",
"(",
"self",
",",
"client",
",",
"stream",
",",
"content_type",
",",
"size",
",",
"num_retries",
",",
"predefined_acl",
")",
":",
"if",
"size",
"is",
"None",
":",
"data",
"=",
"stream",
".",
"read",
"(",
")",
"else",
":",
"data",
"=",
"stream",
".",
"read",
"(",
"size",
")",
"if",
"len",
"(",
"data",
")",
"<",
"size",
":",
"msg",
"=",
"_READ_LESS_THAN_SIZE",
".",
"format",
"(",
"size",
",",
"len",
"(",
"data",
")",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"transport",
"=",
"self",
".",
"_get_transport",
"(",
"client",
")",
"info",
"=",
"self",
".",
"_get_upload_arguments",
"(",
"content_type",
")",
"headers",
",",
"object_metadata",
",",
"content_type",
"=",
"info",
"base_url",
"=",
"_MULTIPART_URL_TEMPLATE",
".",
"format",
"(",
"bucket_path",
"=",
"self",
".",
"bucket",
".",
"path",
")",
"name_value_pairs",
"=",
"[",
"]",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"name_value_pairs",
".",
"append",
"(",
"(",
"\"userProject\"",
",",
"self",
".",
"user_project",
")",
")",
"if",
"self",
".",
"kms_key_name",
"is",
"not",
"None",
":",
"name_value_pairs",
".",
"append",
"(",
"(",
"\"kmsKeyName\"",
",",
"self",
".",
"kms_key_name",
")",
")",
"if",
"predefined_acl",
"is",
"not",
"None",
":",
"name_value_pairs",
".",
"append",
"(",
"(",
"\"predefinedAcl\"",
",",
"predefined_acl",
")",
")",
"upload_url",
"=",
"_add_query_parameters",
"(",
"base_url",
",",
"name_value_pairs",
")",
"upload",
"=",
"MultipartUpload",
"(",
"upload_url",
",",
"headers",
"=",
"headers",
")",
"if",
"num_retries",
"is",
"not",
"None",
":",
"upload",
".",
"_retry_strategy",
"=",
"resumable_media",
".",
"RetryStrategy",
"(",
"max_retries",
"=",
"num_retries",
")",
"response",
"=",
"upload",
".",
"transmit",
"(",
"transport",
",",
"data",
",",
"object_metadata",
",",
"content_type",
")",
"return",
"response"
] |
Perform a multipart upload.
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: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the multipart
upload request.
:raises: :exc:`ValueError` if ``size`` is not :data:`None` but the
``stream`` has fewer than ``size`` bytes remaining.
|
[
"Perform",
"a",
"multipart",
"upload",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L785-L859
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/blob.py
|
Blob._initiate_resumable_upload
|
def _initiate_resumable_upload(
self,
client,
stream,
content_type,
size,
num_retries,
predefined_acl=None,
extra_headers=None,
chunk_size=None,
):
"""Initiate a resumable upload.
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 predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:type extra_headers: dict
:param extra_headers: (Optional) Extra headers to add to standard
headers.
:type chunk_size: int
:param chunk_size:
(Optional) Chunk size to use when creating a
:class:`~google.resumable_media.requests.ResumableUpload`.
If not passed, will fall back to the chunk size on the
current blob.
:rtype: tuple
:returns:
Pair of
* The :class:`~google.resumable_media.requests.ResumableUpload`
that was created
* The ``transport`` used to initiate the upload.
"""
if chunk_size is None:
chunk_size = self.chunk_size
if chunk_size is None:
chunk_size = _DEFAULT_CHUNKSIZE
transport = self._get_transport(client)
info = self._get_upload_arguments(content_type)
headers, object_metadata, content_type = info
if extra_headers is not None:
headers.update(extra_headers)
base_url = _RESUMABLE_URL_TEMPLATE.format(bucket_path=self.bucket.path)
name_value_pairs = []
if self.user_project is not None:
name_value_pairs.append(("userProject", self.user_project))
if self.kms_key_name is not None:
name_value_pairs.append(("kmsKeyName", self.kms_key_name))
if predefined_acl is not None:
name_value_pairs.append(("predefinedAcl", predefined_acl))
upload_url = _add_query_parameters(base_url, name_value_pairs)
upload = ResumableUpload(upload_url, chunk_size, headers=headers)
if num_retries is not None:
upload._retry_strategy = resumable_media.RetryStrategy(
max_retries=num_retries
)
upload.initiate(
transport,
stream,
object_metadata,
content_type,
total_bytes=size,
stream_final=False,
)
return upload, transport
|
python
|
def _initiate_resumable_upload(
self,
client,
stream,
content_type,
size,
num_retries,
predefined_acl=None,
extra_headers=None,
chunk_size=None,
):
"""Initiate a resumable upload.
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 predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:type extra_headers: dict
:param extra_headers: (Optional) Extra headers to add to standard
headers.
:type chunk_size: int
:param chunk_size:
(Optional) Chunk size to use when creating a
:class:`~google.resumable_media.requests.ResumableUpload`.
If not passed, will fall back to the chunk size on the
current blob.
:rtype: tuple
:returns:
Pair of
* The :class:`~google.resumable_media.requests.ResumableUpload`
that was created
* The ``transport`` used to initiate the upload.
"""
if chunk_size is None:
chunk_size = self.chunk_size
if chunk_size is None:
chunk_size = _DEFAULT_CHUNKSIZE
transport = self._get_transport(client)
info = self._get_upload_arguments(content_type)
headers, object_metadata, content_type = info
if extra_headers is not None:
headers.update(extra_headers)
base_url = _RESUMABLE_URL_TEMPLATE.format(bucket_path=self.bucket.path)
name_value_pairs = []
if self.user_project is not None:
name_value_pairs.append(("userProject", self.user_project))
if self.kms_key_name is not None:
name_value_pairs.append(("kmsKeyName", self.kms_key_name))
if predefined_acl is not None:
name_value_pairs.append(("predefinedAcl", predefined_acl))
upload_url = _add_query_parameters(base_url, name_value_pairs)
upload = ResumableUpload(upload_url, chunk_size, headers=headers)
if num_retries is not None:
upload._retry_strategy = resumable_media.RetryStrategy(
max_retries=num_retries
)
upload.initiate(
transport,
stream,
object_metadata,
content_type,
total_bytes=size,
stream_final=False,
)
return upload, transport
|
[
"def",
"_initiate_resumable_upload",
"(",
"self",
",",
"client",
",",
"stream",
",",
"content_type",
",",
"size",
",",
"num_retries",
",",
"predefined_acl",
"=",
"None",
",",
"extra_headers",
"=",
"None",
",",
"chunk_size",
"=",
"None",
",",
")",
":",
"if",
"chunk_size",
"is",
"None",
":",
"chunk_size",
"=",
"self",
".",
"chunk_size",
"if",
"chunk_size",
"is",
"None",
":",
"chunk_size",
"=",
"_DEFAULT_CHUNKSIZE",
"transport",
"=",
"self",
".",
"_get_transport",
"(",
"client",
")",
"info",
"=",
"self",
".",
"_get_upload_arguments",
"(",
"content_type",
")",
"headers",
",",
"object_metadata",
",",
"content_type",
"=",
"info",
"if",
"extra_headers",
"is",
"not",
"None",
":",
"headers",
".",
"update",
"(",
"extra_headers",
")",
"base_url",
"=",
"_RESUMABLE_URL_TEMPLATE",
".",
"format",
"(",
"bucket_path",
"=",
"self",
".",
"bucket",
".",
"path",
")",
"name_value_pairs",
"=",
"[",
"]",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"name_value_pairs",
".",
"append",
"(",
"(",
"\"userProject\"",
",",
"self",
".",
"user_project",
")",
")",
"if",
"self",
".",
"kms_key_name",
"is",
"not",
"None",
":",
"name_value_pairs",
".",
"append",
"(",
"(",
"\"kmsKeyName\"",
",",
"self",
".",
"kms_key_name",
")",
")",
"if",
"predefined_acl",
"is",
"not",
"None",
":",
"name_value_pairs",
".",
"append",
"(",
"(",
"\"predefinedAcl\"",
",",
"predefined_acl",
")",
")",
"upload_url",
"=",
"_add_query_parameters",
"(",
"base_url",
",",
"name_value_pairs",
")",
"upload",
"=",
"ResumableUpload",
"(",
"upload_url",
",",
"chunk_size",
",",
"headers",
"=",
"headers",
")",
"if",
"num_retries",
"is",
"not",
"None",
":",
"upload",
".",
"_retry_strategy",
"=",
"resumable_media",
".",
"RetryStrategy",
"(",
"max_retries",
"=",
"num_retries",
")",
"upload",
".",
"initiate",
"(",
"transport",
",",
"stream",
",",
"object_metadata",
",",
"content_type",
",",
"total_bytes",
"=",
"size",
",",
"stream_final",
"=",
"False",
",",
")",
"return",
"upload",
",",
"transport"
] |
Initiate a resumable upload.
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 predefined_acl: str
:param predefined_acl: (Optional) predefined access control list
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
argument will be removed in a future release.)
:type extra_headers: dict
:param extra_headers: (Optional) Extra headers to add to standard
headers.
:type chunk_size: int
:param chunk_size:
(Optional) Chunk size to use when creating a
:class:`~google.resumable_media.requests.ResumableUpload`.
If not passed, will fall back to the chunk size on the
current blob.
:rtype: tuple
:returns:
Pair of
* The :class:`~google.resumable_media.requests.ResumableUpload`
that was created
* The ``transport`` used to initiate the upload.
|
[
"Initiate",
"a",
"resumable",
"upload",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L861-L962
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/blob.py
|
Blob._do_resumable_upload
|
def _do_resumable_upload(
self, client, stream, content_type, size, num_retries, predefined_acl
):
"""Perform a resumable upload.
Assumes ``chunk_size`` is not :data:`None` on the current blob.
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: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the final chunk
is uploaded.
"""
upload, transport = self._initiate_resumable_upload(
client,
stream,
content_type,
size,
num_retries,
predefined_acl=predefined_acl,
)
while not upload.finished:
response = upload.transmit_next_chunk(transport)
return response
|
python
|
def _do_resumable_upload(
self, client, stream, content_type, size, num_retries, predefined_acl
):
"""Perform a resumable upload.
Assumes ``chunk_size`` is not :data:`None` on the current blob.
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: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the final chunk
is uploaded.
"""
upload, transport = self._initiate_resumable_upload(
client,
stream,
content_type,
size,
num_retries,
predefined_acl=predefined_acl,
)
while not upload.finished:
response = upload.transmit_next_chunk(transport)
return response
|
[
"def",
"_do_resumable_upload",
"(",
"self",
",",
"client",
",",
"stream",
",",
"content_type",
",",
"size",
",",
"num_retries",
",",
"predefined_acl",
")",
":",
"upload",
",",
"transport",
"=",
"self",
".",
"_initiate_resumable_upload",
"(",
"client",
",",
"stream",
",",
"content_type",
",",
"size",
",",
"num_retries",
",",
"predefined_acl",
"=",
"predefined_acl",
",",
")",
"while",
"not",
"upload",
".",
"finished",
":",
"response",
"=",
"upload",
".",
"transmit_next_chunk",
"(",
"transport",
")",
"return",
"response"
] |
Perform a resumable upload.
Assumes ``chunk_size`` is not :data:`None` on the current blob.
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: :class:`~requests.Response`
:returns: The "200 OK" response object returned after the final chunk
is uploaded.
|
[
"Perform",
"a",
"resumable",
"upload",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L964-L1016
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/blob.py
|
Blob.rewrite
|
def rewrite(self, source, token=None, client=None):
"""Rewrite source blob into this one.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type source: :class:`Blob`
:param source: blob whose contents will be rewritten into this blob.
:type token: str
:param token: Optional. Token returned from an earlier, not-completed
call to rewrite the same source blob. If passed,
result will include updated status, total bytes written.
: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: tuple
:returns: ``(token, bytes_rewritten, total_bytes)``, where ``token``
is a rewrite token (``None`` if the rewrite is complete),
``bytes_rewritten`` is the number of bytes rewritten so far,
and ``total_bytes`` is the total number of bytes to be
rewritten.
"""
client = self._require_client(client)
headers = _get_encryption_headers(self._encryption_key)
headers.update(_get_encryption_headers(source._encryption_key, source=True))
query_params = self._query_params
if "generation" in query_params:
del query_params["generation"]
if token:
query_params["rewriteToken"] = token
if source.generation:
query_params["sourceGeneration"] = source.generation
if self.kms_key_name is not None:
query_params["destinationKmsKeyName"] = self.kms_key_name
api_response = client._connection.api_request(
method="POST",
path=source.path + "/rewriteTo" + self.path,
query_params=query_params,
data=self._properties,
headers=headers,
_target_object=self,
)
rewritten = int(api_response["totalBytesRewritten"])
size = int(api_response["objectSize"])
# The resource key is set if and only if the API response is
# completely done. Additionally, there is no rewrite token to return
# in this case.
if api_response["done"]:
self._set_properties(api_response["resource"])
return None, rewritten, size
return api_response["rewriteToken"], rewritten, size
|
python
|
def rewrite(self, source, token=None, client=None):
"""Rewrite source blob into this one.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type source: :class:`Blob`
:param source: blob whose contents will be rewritten into this blob.
:type token: str
:param token: Optional. Token returned from an earlier, not-completed
call to rewrite the same source blob. If passed,
result will include updated status, total bytes written.
: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: tuple
:returns: ``(token, bytes_rewritten, total_bytes)``, where ``token``
is a rewrite token (``None`` if the rewrite is complete),
``bytes_rewritten`` is the number of bytes rewritten so far,
and ``total_bytes`` is the total number of bytes to be
rewritten.
"""
client = self._require_client(client)
headers = _get_encryption_headers(self._encryption_key)
headers.update(_get_encryption_headers(source._encryption_key, source=True))
query_params = self._query_params
if "generation" in query_params:
del query_params["generation"]
if token:
query_params["rewriteToken"] = token
if source.generation:
query_params["sourceGeneration"] = source.generation
if self.kms_key_name is not None:
query_params["destinationKmsKeyName"] = self.kms_key_name
api_response = client._connection.api_request(
method="POST",
path=source.path + "/rewriteTo" + self.path,
query_params=query_params,
data=self._properties,
headers=headers,
_target_object=self,
)
rewritten = int(api_response["totalBytesRewritten"])
size = int(api_response["objectSize"])
# The resource key is set if and only if the API response is
# completely done. Additionally, there is no rewrite token to return
# in this case.
if api_response["done"]:
self._set_properties(api_response["resource"])
return None, rewritten, size
return api_response["rewriteToken"], rewritten, size
|
[
"def",
"rewrite",
"(",
"self",
",",
"source",
",",
"token",
"=",
"None",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"headers",
"=",
"_get_encryption_headers",
"(",
"self",
".",
"_encryption_key",
")",
"headers",
".",
"update",
"(",
"_get_encryption_headers",
"(",
"source",
".",
"_encryption_key",
",",
"source",
"=",
"True",
")",
")",
"query_params",
"=",
"self",
".",
"_query_params",
"if",
"\"generation\"",
"in",
"query_params",
":",
"del",
"query_params",
"[",
"\"generation\"",
"]",
"if",
"token",
":",
"query_params",
"[",
"\"rewriteToken\"",
"]",
"=",
"token",
"if",
"source",
".",
"generation",
":",
"query_params",
"[",
"\"sourceGeneration\"",
"]",
"=",
"source",
".",
"generation",
"if",
"self",
".",
"kms_key_name",
"is",
"not",
"None",
":",
"query_params",
"[",
"\"destinationKmsKeyName\"",
"]",
"=",
"self",
".",
"kms_key_name",
"api_response",
"=",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"source",
".",
"path",
"+",
"\"/rewriteTo\"",
"+",
"self",
".",
"path",
",",
"query_params",
"=",
"query_params",
",",
"data",
"=",
"self",
".",
"_properties",
",",
"headers",
"=",
"headers",
",",
"_target_object",
"=",
"self",
",",
")",
"rewritten",
"=",
"int",
"(",
"api_response",
"[",
"\"totalBytesRewritten\"",
"]",
")",
"size",
"=",
"int",
"(",
"api_response",
"[",
"\"objectSize\"",
"]",
")",
"# The resource key is set if and only if the API response is",
"# completely done. Additionally, there is no rewrite token to return",
"# in this case.",
"if",
"api_response",
"[",
"\"done\"",
"]",
":",
"self",
".",
"_set_properties",
"(",
"api_response",
"[",
"\"resource\"",
"]",
")",
"return",
"None",
",",
"rewritten",
",",
"size",
"return",
"api_response",
"[",
"\"rewriteToken\"",
"]",
",",
"rewritten",
",",
"size"
] |
Rewrite source blob into this one.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type source: :class:`Blob`
:param source: blob whose contents will be rewritten into this blob.
:type token: str
:param token: Optional. Token returned from an earlier, not-completed
call to rewrite the same source blob. If passed,
result will include updated status, total bytes written.
: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: tuple
:returns: ``(token, bytes_rewritten, total_bytes)``, where ``token``
is a rewrite token (``None`` if the rewrite is complete),
``bytes_rewritten`` is the number of bytes rewritten so far,
and ``total_bytes`` is the total number of bytes to be
rewritten.
|
[
"Rewrite",
"source",
"blob",
"into",
"this",
"one",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1529-L1590
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/blob.py
|
Blob.update_storage_class
|
def update_storage_class(self, new_class, client=None):
"""Update blob's storage class via a rewrite-in-place. This helper will
wait for the rewrite to complete before returning, so it may take some
time for large files.
See
https://cloud.google.com/storage/docs/per-object-storage-class
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type new_class: str
:param new_class: new storage class for the object
: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.
"""
if new_class not in self._STORAGE_CLASSES:
raise ValueError("Invalid storage class: %s" % (new_class,))
# Update current blob's storage class prior to rewrite
self._patch_property("storageClass", new_class)
# Execute consecutive rewrite operations until operation is done
token, _, _ = self.rewrite(self)
while token is not None:
token, _, _ = self.rewrite(self, token=token)
|
python
|
def update_storage_class(self, new_class, client=None):
"""Update blob's storage class via a rewrite-in-place. This helper will
wait for the rewrite to complete before returning, so it may take some
time for large files.
See
https://cloud.google.com/storage/docs/per-object-storage-class
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type new_class: str
:param new_class: new storage class for the object
: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.
"""
if new_class not in self._STORAGE_CLASSES:
raise ValueError("Invalid storage class: %s" % (new_class,))
# Update current blob's storage class prior to rewrite
self._patch_property("storageClass", new_class)
# Execute consecutive rewrite operations until operation is done
token, _, _ = self.rewrite(self)
while token is not None:
token, _, _ = self.rewrite(self, token=token)
|
[
"def",
"update_storage_class",
"(",
"self",
",",
"new_class",
",",
"client",
"=",
"None",
")",
":",
"if",
"new_class",
"not",
"in",
"self",
".",
"_STORAGE_CLASSES",
":",
"raise",
"ValueError",
"(",
"\"Invalid storage class: %s\"",
"%",
"(",
"new_class",
",",
")",
")",
"# Update current blob's storage class prior to rewrite",
"self",
".",
"_patch_property",
"(",
"\"storageClass\"",
",",
"new_class",
")",
"# Execute consecutive rewrite operations until operation is done",
"token",
",",
"_",
",",
"_",
"=",
"self",
".",
"rewrite",
"(",
"self",
")",
"while",
"token",
"is",
"not",
"None",
":",
"token",
",",
"_",
",",
"_",
"=",
"self",
".",
"rewrite",
"(",
"self",
",",
"token",
"=",
"token",
")"
] |
Update blob's storage class via a rewrite-in-place. This helper will
wait for the rewrite to complete before returning, so it may take some
time for large files.
See
https://cloud.google.com/storage/docs/per-object-storage-class
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type new_class: str
:param new_class: new storage class for the object
: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.
|
[
"Update",
"blob",
"s",
"storage",
"class",
"via",
"a",
"rewrite",
"-",
"in",
"-",
"place",
".",
"This",
"helper",
"will",
"wait",
"for",
"the",
"rewrite",
"to",
"complete",
"before",
"returning",
"so",
"it",
"may",
"take",
"some",
"time",
"for",
"large",
"files",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1592-L1619
|
train
|
googleapis/google-cloud-python
|
firestore/google/cloud/firestore_v1beta1/_helpers.py
|
verify_path
|
def verify_path(path, is_collection):
"""Verifies that a ``path`` has the correct form.
Checks that all of the elements in ``path`` are strings.
Args:
path (Tuple[str, ...]): The components in a collection or
document path.
is_collection (bool): Indicates if the ``path`` represents
a document or a collection.
Raises:
ValueError: if
* the ``path`` is empty
* ``is_collection=True`` and there are an even number of elements
* ``is_collection=False`` and there are an odd number of elements
* an element is not a string
"""
num_elements = len(path)
if num_elements == 0:
raise ValueError("Document or collection path cannot be empty")
if is_collection:
if num_elements % 2 == 0:
raise ValueError("A collection must have an odd number of path elements")
else:
if num_elements % 2 == 1:
raise ValueError("A document must have an even number of path elements")
for element in path:
if not isinstance(element, six.string_types):
msg = BAD_PATH_TEMPLATE.format(element, type(element))
raise ValueError(msg)
|
python
|
def verify_path(path, is_collection):
"""Verifies that a ``path`` has the correct form.
Checks that all of the elements in ``path`` are strings.
Args:
path (Tuple[str, ...]): The components in a collection or
document path.
is_collection (bool): Indicates if the ``path`` represents
a document or a collection.
Raises:
ValueError: if
* the ``path`` is empty
* ``is_collection=True`` and there are an even number of elements
* ``is_collection=False`` and there are an odd number of elements
* an element is not a string
"""
num_elements = len(path)
if num_elements == 0:
raise ValueError("Document or collection path cannot be empty")
if is_collection:
if num_elements % 2 == 0:
raise ValueError("A collection must have an odd number of path elements")
else:
if num_elements % 2 == 1:
raise ValueError("A document must have an even number of path elements")
for element in path:
if not isinstance(element, six.string_types):
msg = BAD_PATH_TEMPLATE.format(element, type(element))
raise ValueError(msg)
|
[
"def",
"verify_path",
"(",
"path",
",",
"is_collection",
")",
":",
"num_elements",
"=",
"len",
"(",
"path",
")",
"if",
"num_elements",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Document or collection path cannot be empty\"",
")",
"if",
"is_collection",
":",
"if",
"num_elements",
"%",
"2",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"A collection must have an odd number of path elements\"",
")",
"else",
":",
"if",
"num_elements",
"%",
"2",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"\"A document must have an even number of path elements\"",
")",
"for",
"element",
"in",
"path",
":",
"if",
"not",
"isinstance",
"(",
"element",
",",
"six",
".",
"string_types",
")",
":",
"msg",
"=",
"BAD_PATH_TEMPLATE",
".",
"format",
"(",
"element",
",",
"type",
"(",
"element",
")",
")",
"raise",
"ValueError",
"(",
"msg",
")"
] |
Verifies that a ``path`` has the correct form.
Checks that all of the elements in ``path`` are strings.
Args:
path (Tuple[str, ...]): The components in a collection or
document path.
is_collection (bool): Indicates if the ``path`` represents
a document or a collection.
Raises:
ValueError: if
* the ``path`` is empty
* ``is_collection=True`` and there are an even number of elements
* ``is_collection=False`` and there are an odd number of elements
* an element is not a string
|
[
"Verifies",
"that",
"a",
"path",
"has",
"the",
"correct",
"form",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L104-L137
|
train
|
googleapis/google-cloud-python
|
firestore/google/cloud/firestore_v1beta1/_helpers.py
|
encode_value
|
def encode_value(value):
"""Converts a native Python value into a Firestore protobuf ``Value``.
Args:
value (Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]): A native
Python value to convert to a protobuf field.
Returns:
~google.cloud.firestore_v1beta1.types.Value: A
value encoded as a Firestore protobuf.
Raises:
TypeError: If the ``value`` is not one of the accepted types.
"""
if value is None:
return document_pb2.Value(null_value=struct_pb2.NULL_VALUE)
# Must come before six.integer_types since ``bool`` is an integer subtype.
if isinstance(value, bool):
return document_pb2.Value(boolean_value=value)
if isinstance(value, six.integer_types):
return document_pb2.Value(integer_value=value)
if isinstance(value, float):
return document_pb2.Value(double_value=value)
if isinstance(value, DatetimeWithNanoseconds):
return document_pb2.Value(timestamp_value=value.timestamp_pb())
if isinstance(value, datetime.datetime):
return document_pb2.Value(timestamp_value=_datetime_to_pb_timestamp(value))
if isinstance(value, six.text_type):
return document_pb2.Value(string_value=value)
if isinstance(value, six.binary_type):
return document_pb2.Value(bytes_value=value)
# NOTE: We avoid doing an isinstance() check for a Document
# here to avoid import cycles.
document_path = getattr(value, "_document_path", None)
if document_path is not None:
return document_pb2.Value(reference_value=document_path)
if isinstance(value, GeoPoint):
return document_pb2.Value(geo_point_value=value.to_protobuf())
if isinstance(value, list):
value_list = [encode_value(element) for element in value]
value_pb = document_pb2.ArrayValue(values=value_list)
return document_pb2.Value(array_value=value_pb)
if isinstance(value, dict):
value_dict = encode_dict(value)
value_pb = document_pb2.MapValue(fields=value_dict)
return document_pb2.Value(map_value=value_pb)
raise TypeError(
"Cannot convert to a Firestore Value", value, "Invalid type", type(value)
)
|
python
|
def encode_value(value):
"""Converts a native Python value into a Firestore protobuf ``Value``.
Args:
value (Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]): A native
Python value to convert to a protobuf field.
Returns:
~google.cloud.firestore_v1beta1.types.Value: A
value encoded as a Firestore protobuf.
Raises:
TypeError: If the ``value`` is not one of the accepted types.
"""
if value is None:
return document_pb2.Value(null_value=struct_pb2.NULL_VALUE)
# Must come before six.integer_types since ``bool`` is an integer subtype.
if isinstance(value, bool):
return document_pb2.Value(boolean_value=value)
if isinstance(value, six.integer_types):
return document_pb2.Value(integer_value=value)
if isinstance(value, float):
return document_pb2.Value(double_value=value)
if isinstance(value, DatetimeWithNanoseconds):
return document_pb2.Value(timestamp_value=value.timestamp_pb())
if isinstance(value, datetime.datetime):
return document_pb2.Value(timestamp_value=_datetime_to_pb_timestamp(value))
if isinstance(value, six.text_type):
return document_pb2.Value(string_value=value)
if isinstance(value, six.binary_type):
return document_pb2.Value(bytes_value=value)
# NOTE: We avoid doing an isinstance() check for a Document
# here to avoid import cycles.
document_path = getattr(value, "_document_path", None)
if document_path is not None:
return document_pb2.Value(reference_value=document_path)
if isinstance(value, GeoPoint):
return document_pb2.Value(geo_point_value=value.to_protobuf())
if isinstance(value, list):
value_list = [encode_value(element) for element in value]
value_pb = document_pb2.ArrayValue(values=value_list)
return document_pb2.Value(array_value=value_pb)
if isinstance(value, dict):
value_dict = encode_dict(value)
value_pb = document_pb2.MapValue(fields=value_dict)
return document_pb2.Value(map_value=value_pb)
raise TypeError(
"Cannot convert to a Firestore Value", value, "Invalid type", type(value)
)
|
[
"def",
"encode_value",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"null_value",
"=",
"struct_pb2",
".",
"NULL_VALUE",
")",
"# Must come before six.integer_types since ``bool`` is an integer subtype.",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"boolean_value",
"=",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"integer_value",
"=",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"double_value",
"=",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"DatetimeWithNanoseconds",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"timestamp_value",
"=",
"value",
".",
"timestamp_pb",
"(",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"timestamp_value",
"=",
"_datetime_to_pb_timestamp",
"(",
"value",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"text_type",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"string_value",
"=",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"bytes_value",
"=",
"value",
")",
"# NOTE: We avoid doing an isinstance() check for a Document",
"# here to avoid import cycles.",
"document_path",
"=",
"getattr",
"(",
"value",
",",
"\"_document_path\"",
",",
"None",
")",
"if",
"document_path",
"is",
"not",
"None",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"reference_value",
"=",
"document_path",
")",
"if",
"isinstance",
"(",
"value",
",",
"GeoPoint",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"geo_point_value",
"=",
"value",
".",
"to_protobuf",
"(",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value_list",
"=",
"[",
"encode_value",
"(",
"element",
")",
"for",
"element",
"in",
"value",
"]",
"value_pb",
"=",
"document_pb2",
".",
"ArrayValue",
"(",
"values",
"=",
"value_list",
")",
"return",
"document_pb2",
".",
"Value",
"(",
"array_value",
"=",
"value_pb",
")",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"value_dict",
"=",
"encode_dict",
"(",
"value",
")",
"value_pb",
"=",
"document_pb2",
".",
"MapValue",
"(",
"fields",
"=",
"value_dict",
")",
"return",
"document_pb2",
".",
"Value",
"(",
"map_value",
"=",
"value_pb",
")",
"raise",
"TypeError",
"(",
"\"Cannot convert to a Firestore Value\"",
",",
"value",
",",
"\"Invalid type\"",
",",
"type",
"(",
"value",
")",
")"
] |
Converts a native Python value into a Firestore protobuf ``Value``.
Args:
value (Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]): A native
Python value to convert to a protobuf field.
Returns:
~google.cloud.firestore_v1beta1.types.Value: A
value encoded as a Firestore protobuf.
Raises:
TypeError: If the ``value`` is not one of the accepted types.
|
[
"Converts",
"a",
"native",
"Python",
"value",
"into",
"a",
"Firestore",
"protobuf",
"Value",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L140-L201
|
train
|
googleapis/google-cloud-python
|
firestore/google/cloud/firestore_v1beta1/_helpers.py
|
encode_dict
|
def encode_dict(values_dict):
"""Encode a dictionary into protobuf ``Value``-s.
Args:
values_dict (dict): The dictionary to encode as protobuf fields.
Returns:
Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A
dictionary of string keys and ``Value`` protobufs as dictionary
values.
"""
return {key: encode_value(value) for key, value in six.iteritems(values_dict)}
|
python
|
def encode_dict(values_dict):
"""Encode a dictionary into protobuf ``Value``-s.
Args:
values_dict (dict): The dictionary to encode as protobuf fields.
Returns:
Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A
dictionary of string keys and ``Value`` protobufs as dictionary
values.
"""
return {key: encode_value(value) for key, value in six.iteritems(values_dict)}
|
[
"def",
"encode_dict",
"(",
"values_dict",
")",
":",
"return",
"{",
"key",
":",
"encode_value",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"values_dict",
")",
"}"
] |
Encode a dictionary into protobuf ``Value``-s.
Args:
values_dict (dict): The dictionary to encode as protobuf fields.
Returns:
Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A
dictionary of string keys and ``Value`` protobufs as dictionary
values.
|
[
"Encode",
"a",
"dictionary",
"into",
"protobuf",
"Value",
"-",
"s",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L204-L215
|
train
|
googleapis/google-cloud-python
|
firestore/google/cloud/firestore_v1beta1/_helpers.py
|
reference_value_to_document
|
def reference_value_to_document(reference_value, client):
"""Convert a reference value string to a document.
Args:
reference_value (str): A document reference value.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
~.firestore_v1beta1.document.DocumentReference: The document
corresponding to ``reference_value``.
Raises:
ValueError: If the ``reference_value`` is not of the expected
format: ``projects/{project}/databases/{database}/documents/...``.
ValueError: If the ``reference_value`` does not come from the same
project / database combination as the ``client``.
"""
# The first 5 parts are
# projects, {project}, databases, {database}, documents
parts = reference_value.split(DOCUMENT_PATH_DELIMITER, 5)
if len(parts) != 6:
msg = BAD_REFERENCE_ERROR.format(reference_value)
raise ValueError(msg)
# The sixth part is `a/b/c/d` (i.e. the document path)
document = client.document(parts[-1])
if document._document_path != reference_value:
msg = WRONG_APP_REFERENCE.format(reference_value, client._database_string)
raise ValueError(msg)
return document
|
python
|
def reference_value_to_document(reference_value, client):
"""Convert a reference value string to a document.
Args:
reference_value (str): A document reference value.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
~.firestore_v1beta1.document.DocumentReference: The document
corresponding to ``reference_value``.
Raises:
ValueError: If the ``reference_value`` is not of the expected
format: ``projects/{project}/databases/{database}/documents/...``.
ValueError: If the ``reference_value`` does not come from the same
project / database combination as the ``client``.
"""
# The first 5 parts are
# projects, {project}, databases, {database}, documents
parts = reference_value.split(DOCUMENT_PATH_DELIMITER, 5)
if len(parts) != 6:
msg = BAD_REFERENCE_ERROR.format(reference_value)
raise ValueError(msg)
# The sixth part is `a/b/c/d` (i.e. the document path)
document = client.document(parts[-1])
if document._document_path != reference_value:
msg = WRONG_APP_REFERENCE.format(reference_value, client._database_string)
raise ValueError(msg)
return document
|
[
"def",
"reference_value_to_document",
"(",
"reference_value",
",",
"client",
")",
":",
"# The first 5 parts are",
"# projects, {project}, databases, {database}, documents",
"parts",
"=",
"reference_value",
".",
"split",
"(",
"DOCUMENT_PATH_DELIMITER",
",",
"5",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"6",
":",
"msg",
"=",
"BAD_REFERENCE_ERROR",
".",
"format",
"(",
"reference_value",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"# The sixth part is `a/b/c/d` (i.e. the document path)",
"document",
"=",
"client",
".",
"document",
"(",
"parts",
"[",
"-",
"1",
"]",
")",
"if",
"document",
".",
"_document_path",
"!=",
"reference_value",
":",
"msg",
"=",
"WRONG_APP_REFERENCE",
".",
"format",
"(",
"reference_value",
",",
"client",
".",
"_database_string",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"return",
"document"
] |
Convert a reference value string to a document.
Args:
reference_value (str): A document reference value.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
~.firestore_v1beta1.document.DocumentReference: The document
corresponding to ``reference_value``.
Raises:
ValueError: If the ``reference_value`` is not of the expected
format: ``projects/{project}/databases/{database}/documents/...``.
ValueError: If the ``reference_value`` does not come from the same
project / database combination as the ``client``.
|
[
"Convert",
"a",
"reference",
"value",
"string",
"to",
"a",
"document",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L218-L249
|
train
|
googleapis/google-cloud-python
|
firestore/google/cloud/firestore_v1beta1/_helpers.py
|
decode_value
|
def decode_value(value, client):
"""Converts a Firestore protobuf ``Value`` to a native Python value.
Args:
value (google.cloud.firestore_v1beta1.types.Value): A
Firestore protobuf to be decoded / parsed / converted.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]: A native
Python value converted from the ``value``.
Raises:
NotImplementedError: If the ``value_type`` is ``reference_value``.
ValueError: If the ``value_type`` is unknown.
"""
value_type = value.WhichOneof("value_type")
if value_type == "null_value":
return None
elif value_type == "boolean_value":
return value.boolean_value
elif value_type == "integer_value":
return value.integer_value
elif value_type == "double_value":
return value.double_value
elif value_type == "timestamp_value":
return DatetimeWithNanoseconds.from_timestamp_pb(value.timestamp_value)
elif value_type == "string_value":
return value.string_value
elif value_type == "bytes_value":
return value.bytes_value
elif value_type == "reference_value":
return reference_value_to_document(value.reference_value, client)
elif value_type == "geo_point_value":
return GeoPoint(value.geo_point_value.latitude, value.geo_point_value.longitude)
elif value_type == "array_value":
return [decode_value(element, client) for element in value.array_value.values]
elif value_type == "map_value":
return decode_dict(value.map_value.fields, client)
else:
raise ValueError("Unknown ``value_type``", value_type)
|
python
|
def decode_value(value, client):
"""Converts a Firestore protobuf ``Value`` to a native Python value.
Args:
value (google.cloud.firestore_v1beta1.types.Value): A
Firestore protobuf to be decoded / parsed / converted.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]: A native
Python value converted from the ``value``.
Raises:
NotImplementedError: If the ``value_type`` is ``reference_value``.
ValueError: If the ``value_type`` is unknown.
"""
value_type = value.WhichOneof("value_type")
if value_type == "null_value":
return None
elif value_type == "boolean_value":
return value.boolean_value
elif value_type == "integer_value":
return value.integer_value
elif value_type == "double_value":
return value.double_value
elif value_type == "timestamp_value":
return DatetimeWithNanoseconds.from_timestamp_pb(value.timestamp_value)
elif value_type == "string_value":
return value.string_value
elif value_type == "bytes_value":
return value.bytes_value
elif value_type == "reference_value":
return reference_value_to_document(value.reference_value, client)
elif value_type == "geo_point_value":
return GeoPoint(value.geo_point_value.latitude, value.geo_point_value.longitude)
elif value_type == "array_value":
return [decode_value(element, client) for element in value.array_value.values]
elif value_type == "map_value":
return decode_dict(value.map_value.fields, client)
else:
raise ValueError("Unknown ``value_type``", value_type)
|
[
"def",
"decode_value",
"(",
"value",
",",
"client",
")",
":",
"value_type",
"=",
"value",
".",
"WhichOneof",
"(",
"\"value_type\"",
")",
"if",
"value_type",
"==",
"\"null_value\"",
":",
"return",
"None",
"elif",
"value_type",
"==",
"\"boolean_value\"",
":",
"return",
"value",
".",
"boolean_value",
"elif",
"value_type",
"==",
"\"integer_value\"",
":",
"return",
"value",
".",
"integer_value",
"elif",
"value_type",
"==",
"\"double_value\"",
":",
"return",
"value",
".",
"double_value",
"elif",
"value_type",
"==",
"\"timestamp_value\"",
":",
"return",
"DatetimeWithNanoseconds",
".",
"from_timestamp_pb",
"(",
"value",
".",
"timestamp_value",
")",
"elif",
"value_type",
"==",
"\"string_value\"",
":",
"return",
"value",
".",
"string_value",
"elif",
"value_type",
"==",
"\"bytes_value\"",
":",
"return",
"value",
".",
"bytes_value",
"elif",
"value_type",
"==",
"\"reference_value\"",
":",
"return",
"reference_value_to_document",
"(",
"value",
".",
"reference_value",
",",
"client",
")",
"elif",
"value_type",
"==",
"\"geo_point_value\"",
":",
"return",
"GeoPoint",
"(",
"value",
".",
"geo_point_value",
".",
"latitude",
",",
"value",
".",
"geo_point_value",
".",
"longitude",
")",
"elif",
"value_type",
"==",
"\"array_value\"",
":",
"return",
"[",
"decode_value",
"(",
"element",
",",
"client",
")",
"for",
"element",
"in",
"value",
".",
"array_value",
".",
"values",
"]",
"elif",
"value_type",
"==",
"\"map_value\"",
":",
"return",
"decode_dict",
"(",
"value",
".",
"map_value",
".",
"fields",
",",
"client",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown ``value_type``\"",
",",
"value_type",
")"
] |
Converts a Firestore protobuf ``Value`` to a native Python value.
Args:
value (google.cloud.firestore_v1beta1.types.Value): A
Firestore protobuf to be decoded / parsed / converted.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]: A native
Python value converted from the ``value``.
Raises:
NotImplementedError: If the ``value_type`` is ``reference_value``.
ValueError: If the ``value_type`` is unknown.
|
[
"Converts",
"a",
"Firestore",
"protobuf",
"Value",
"to",
"a",
"native",
"Python",
"value",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L252-L295
|
train
|
googleapis/google-cloud-python
|
firestore/google/cloud/firestore_v1beta1/_helpers.py
|
decode_dict
|
def decode_dict(value_fields, client):
"""Converts a protobuf map of Firestore ``Value``-s.
Args:
value_fields (google.protobuf.pyext._message.MessageMapContainer): A
protobuf map of Firestore ``Value``-s.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Dict[str, Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]]: A dictionary
of native Python values converted from the ``value_fields``.
"""
return {
key: decode_value(value, client) for key, value in six.iteritems(value_fields)
}
|
python
|
def decode_dict(value_fields, client):
"""Converts a protobuf map of Firestore ``Value``-s.
Args:
value_fields (google.protobuf.pyext._message.MessageMapContainer): A
protobuf map of Firestore ``Value``-s.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Dict[str, Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]]: A dictionary
of native Python values converted from the ``value_fields``.
"""
return {
key: decode_value(value, client) for key, value in six.iteritems(value_fields)
}
|
[
"def",
"decode_dict",
"(",
"value_fields",
",",
"client",
")",
":",
"return",
"{",
"key",
":",
"decode_value",
"(",
"value",
",",
"client",
")",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"value_fields",
")",
"}"
] |
Converts a protobuf map of Firestore ``Value``-s.
Args:
value_fields (google.protobuf.pyext._message.MessageMapContainer): A
protobuf map of Firestore ``Value``-s.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Dict[str, Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]]: A dictionary
of native Python values converted from the ``value_fields``.
|
[
"Converts",
"a",
"protobuf",
"map",
"of",
"Firestore",
"Value",
"-",
"s",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L298-L314
|
train
|
googleapis/google-cloud-python
|
firestore/google/cloud/firestore_v1beta1/_helpers.py
|
get_doc_id
|
def get_doc_id(document_pb, expected_prefix):
"""Parse a document ID from a document protobuf.
Args:
document_pb (google.cloud.proto.firestore.v1beta1.\
document_pb2.Document): A protobuf for a document that
was created in a ``CreateDocument`` RPC.
expected_prefix (str): The expected collection prefix for the
fully-qualified document name.
Returns:
str: The document ID from the protobuf.
Raises:
ValueError: If the name does not begin with the prefix.
"""
prefix, document_id = document_pb.name.rsplit(DOCUMENT_PATH_DELIMITER, 1)
if prefix != expected_prefix:
raise ValueError(
"Unexpected document name",
document_pb.name,
"Expected to begin with",
expected_prefix,
)
return document_id
|
python
|
def get_doc_id(document_pb, expected_prefix):
"""Parse a document ID from a document protobuf.
Args:
document_pb (google.cloud.proto.firestore.v1beta1.\
document_pb2.Document): A protobuf for a document that
was created in a ``CreateDocument`` RPC.
expected_prefix (str): The expected collection prefix for the
fully-qualified document name.
Returns:
str: The document ID from the protobuf.
Raises:
ValueError: If the name does not begin with the prefix.
"""
prefix, document_id = document_pb.name.rsplit(DOCUMENT_PATH_DELIMITER, 1)
if prefix != expected_prefix:
raise ValueError(
"Unexpected document name",
document_pb.name,
"Expected to begin with",
expected_prefix,
)
return document_id
|
[
"def",
"get_doc_id",
"(",
"document_pb",
",",
"expected_prefix",
")",
":",
"prefix",
",",
"document_id",
"=",
"document_pb",
".",
"name",
".",
"rsplit",
"(",
"DOCUMENT_PATH_DELIMITER",
",",
"1",
")",
"if",
"prefix",
"!=",
"expected_prefix",
":",
"raise",
"ValueError",
"(",
"\"Unexpected document name\"",
",",
"document_pb",
".",
"name",
",",
"\"Expected to begin with\"",
",",
"expected_prefix",
",",
")",
"return",
"document_id"
] |
Parse a document ID from a document protobuf.
Args:
document_pb (google.cloud.proto.firestore.v1beta1.\
document_pb2.Document): A protobuf for a document that
was created in a ``CreateDocument`` RPC.
expected_prefix (str): The expected collection prefix for the
fully-qualified document name.
Returns:
str: The document ID from the protobuf.
Raises:
ValueError: If the name does not begin with the prefix.
|
[
"Parse",
"a",
"document",
"ID",
"from",
"a",
"document",
"protobuf",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L317-L342
|
train
|
googleapis/google-cloud-python
|
firestore/google/cloud/firestore_v1beta1/_helpers.py
|
extract_fields
|
def extract_fields(document_data, prefix_path, expand_dots=False):
"""Do depth-first walk of tree, yielding field_path, value"""
if not document_data:
yield prefix_path, _EmptyDict
else:
for key, value in sorted(six.iteritems(document_data)):
if expand_dots:
sub_key = FieldPath.from_string(key)
else:
sub_key = FieldPath(key)
field_path = FieldPath(*(prefix_path.parts + sub_key.parts))
if isinstance(value, dict):
for s_path, s_value in extract_fields(value, field_path):
yield s_path, s_value
else:
yield field_path, value
|
python
|
def extract_fields(document_data, prefix_path, expand_dots=False):
"""Do depth-first walk of tree, yielding field_path, value"""
if not document_data:
yield prefix_path, _EmptyDict
else:
for key, value in sorted(six.iteritems(document_data)):
if expand_dots:
sub_key = FieldPath.from_string(key)
else:
sub_key = FieldPath(key)
field_path = FieldPath(*(prefix_path.parts + sub_key.parts))
if isinstance(value, dict):
for s_path, s_value in extract_fields(value, field_path):
yield s_path, s_value
else:
yield field_path, value
|
[
"def",
"extract_fields",
"(",
"document_data",
",",
"prefix_path",
",",
"expand_dots",
"=",
"False",
")",
":",
"if",
"not",
"document_data",
":",
"yield",
"prefix_path",
",",
"_EmptyDict",
"else",
":",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"six",
".",
"iteritems",
"(",
"document_data",
")",
")",
":",
"if",
"expand_dots",
":",
"sub_key",
"=",
"FieldPath",
".",
"from_string",
"(",
"key",
")",
"else",
":",
"sub_key",
"=",
"FieldPath",
"(",
"key",
")",
"field_path",
"=",
"FieldPath",
"(",
"*",
"(",
"prefix_path",
".",
"parts",
"+",
"sub_key",
".",
"parts",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"for",
"s_path",
",",
"s_value",
"in",
"extract_fields",
"(",
"value",
",",
"field_path",
")",
":",
"yield",
"s_path",
",",
"s_value",
"else",
":",
"yield",
"field_path",
",",
"value"
] |
Do depth-first walk of tree, yielding field_path, value
|
[
"Do",
"depth",
"-",
"first",
"walk",
"of",
"tree",
"yielding",
"field_path",
"value"
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L348-L366
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.