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
|
datastore/google/cloud/datastore/_http.py
|
HTTPDatastoreAPI.begin_transaction
|
def begin_transaction(self, project_id, transaction_options=None):
"""Perform a ``beginTransaction`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type transaction_options: ~.datastore_v1.types.TransactionOptions
:param transaction_options: (Optional) Options for a new transaction.
:rtype: :class:`.datastore_pb2.BeginTransactionResponse`
:returns: The returned protobuf response object.
"""
request_pb = _datastore_pb2.BeginTransactionRequest()
return _rpc(
self.client._http,
project_id,
"beginTransaction",
self.client._base_url,
request_pb,
_datastore_pb2.BeginTransactionResponse,
)
|
python
|
def begin_transaction(self, project_id, transaction_options=None):
"""Perform a ``beginTransaction`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type transaction_options: ~.datastore_v1.types.TransactionOptions
:param transaction_options: (Optional) Options for a new transaction.
:rtype: :class:`.datastore_pb2.BeginTransactionResponse`
:returns: The returned protobuf response object.
"""
request_pb = _datastore_pb2.BeginTransactionRequest()
return _rpc(
self.client._http,
project_id,
"beginTransaction",
self.client._base_url,
request_pb,
_datastore_pb2.BeginTransactionResponse,
)
|
[
"def",
"begin_transaction",
"(",
"self",
",",
"project_id",
",",
"transaction_options",
"=",
"None",
")",
":",
"request_pb",
"=",
"_datastore_pb2",
".",
"BeginTransactionRequest",
"(",
")",
"return",
"_rpc",
"(",
"self",
".",
"client",
".",
"_http",
",",
"project_id",
",",
"\"beginTransaction\"",
",",
"self",
".",
"client",
".",
"_base_url",
",",
"request_pb",
",",
"_datastore_pb2",
".",
"BeginTransactionResponse",
",",
")"
] |
Perform a ``beginTransaction`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type transaction_options: ~.datastore_v1.types.TransactionOptions
:param transaction_options: (Optional) Options for a new transaction.
:rtype: :class:`.datastore_pb2.BeginTransactionResponse`
:returns: The returned protobuf response object.
|
[
"Perform",
"a",
"beginTransaction",
"request",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/_http.py#L224-L245
|
train
|
googleapis/google-cloud-python
|
datastore/google/cloud/datastore/_http.py
|
HTTPDatastoreAPI.commit
|
def commit(self, project_id, mode, mutations, transaction=None):
"""Perform a ``commit`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type mode: :class:`.gapic.datastore.v1.enums.CommitRequest.Mode`
:param mode: The type of commit to perform. Expected to be one of
``TRANSACTIONAL`` or ``NON_TRANSACTIONAL``.
:type mutations: list
:param mutations: List of :class:`.datastore_pb2.Mutation`, the
mutations to perform.
:type transaction: bytes
:param transaction: (Optional) The transaction ID returned from
:meth:`begin_transaction`. Non-transactional
commits must pass :data:`None`.
:rtype: :class:`.datastore_pb2.CommitResponse`
:returns: The returned protobuf response object.
"""
request_pb = _datastore_pb2.CommitRequest(
project_id=project_id,
mode=mode,
transaction=transaction,
mutations=mutations,
)
return _rpc(
self.client._http,
project_id,
"commit",
self.client._base_url,
request_pb,
_datastore_pb2.CommitResponse,
)
|
python
|
def commit(self, project_id, mode, mutations, transaction=None):
"""Perform a ``commit`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type mode: :class:`.gapic.datastore.v1.enums.CommitRequest.Mode`
:param mode: The type of commit to perform. Expected to be one of
``TRANSACTIONAL`` or ``NON_TRANSACTIONAL``.
:type mutations: list
:param mutations: List of :class:`.datastore_pb2.Mutation`, the
mutations to perform.
:type transaction: bytes
:param transaction: (Optional) The transaction ID returned from
:meth:`begin_transaction`. Non-transactional
commits must pass :data:`None`.
:rtype: :class:`.datastore_pb2.CommitResponse`
:returns: The returned protobuf response object.
"""
request_pb = _datastore_pb2.CommitRequest(
project_id=project_id,
mode=mode,
transaction=transaction,
mutations=mutations,
)
return _rpc(
self.client._http,
project_id,
"commit",
self.client._base_url,
request_pb,
_datastore_pb2.CommitResponse,
)
|
[
"def",
"commit",
"(",
"self",
",",
"project_id",
",",
"mode",
",",
"mutations",
",",
"transaction",
"=",
"None",
")",
":",
"request_pb",
"=",
"_datastore_pb2",
".",
"CommitRequest",
"(",
"project_id",
"=",
"project_id",
",",
"mode",
"=",
"mode",
",",
"transaction",
"=",
"transaction",
",",
"mutations",
"=",
"mutations",
",",
")",
"return",
"_rpc",
"(",
"self",
".",
"client",
".",
"_http",
",",
"project_id",
",",
"\"commit\"",
",",
"self",
".",
"client",
".",
"_base_url",
",",
"request_pb",
",",
"_datastore_pb2",
".",
"CommitResponse",
",",
")"
] |
Perform a ``commit`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type mode: :class:`.gapic.datastore.v1.enums.CommitRequest.Mode`
:param mode: The type of commit to perform. Expected to be one of
``TRANSACTIONAL`` or ``NON_TRANSACTIONAL``.
:type mutations: list
:param mutations: List of :class:`.datastore_pb2.Mutation`, the
mutations to perform.
:type transaction: bytes
:param transaction: (Optional) The transaction ID returned from
:meth:`begin_transaction`. Non-transactional
commits must pass :data:`None`.
:rtype: :class:`.datastore_pb2.CommitResponse`
:returns: The returned protobuf response object.
|
[
"Perform",
"a",
"commit",
"request",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/_http.py#L247-L283
|
train
|
googleapis/google-cloud-python
|
datastore/google/cloud/datastore/_http.py
|
HTTPDatastoreAPI.rollback
|
def rollback(self, project_id, transaction):
"""Perform a ``rollback`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type transaction: bytes
:param transaction: The transaction ID to rollback.
:rtype: :class:`.datastore_pb2.RollbackResponse`
:returns: The returned protobuf response object.
"""
request_pb = _datastore_pb2.RollbackRequest(
project_id=project_id, transaction=transaction
)
# Response is empty (i.e. no fields) but we return it anyway.
return _rpc(
self.client._http,
project_id,
"rollback",
self.client._base_url,
request_pb,
_datastore_pb2.RollbackResponse,
)
|
python
|
def rollback(self, project_id, transaction):
"""Perform a ``rollback`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type transaction: bytes
:param transaction: The transaction ID to rollback.
:rtype: :class:`.datastore_pb2.RollbackResponse`
:returns: The returned protobuf response object.
"""
request_pb = _datastore_pb2.RollbackRequest(
project_id=project_id, transaction=transaction
)
# Response is empty (i.e. no fields) but we return it anyway.
return _rpc(
self.client._http,
project_id,
"rollback",
self.client._base_url,
request_pb,
_datastore_pb2.RollbackResponse,
)
|
[
"def",
"rollback",
"(",
"self",
",",
"project_id",
",",
"transaction",
")",
":",
"request_pb",
"=",
"_datastore_pb2",
".",
"RollbackRequest",
"(",
"project_id",
"=",
"project_id",
",",
"transaction",
"=",
"transaction",
")",
"# Response is empty (i.e. no fields) but we return it anyway.",
"return",
"_rpc",
"(",
"self",
".",
"client",
".",
"_http",
",",
"project_id",
",",
"\"rollback\"",
",",
"self",
".",
"client",
".",
"_base_url",
",",
"request_pb",
",",
"_datastore_pb2",
".",
"RollbackResponse",
",",
")"
] |
Perform a ``rollback`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type transaction: bytes
:param transaction: The transaction ID to rollback.
:rtype: :class:`.datastore_pb2.RollbackResponse`
:returns: The returned protobuf response object.
|
[
"Perform",
"a",
"rollback",
"request",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/_http.py#L285-L309
|
train
|
googleapis/google-cloud-python
|
datastore/google/cloud/datastore/_http.py
|
HTTPDatastoreAPI.allocate_ids
|
def allocate_ids(self, project_id, keys):
"""Perform an ``allocateIds`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type keys: List[.entity_pb2.Key]
:param keys: The keys for which the backend should allocate IDs.
:rtype: :class:`.datastore_pb2.AllocateIdsResponse`
:returns: The returned protobuf response object.
"""
request_pb = _datastore_pb2.AllocateIdsRequest(keys=keys)
return _rpc(
self.client._http,
project_id,
"allocateIds",
self.client._base_url,
request_pb,
_datastore_pb2.AllocateIdsResponse,
)
|
python
|
def allocate_ids(self, project_id, keys):
"""Perform an ``allocateIds`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type keys: List[.entity_pb2.Key]
:param keys: The keys for which the backend should allocate IDs.
:rtype: :class:`.datastore_pb2.AllocateIdsResponse`
:returns: The returned protobuf response object.
"""
request_pb = _datastore_pb2.AllocateIdsRequest(keys=keys)
return _rpc(
self.client._http,
project_id,
"allocateIds",
self.client._base_url,
request_pb,
_datastore_pb2.AllocateIdsResponse,
)
|
[
"def",
"allocate_ids",
"(",
"self",
",",
"project_id",
",",
"keys",
")",
":",
"request_pb",
"=",
"_datastore_pb2",
".",
"AllocateIdsRequest",
"(",
"keys",
"=",
"keys",
")",
"return",
"_rpc",
"(",
"self",
".",
"client",
".",
"_http",
",",
"project_id",
",",
"\"allocateIds\"",
",",
"self",
".",
"client",
".",
"_base_url",
",",
"request_pb",
",",
"_datastore_pb2",
".",
"AllocateIdsResponse",
",",
")"
] |
Perform an ``allocateIds`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type keys: List[.entity_pb2.Key]
:param keys: The keys for which the backend should allocate IDs.
:rtype: :class:`.datastore_pb2.AllocateIdsResponse`
:returns: The returned protobuf response object.
|
[
"Perform",
"an",
"allocateIds",
"request",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/_http.py#L311-L332
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
_create_row_request
|
def _create_row_request(
table_name,
start_key=None,
end_key=None,
filter_=None,
limit=None,
end_inclusive=False,
app_profile_id=None,
row_set=None,
):
"""Creates a request to read rows in a table.
:type table_name: str
:param table_name: The name of the table to read from.
:type start_key: bytes
:param start_key: (Optional) The beginning of a range of row keys to
read from. The range will include ``start_key``. If
left empty, will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) The end of a range of row keys to read from.
The range will not include ``end_key``. If left empty,
will be interpreted as an infinite string.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
specified row(s). If unset, reads the entire table.
:type limit: int
:param limit: (Optional) The read will terminate after committing to N
rows' worth of results. The default (zero) is to return
all results.
:type end_inclusive: bool
:param end_inclusive: (Optional) Whether the ``end_key`` should be
considered inclusive. The default is False (exclusive).
:type: app_profile_id: str
:param app_profile_id: (Optional) The unique name of the AppProfile.
:type row_set: :class:`row_set.RowSet`
:param row_set: (Optional) The row set containing multiple row keys and
row_ranges.
:rtype: :class:`data_messages_v2_pb2.ReadRowsRequest`
:returns: The ``ReadRowsRequest`` protobuf corresponding to the inputs.
:raises: :class:`ValueError <exceptions.ValueError>` if both
``row_set`` and one of ``start_key`` or ``end_key`` are set
"""
request_kwargs = {"table_name": table_name}
if (start_key is not None or end_key is not None) and row_set is not None:
raise ValueError("Row range and row set cannot be " "set simultaneously")
if filter_ is not None:
request_kwargs["filter"] = filter_.to_pb()
if limit is not None:
request_kwargs["rows_limit"] = limit
if app_profile_id is not None:
request_kwargs["app_profile_id"] = app_profile_id
message = data_messages_v2_pb2.ReadRowsRequest(**request_kwargs)
if start_key is not None or end_key is not None:
row_set = RowSet()
row_set.add_row_range(RowRange(start_key, end_key, end_inclusive=end_inclusive))
if row_set is not None:
row_set._update_message_request(message)
return message
|
python
|
def _create_row_request(
table_name,
start_key=None,
end_key=None,
filter_=None,
limit=None,
end_inclusive=False,
app_profile_id=None,
row_set=None,
):
"""Creates a request to read rows in a table.
:type table_name: str
:param table_name: The name of the table to read from.
:type start_key: bytes
:param start_key: (Optional) The beginning of a range of row keys to
read from. The range will include ``start_key``. If
left empty, will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) The end of a range of row keys to read from.
The range will not include ``end_key``. If left empty,
will be interpreted as an infinite string.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
specified row(s). If unset, reads the entire table.
:type limit: int
:param limit: (Optional) The read will terminate after committing to N
rows' worth of results. The default (zero) is to return
all results.
:type end_inclusive: bool
:param end_inclusive: (Optional) Whether the ``end_key`` should be
considered inclusive. The default is False (exclusive).
:type: app_profile_id: str
:param app_profile_id: (Optional) The unique name of the AppProfile.
:type row_set: :class:`row_set.RowSet`
:param row_set: (Optional) The row set containing multiple row keys and
row_ranges.
:rtype: :class:`data_messages_v2_pb2.ReadRowsRequest`
:returns: The ``ReadRowsRequest`` protobuf corresponding to the inputs.
:raises: :class:`ValueError <exceptions.ValueError>` if both
``row_set`` and one of ``start_key`` or ``end_key`` are set
"""
request_kwargs = {"table_name": table_name}
if (start_key is not None or end_key is not None) and row_set is not None:
raise ValueError("Row range and row set cannot be " "set simultaneously")
if filter_ is not None:
request_kwargs["filter"] = filter_.to_pb()
if limit is not None:
request_kwargs["rows_limit"] = limit
if app_profile_id is not None:
request_kwargs["app_profile_id"] = app_profile_id
message = data_messages_v2_pb2.ReadRowsRequest(**request_kwargs)
if start_key is not None or end_key is not None:
row_set = RowSet()
row_set.add_row_range(RowRange(start_key, end_key, end_inclusive=end_inclusive))
if row_set is not None:
row_set._update_message_request(message)
return message
|
[
"def",
"_create_row_request",
"(",
"table_name",
",",
"start_key",
"=",
"None",
",",
"end_key",
"=",
"None",
",",
"filter_",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"end_inclusive",
"=",
"False",
",",
"app_profile_id",
"=",
"None",
",",
"row_set",
"=",
"None",
",",
")",
":",
"request_kwargs",
"=",
"{",
"\"table_name\"",
":",
"table_name",
"}",
"if",
"(",
"start_key",
"is",
"not",
"None",
"or",
"end_key",
"is",
"not",
"None",
")",
"and",
"row_set",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Row range and row set cannot be \"",
"\"set simultaneously\"",
")",
"if",
"filter_",
"is",
"not",
"None",
":",
"request_kwargs",
"[",
"\"filter\"",
"]",
"=",
"filter_",
".",
"to_pb",
"(",
")",
"if",
"limit",
"is",
"not",
"None",
":",
"request_kwargs",
"[",
"\"rows_limit\"",
"]",
"=",
"limit",
"if",
"app_profile_id",
"is",
"not",
"None",
":",
"request_kwargs",
"[",
"\"app_profile_id\"",
"]",
"=",
"app_profile_id",
"message",
"=",
"data_messages_v2_pb2",
".",
"ReadRowsRequest",
"(",
"*",
"*",
"request_kwargs",
")",
"if",
"start_key",
"is",
"not",
"None",
"or",
"end_key",
"is",
"not",
"None",
":",
"row_set",
"=",
"RowSet",
"(",
")",
"row_set",
".",
"add_row_range",
"(",
"RowRange",
"(",
"start_key",
",",
"end_key",
",",
"end_inclusive",
"=",
"end_inclusive",
")",
")",
"if",
"row_set",
"is",
"not",
"None",
":",
"row_set",
".",
"_update_message_request",
"(",
"message",
")",
"return",
"message"
] |
Creates a request to read rows in a table.
:type table_name: str
:param table_name: The name of the table to read from.
:type start_key: bytes
:param start_key: (Optional) The beginning of a range of row keys to
read from. The range will include ``start_key``. If
left empty, will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) The end of a range of row keys to read from.
The range will not include ``end_key``. If left empty,
will be interpreted as an infinite string.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
specified row(s). If unset, reads the entire table.
:type limit: int
:param limit: (Optional) The read will terminate after committing to N
rows' worth of results. The default (zero) is to return
all results.
:type end_inclusive: bool
:param end_inclusive: (Optional) Whether the ``end_key`` should be
considered inclusive. The default is False (exclusive).
:type: app_profile_id: str
:param app_profile_id: (Optional) The unique name of the AppProfile.
:type row_set: :class:`row_set.RowSet`
:param row_set: (Optional) The row set containing multiple row keys and
row_ranges.
:rtype: :class:`data_messages_v2_pb2.ReadRowsRequest`
:returns: The ``ReadRowsRequest`` protobuf corresponding to the inputs.
:raises: :class:`ValueError <exceptions.ValueError>` if both
``row_set`` and one of ``start_key`` or ``end_key`` are set
|
[
"Creates",
"a",
"request",
"to",
"read",
"rows",
"in",
"a",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L862-L932
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
_mutate_rows_request
|
def _mutate_rows_request(table_name, rows, app_profile_id=None):
"""Creates a request to mutate rows in a table.
:type table_name: str
:param table_name: The name of the table to write to.
:type rows: list
:param rows: List or other iterable of :class:`.DirectRow` instances.
:type: app_profile_id: str
:param app_profile_id: (Optional) The unique name of the AppProfile.
:rtype: :class:`data_messages_v2_pb2.MutateRowsRequest`
:returns: The ``MutateRowsRequest`` protobuf corresponding to the inputs.
:raises: :exc:`~.table.TooManyMutationsError` if the number of mutations is
greater than 100,000
"""
request_pb = data_messages_v2_pb2.MutateRowsRequest(
table_name=table_name, app_profile_id=app_profile_id
)
mutations_count = 0
for row in rows:
_check_row_table_name(table_name, row)
_check_row_type(row)
mutations = row._get_mutations()
request_pb.entries.add(row_key=row.row_key, mutations=mutations)
mutations_count += len(mutations)
if mutations_count > _MAX_BULK_MUTATIONS:
raise TooManyMutationsError(
"Maximum number of mutations is %s" % (_MAX_BULK_MUTATIONS,)
)
return request_pb
|
python
|
def _mutate_rows_request(table_name, rows, app_profile_id=None):
"""Creates a request to mutate rows in a table.
:type table_name: str
:param table_name: The name of the table to write to.
:type rows: list
:param rows: List or other iterable of :class:`.DirectRow` instances.
:type: app_profile_id: str
:param app_profile_id: (Optional) The unique name of the AppProfile.
:rtype: :class:`data_messages_v2_pb2.MutateRowsRequest`
:returns: The ``MutateRowsRequest`` protobuf corresponding to the inputs.
:raises: :exc:`~.table.TooManyMutationsError` if the number of mutations is
greater than 100,000
"""
request_pb = data_messages_v2_pb2.MutateRowsRequest(
table_name=table_name, app_profile_id=app_profile_id
)
mutations_count = 0
for row in rows:
_check_row_table_name(table_name, row)
_check_row_type(row)
mutations = row._get_mutations()
request_pb.entries.add(row_key=row.row_key, mutations=mutations)
mutations_count += len(mutations)
if mutations_count > _MAX_BULK_MUTATIONS:
raise TooManyMutationsError(
"Maximum number of mutations is %s" % (_MAX_BULK_MUTATIONS,)
)
return request_pb
|
[
"def",
"_mutate_rows_request",
"(",
"table_name",
",",
"rows",
",",
"app_profile_id",
"=",
"None",
")",
":",
"request_pb",
"=",
"data_messages_v2_pb2",
".",
"MutateRowsRequest",
"(",
"table_name",
"=",
"table_name",
",",
"app_profile_id",
"=",
"app_profile_id",
")",
"mutations_count",
"=",
"0",
"for",
"row",
"in",
"rows",
":",
"_check_row_table_name",
"(",
"table_name",
",",
"row",
")",
"_check_row_type",
"(",
"row",
")",
"mutations",
"=",
"row",
".",
"_get_mutations",
"(",
")",
"request_pb",
".",
"entries",
".",
"add",
"(",
"row_key",
"=",
"row",
".",
"row_key",
",",
"mutations",
"=",
"mutations",
")",
"mutations_count",
"+=",
"len",
"(",
"mutations",
")",
"if",
"mutations_count",
">",
"_MAX_BULK_MUTATIONS",
":",
"raise",
"TooManyMutationsError",
"(",
"\"Maximum number of mutations is %s\"",
"%",
"(",
"_MAX_BULK_MUTATIONS",
",",
")",
")",
"return",
"request_pb"
] |
Creates a request to mutate rows in a table.
:type table_name: str
:param table_name: The name of the table to write to.
:type rows: list
:param rows: List or other iterable of :class:`.DirectRow` instances.
:type: app_profile_id: str
:param app_profile_id: (Optional) The unique name of the AppProfile.
:rtype: :class:`data_messages_v2_pb2.MutateRowsRequest`
:returns: The ``MutateRowsRequest`` protobuf corresponding to the inputs.
:raises: :exc:`~.table.TooManyMutationsError` if the number of mutations is
greater than 100,000
|
[
"Creates",
"a",
"request",
"to",
"mutate",
"rows",
"in",
"a",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L935-L966
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
_check_row_table_name
|
def _check_row_table_name(table_name, row):
"""Checks that a row belongs to a table.
:type table_name: str
:param table_name: The name of the table.
:type row: :class:`~google.cloud.bigtable.row.Row`
:param row: An instance of :class:`~google.cloud.bigtable.row.Row`
subclasses.
:raises: :exc:`~.table.TableMismatchError` if the row does not belong to
the table.
"""
if row.table is not None and row.table.name != table_name:
raise TableMismatchError(
"Row %s is a part of %s table. Current table: %s"
% (row.row_key, row.table.name, table_name)
)
|
python
|
def _check_row_table_name(table_name, row):
"""Checks that a row belongs to a table.
:type table_name: str
:param table_name: The name of the table.
:type row: :class:`~google.cloud.bigtable.row.Row`
:param row: An instance of :class:`~google.cloud.bigtable.row.Row`
subclasses.
:raises: :exc:`~.table.TableMismatchError` if the row does not belong to
the table.
"""
if row.table is not None and row.table.name != table_name:
raise TableMismatchError(
"Row %s is a part of %s table. Current table: %s"
% (row.row_key, row.table.name, table_name)
)
|
[
"def",
"_check_row_table_name",
"(",
"table_name",
",",
"row",
")",
":",
"if",
"row",
".",
"table",
"is",
"not",
"None",
"and",
"row",
".",
"table",
".",
"name",
"!=",
"table_name",
":",
"raise",
"TableMismatchError",
"(",
"\"Row %s is a part of %s table. Current table: %s\"",
"%",
"(",
"row",
".",
"row_key",
",",
"row",
".",
"table",
".",
"name",
",",
"table_name",
")",
")"
] |
Checks that a row belongs to a table.
:type table_name: str
:param table_name: The name of the table.
:type row: :class:`~google.cloud.bigtable.row.Row`
:param row: An instance of :class:`~google.cloud.bigtable.row.Row`
subclasses.
:raises: :exc:`~.table.TableMismatchError` if the row does not belong to
the table.
|
[
"Checks",
"that",
"a",
"row",
"belongs",
"to",
"a",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L969-L986
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.name
|
def name(self):
"""Table name used in requests.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_table_name]
:end-before: [END bigtable_table_name]
.. note::
This property will not change if ``table_id`` does not, but the
return value is not cached.
The table name is of the form
``"projects/../instances/../tables/{table_id}"``
:rtype: str
:returns: The table name.
"""
project = self._instance._client.project
instance_id = self._instance.instance_id
table_client = self._instance._client.table_data_client
return table_client.table_path(
project=project, instance=instance_id, table=self.table_id
)
|
python
|
def name(self):
"""Table name used in requests.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_table_name]
:end-before: [END bigtable_table_name]
.. note::
This property will not change if ``table_id`` does not, but the
return value is not cached.
The table name is of the form
``"projects/../instances/../tables/{table_id}"``
:rtype: str
:returns: The table name.
"""
project = self._instance._client.project
instance_id = self._instance.instance_id
table_client = self._instance._client.table_data_client
return table_client.table_path(
project=project, instance=instance_id, table=self.table_id
)
|
[
"def",
"name",
"(",
"self",
")",
":",
"project",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"project",
"instance_id",
"=",
"self",
".",
"_instance",
".",
"instance_id",
"table_client",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"table_data_client",
"return",
"table_client",
".",
"table_path",
"(",
"project",
"=",
"project",
",",
"instance",
"=",
"instance_id",
",",
"table",
"=",
"self",
".",
"table_id",
")"
] |
Table name used in requests.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_table_name]
:end-before: [END bigtable_table_name]
.. note::
This property will not change if ``table_id`` does not, but the
return value is not cached.
The table name is of the form
``"projects/../instances/../tables/{table_id}"``
:rtype: str
:returns: The table name.
|
[
"Table",
"name",
"used",
"in",
"requests",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L113-L139
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.row
|
def row(self, row_key, filter_=None, append=False):
"""Factory to create a row associated with this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_table_row]
:end-before: [END bigtable_table_row]
.. warning::
At most one of ``filter_`` and ``append`` can be used in a
:class:`~google.cloud.bigtable.row.Row`.
:type row_key: bytes
:param row_key: The key for the row being created.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) Filter to be used for conditional mutations.
See :class:`.ConditionalRow` for more details.
:type append: bool
:param append: (Optional) Flag to determine if the row should be used
for append mutations.
:rtype: :class:`~google.cloud.bigtable.row.Row`
:returns: A row owned by this table.
:raises: :class:`ValueError <exceptions.ValueError>` if both
``filter_`` and ``append`` are used.
"""
if append and filter_ is not None:
raise ValueError("At most one of filter_ and append can be set")
if append:
return AppendRow(row_key, self)
elif filter_ is not None:
return ConditionalRow(row_key, self, filter_=filter_)
else:
return DirectRow(row_key, self)
|
python
|
def row(self, row_key, filter_=None, append=False):
"""Factory to create a row associated with this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_table_row]
:end-before: [END bigtable_table_row]
.. warning::
At most one of ``filter_`` and ``append`` can be used in a
:class:`~google.cloud.bigtable.row.Row`.
:type row_key: bytes
:param row_key: The key for the row being created.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) Filter to be used for conditional mutations.
See :class:`.ConditionalRow` for more details.
:type append: bool
:param append: (Optional) Flag to determine if the row should be used
for append mutations.
:rtype: :class:`~google.cloud.bigtable.row.Row`
:returns: A row owned by this table.
:raises: :class:`ValueError <exceptions.ValueError>` if both
``filter_`` and ``append`` are used.
"""
if append and filter_ is not None:
raise ValueError("At most one of filter_ and append can be set")
if append:
return AppendRow(row_key, self)
elif filter_ is not None:
return ConditionalRow(row_key, self, filter_=filter_)
else:
return DirectRow(row_key, self)
|
[
"def",
"row",
"(",
"self",
",",
"row_key",
",",
"filter_",
"=",
"None",
",",
"append",
"=",
"False",
")",
":",
"if",
"append",
"and",
"filter_",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"At most one of filter_ and append can be set\"",
")",
"if",
"append",
":",
"return",
"AppendRow",
"(",
"row_key",
",",
"self",
")",
"elif",
"filter_",
"is",
"not",
"None",
":",
"return",
"ConditionalRow",
"(",
"row_key",
",",
"self",
",",
"filter_",
"=",
"filter_",
")",
"else",
":",
"return",
"DirectRow",
"(",
"row_key",
",",
"self",
")"
] |
Factory to create a row associated with this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_table_row]
:end-before: [END bigtable_table_row]
.. warning::
At most one of ``filter_`` and ``append`` can be used in a
:class:`~google.cloud.bigtable.row.Row`.
:type row_key: bytes
:param row_key: The key for the row being created.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) Filter to be used for conditional mutations.
See :class:`.ConditionalRow` for more details.
:type append: bool
:param append: (Optional) Flag to determine if the row should be used
for append mutations.
:rtype: :class:`~google.cloud.bigtable.row.Row`
:returns: A row owned by this table.
:raises: :class:`ValueError <exceptions.ValueError>` if both
``filter_`` and ``append`` are used.
|
[
"Factory",
"to",
"create",
"a",
"row",
"associated",
"with",
"this",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L163-L200
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.create
|
def create(self, initial_split_keys=[], column_families={}):
"""Creates this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_create_table]
:end-before: [END bigtable_create_table]
.. note::
A create request returns a
:class:`._generated.table_pb2.Table` but we don't use
this response.
:type initial_split_keys: list
:param initial_split_keys: (Optional) list of row keys in bytes that
will be used to initially split the table
into several tablets.
:type column_families: dict
:param column_failies: (Optional) A map columns to create. The key is
the column_id str and the value is a
:class:`GarbageCollectionRule`
"""
table_client = self._instance._client.table_admin_client
instance_name = self._instance.name
families = {
id: ColumnFamily(id, self, rule).to_pb()
for (id, rule) in column_families.items()
}
table = admin_messages_v2_pb2.Table(column_families=families)
split = table_admin_messages_v2_pb2.CreateTableRequest.Split
splits = [split(key=_to_bytes(key)) for key in initial_split_keys]
table_client.create_table(
parent=instance_name,
table_id=self.table_id,
table=table,
initial_splits=splits,
)
|
python
|
def create(self, initial_split_keys=[], column_families={}):
"""Creates this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_create_table]
:end-before: [END bigtable_create_table]
.. note::
A create request returns a
:class:`._generated.table_pb2.Table` but we don't use
this response.
:type initial_split_keys: list
:param initial_split_keys: (Optional) list of row keys in bytes that
will be used to initially split the table
into several tablets.
:type column_families: dict
:param column_failies: (Optional) A map columns to create. The key is
the column_id str and the value is a
:class:`GarbageCollectionRule`
"""
table_client = self._instance._client.table_admin_client
instance_name = self._instance.name
families = {
id: ColumnFamily(id, self, rule).to_pb()
for (id, rule) in column_families.items()
}
table = admin_messages_v2_pb2.Table(column_families=families)
split = table_admin_messages_v2_pb2.CreateTableRequest.Split
splits = [split(key=_to_bytes(key)) for key in initial_split_keys]
table_client.create_table(
parent=instance_name,
table_id=self.table_id,
table=table,
initial_splits=splits,
)
|
[
"def",
"create",
"(",
"self",
",",
"initial_split_keys",
"=",
"[",
"]",
",",
"column_families",
"=",
"{",
"}",
")",
":",
"table_client",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"table_admin_client",
"instance_name",
"=",
"self",
".",
"_instance",
".",
"name",
"families",
"=",
"{",
"id",
":",
"ColumnFamily",
"(",
"id",
",",
"self",
",",
"rule",
")",
".",
"to_pb",
"(",
")",
"for",
"(",
"id",
",",
"rule",
")",
"in",
"column_families",
".",
"items",
"(",
")",
"}",
"table",
"=",
"admin_messages_v2_pb2",
".",
"Table",
"(",
"column_families",
"=",
"families",
")",
"split",
"=",
"table_admin_messages_v2_pb2",
".",
"CreateTableRequest",
".",
"Split",
"splits",
"=",
"[",
"split",
"(",
"key",
"=",
"_to_bytes",
"(",
"key",
")",
")",
"for",
"key",
"in",
"initial_split_keys",
"]",
"table_client",
".",
"create_table",
"(",
"parent",
"=",
"instance_name",
",",
"table_id",
"=",
"self",
".",
"table_id",
",",
"table",
"=",
"table",
",",
"initial_splits",
"=",
"splits",
",",
")"
] |
Creates this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_create_table]
:end-before: [END bigtable_create_table]
.. note::
A create request returns a
:class:`._generated.table_pb2.Table` but we don't use
this response.
:type initial_split_keys: list
:param initial_split_keys: (Optional) list of row keys in bytes that
will be used to initially split the table
into several tablets.
:type column_families: dict
:param column_failies: (Optional) A map columns to create. The key is
the column_id str and the value is a
:class:`GarbageCollectionRule`
|
[
"Creates",
"this",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L210-L252
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.exists
|
def exists(self):
"""Check whether the table exists.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_check_table_exists]
:end-before: [END bigtable_check_table_exists]
:rtype: bool
:returns: True if the table exists, else False.
"""
table_client = self._instance._client.table_admin_client
try:
table_client.get_table(name=self.name, view=VIEW_NAME_ONLY)
return True
except NotFound:
return False
|
python
|
def exists(self):
"""Check whether the table exists.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_check_table_exists]
:end-before: [END bigtable_check_table_exists]
:rtype: bool
:returns: True if the table exists, else False.
"""
table_client = self._instance._client.table_admin_client
try:
table_client.get_table(name=self.name, view=VIEW_NAME_ONLY)
return True
except NotFound:
return False
|
[
"def",
"exists",
"(",
"self",
")",
":",
"table_client",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"table_admin_client",
"try",
":",
"table_client",
".",
"get_table",
"(",
"name",
"=",
"self",
".",
"name",
",",
"view",
"=",
"VIEW_NAME_ONLY",
")",
"return",
"True",
"except",
"NotFound",
":",
"return",
"False"
] |
Check whether the table exists.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_check_table_exists]
:end-before: [END bigtable_check_table_exists]
:rtype: bool
:returns: True if the table exists, else False.
|
[
"Check",
"whether",
"the",
"table",
"exists",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L254-L271
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.delete
|
def delete(self):
"""Delete this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_delete_table]
:end-before: [END bigtable_delete_table]
"""
table_client = self._instance._client.table_admin_client
table_client.delete_table(name=self.name)
|
python
|
def delete(self):
"""Delete this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_delete_table]
:end-before: [END bigtable_delete_table]
"""
table_client = self._instance._client.table_admin_client
table_client.delete_table(name=self.name)
|
[
"def",
"delete",
"(",
"self",
")",
":",
"table_client",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"table_admin_client",
"table_client",
".",
"delete_table",
"(",
"name",
"=",
"self",
".",
"name",
")"
] |
Delete this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_delete_table]
:end-before: [END bigtable_delete_table]
|
[
"Delete",
"this",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L273-L284
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.list_column_families
|
def list_column_families(self):
"""List the column families owned by this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_list_column_families]
:end-before: [END bigtable_list_column_families]
:rtype: dict
:returns: Dictionary of column families attached to this table. Keys
are strings (column family names) and values are
:class:`.ColumnFamily` instances.
:raises: :class:`ValueError <exceptions.ValueError>` if the column
family name from the response does not agree with the computed
name from the column family ID.
"""
table_client = self._instance._client.table_admin_client
table_pb = table_client.get_table(self.name)
result = {}
for column_family_id, value_pb in table_pb.column_families.items():
gc_rule = _gc_rule_from_pb(value_pb.gc_rule)
column_family = self.column_family(column_family_id, gc_rule=gc_rule)
result[column_family_id] = column_family
return result
|
python
|
def list_column_families(self):
"""List the column families owned by this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_list_column_families]
:end-before: [END bigtable_list_column_families]
:rtype: dict
:returns: Dictionary of column families attached to this table. Keys
are strings (column family names) and values are
:class:`.ColumnFamily` instances.
:raises: :class:`ValueError <exceptions.ValueError>` if the column
family name from the response does not agree with the computed
name from the column family ID.
"""
table_client = self._instance._client.table_admin_client
table_pb = table_client.get_table(self.name)
result = {}
for column_family_id, value_pb in table_pb.column_families.items():
gc_rule = _gc_rule_from_pb(value_pb.gc_rule)
column_family = self.column_family(column_family_id, gc_rule=gc_rule)
result[column_family_id] = column_family
return result
|
[
"def",
"list_column_families",
"(",
"self",
")",
":",
"table_client",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"table_admin_client",
"table_pb",
"=",
"table_client",
".",
"get_table",
"(",
"self",
".",
"name",
")",
"result",
"=",
"{",
"}",
"for",
"column_family_id",
",",
"value_pb",
"in",
"table_pb",
".",
"column_families",
".",
"items",
"(",
")",
":",
"gc_rule",
"=",
"_gc_rule_from_pb",
"(",
"value_pb",
".",
"gc_rule",
")",
"column_family",
"=",
"self",
".",
"column_family",
"(",
"column_family_id",
",",
"gc_rule",
"=",
"gc_rule",
")",
"result",
"[",
"column_family_id",
"]",
"=",
"column_family",
"return",
"result"
] |
List the column families owned by this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_list_column_families]
:end-before: [END bigtable_list_column_families]
:rtype: dict
:returns: Dictionary of column families attached to this table. Keys
are strings (column family names) and values are
:class:`.ColumnFamily` instances.
:raises: :class:`ValueError <exceptions.ValueError>` if the column
family name from the response does not agree with the computed
name from the column family ID.
|
[
"List",
"the",
"column",
"families",
"owned",
"by",
"this",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L286-L311
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.get_cluster_states
|
def get_cluster_states(self):
"""List the cluster states owned by this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_get_cluster_states]
:end-before: [END bigtable_get_cluster_states]
:rtype: dict
:returns: Dictionary of cluster states for this table.
Keys are cluster ids and values are
:class: 'ClusterState' instances.
"""
REPLICATION_VIEW = enums.Table.View.REPLICATION_VIEW
table_client = self._instance._client.table_admin_client
table_pb = table_client.get_table(self.name, view=REPLICATION_VIEW)
return {
cluster_id: ClusterState(value_pb.replication_state)
for cluster_id, value_pb in table_pb.cluster_states.items()
}
|
python
|
def get_cluster_states(self):
"""List the cluster states owned by this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_get_cluster_states]
:end-before: [END bigtable_get_cluster_states]
:rtype: dict
:returns: Dictionary of cluster states for this table.
Keys are cluster ids and values are
:class: 'ClusterState' instances.
"""
REPLICATION_VIEW = enums.Table.View.REPLICATION_VIEW
table_client = self._instance._client.table_admin_client
table_pb = table_client.get_table(self.name, view=REPLICATION_VIEW)
return {
cluster_id: ClusterState(value_pb.replication_state)
for cluster_id, value_pb in table_pb.cluster_states.items()
}
|
[
"def",
"get_cluster_states",
"(",
"self",
")",
":",
"REPLICATION_VIEW",
"=",
"enums",
".",
"Table",
".",
"View",
".",
"REPLICATION_VIEW",
"table_client",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"table_admin_client",
"table_pb",
"=",
"table_client",
".",
"get_table",
"(",
"self",
".",
"name",
",",
"view",
"=",
"REPLICATION_VIEW",
")",
"return",
"{",
"cluster_id",
":",
"ClusterState",
"(",
"value_pb",
".",
"replication_state",
")",
"for",
"cluster_id",
",",
"value_pb",
"in",
"table_pb",
".",
"cluster_states",
".",
"items",
"(",
")",
"}"
] |
List the cluster states owned by this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_get_cluster_states]
:end-before: [END bigtable_get_cluster_states]
:rtype: dict
:returns: Dictionary of cluster states for this table.
Keys are cluster ids and values are
:class: 'ClusterState' instances.
|
[
"List",
"the",
"cluster",
"states",
"owned",
"by",
"this",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L313-L335
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.read_row
|
def read_row(self, row_key, filter_=None):
"""Read a single row from this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_read_row]
:end-before: [END bigtable_read_row]
:type row_key: bytes
:param row_key: The key of the row to read from.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
row. If unset, returns the entire row.
:rtype: :class:`.PartialRowData`, :data:`NoneType <types.NoneType>`
:returns: The contents of the row if any chunks were returned in
the response, otherwise :data:`None`.
:raises: :class:`ValueError <exceptions.ValueError>` if a commit row
chunk is never encountered.
"""
row_set = RowSet()
row_set.add_row_key(row_key)
result_iter = iter(self.read_rows(filter_=filter_, row_set=row_set))
row = next(result_iter, None)
if next(result_iter, None) is not None:
raise ValueError("More than one row was returned.")
return row
|
python
|
def read_row(self, row_key, filter_=None):
"""Read a single row from this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_read_row]
:end-before: [END bigtable_read_row]
:type row_key: bytes
:param row_key: The key of the row to read from.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
row. If unset, returns the entire row.
:rtype: :class:`.PartialRowData`, :data:`NoneType <types.NoneType>`
:returns: The contents of the row if any chunks were returned in
the response, otherwise :data:`None`.
:raises: :class:`ValueError <exceptions.ValueError>` if a commit row
chunk is never encountered.
"""
row_set = RowSet()
row_set.add_row_key(row_key)
result_iter = iter(self.read_rows(filter_=filter_, row_set=row_set))
row = next(result_iter, None)
if next(result_iter, None) is not None:
raise ValueError("More than one row was returned.")
return row
|
[
"def",
"read_row",
"(",
"self",
",",
"row_key",
",",
"filter_",
"=",
"None",
")",
":",
"row_set",
"=",
"RowSet",
"(",
")",
"row_set",
".",
"add_row_key",
"(",
"row_key",
")",
"result_iter",
"=",
"iter",
"(",
"self",
".",
"read_rows",
"(",
"filter_",
"=",
"filter_",
",",
"row_set",
"=",
"row_set",
")",
")",
"row",
"=",
"next",
"(",
"result_iter",
",",
"None",
")",
"if",
"next",
"(",
"result_iter",
",",
"None",
")",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"More than one row was returned.\"",
")",
"return",
"row"
] |
Read a single row from this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_read_row]
:end-before: [END bigtable_read_row]
:type row_key: bytes
:param row_key: The key of the row to read from.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
row. If unset, returns the entire row.
:rtype: :class:`.PartialRowData`, :data:`NoneType <types.NoneType>`
:returns: The contents of the row if any chunks were returned in
the response, otherwise :data:`None`.
:raises: :class:`ValueError <exceptions.ValueError>` if a commit row
chunk is never encountered.
|
[
"Read",
"a",
"single",
"row",
"from",
"this",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L337-L365
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.read_rows
|
def read_rows(
self,
start_key=None,
end_key=None,
limit=None,
filter_=None,
end_inclusive=False,
row_set=None,
retry=DEFAULT_RETRY_READ_ROWS,
):
"""Read rows from this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_read_rows]
:end-before: [END bigtable_read_rows]
:type start_key: bytes
:param start_key: (Optional) The beginning of a range of row keys to
read from. The range will include ``start_key``. If
left empty, will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) The end of a range of row keys to read from.
The range will not include ``end_key``. If left empty,
will be interpreted as an infinite string.
:type limit: int
:param limit: (Optional) The read will terminate after committing to N
rows' worth of results. The default (zero) is to return
all results.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
specified row(s). If unset, reads every column in
each row.
:type end_inclusive: bool
:param end_inclusive: (Optional) Whether the ``end_key`` should be
considered inclusive. The default is False (exclusive).
:type row_set: :class:`row_set.RowSet`
:param row_set: (Optional) The row set containing multiple row keys and
row_ranges.
:type retry: :class:`~google.api_core.retry.Retry`
:param retry:
(Optional) Retry delay and deadline arguments. To override, the
default value :attr:`DEFAULT_RETRY_READ_ROWS` can be used and
modified with the :meth:`~google.api_core.retry.Retry.with_delay`
method or the :meth:`~google.api_core.retry.Retry.with_deadline`
method.
:rtype: :class:`.PartialRowsData`
:returns: A :class:`.PartialRowsData` a generator for consuming
the streamed results.
"""
request_pb = _create_row_request(
self.name,
start_key=start_key,
end_key=end_key,
filter_=filter_,
limit=limit,
end_inclusive=end_inclusive,
app_profile_id=self._app_profile_id,
row_set=row_set,
)
data_client = self._instance._client.table_data_client
return PartialRowsData(data_client.transport.read_rows, request_pb, retry)
|
python
|
def read_rows(
self,
start_key=None,
end_key=None,
limit=None,
filter_=None,
end_inclusive=False,
row_set=None,
retry=DEFAULT_RETRY_READ_ROWS,
):
"""Read rows from this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_read_rows]
:end-before: [END bigtable_read_rows]
:type start_key: bytes
:param start_key: (Optional) The beginning of a range of row keys to
read from. The range will include ``start_key``. If
left empty, will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) The end of a range of row keys to read from.
The range will not include ``end_key``. If left empty,
will be interpreted as an infinite string.
:type limit: int
:param limit: (Optional) The read will terminate after committing to N
rows' worth of results. The default (zero) is to return
all results.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
specified row(s). If unset, reads every column in
each row.
:type end_inclusive: bool
:param end_inclusive: (Optional) Whether the ``end_key`` should be
considered inclusive. The default is False (exclusive).
:type row_set: :class:`row_set.RowSet`
:param row_set: (Optional) The row set containing multiple row keys and
row_ranges.
:type retry: :class:`~google.api_core.retry.Retry`
:param retry:
(Optional) Retry delay and deadline arguments. To override, the
default value :attr:`DEFAULT_RETRY_READ_ROWS` can be used and
modified with the :meth:`~google.api_core.retry.Retry.with_delay`
method or the :meth:`~google.api_core.retry.Retry.with_deadline`
method.
:rtype: :class:`.PartialRowsData`
:returns: A :class:`.PartialRowsData` a generator for consuming
the streamed results.
"""
request_pb = _create_row_request(
self.name,
start_key=start_key,
end_key=end_key,
filter_=filter_,
limit=limit,
end_inclusive=end_inclusive,
app_profile_id=self._app_profile_id,
row_set=row_set,
)
data_client = self._instance._client.table_data_client
return PartialRowsData(data_client.transport.read_rows, request_pb, retry)
|
[
"def",
"read_rows",
"(",
"self",
",",
"start_key",
"=",
"None",
",",
"end_key",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"filter_",
"=",
"None",
",",
"end_inclusive",
"=",
"False",
",",
"row_set",
"=",
"None",
",",
"retry",
"=",
"DEFAULT_RETRY_READ_ROWS",
",",
")",
":",
"request_pb",
"=",
"_create_row_request",
"(",
"self",
".",
"name",
",",
"start_key",
"=",
"start_key",
",",
"end_key",
"=",
"end_key",
",",
"filter_",
"=",
"filter_",
",",
"limit",
"=",
"limit",
",",
"end_inclusive",
"=",
"end_inclusive",
",",
"app_profile_id",
"=",
"self",
".",
"_app_profile_id",
",",
"row_set",
"=",
"row_set",
",",
")",
"data_client",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"table_data_client",
"return",
"PartialRowsData",
"(",
"data_client",
".",
"transport",
".",
"read_rows",
",",
"request_pb",
",",
"retry",
")"
] |
Read rows from this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_read_rows]
:end-before: [END bigtable_read_rows]
:type start_key: bytes
:param start_key: (Optional) The beginning of a range of row keys to
read from. The range will include ``start_key``. If
left empty, will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) The end of a range of row keys to read from.
The range will not include ``end_key``. If left empty,
will be interpreted as an infinite string.
:type limit: int
:param limit: (Optional) The read will terminate after committing to N
rows' worth of results. The default (zero) is to return
all results.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
specified row(s). If unset, reads every column in
each row.
:type end_inclusive: bool
:param end_inclusive: (Optional) Whether the ``end_key`` should be
considered inclusive. The default is False (exclusive).
:type row_set: :class:`row_set.RowSet`
:param row_set: (Optional) The row set containing multiple row keys and
row_ranges.
:type retry: :class:`~google.api_core.retry.Retry`
:param retry:
(Optional) Retry delay and deadline arguments. To override, the
default value :attr:`DEFAULT_RETRY_READ_ROWS` can be used and
modified with the :meth:`~google.api_core.retry.Retry.with_delay`
method or the :meth:`~google.api_core.retry.Retry.with_deadline`
method.
:rtype: :class:`.PartialRowsData`
:returns: A :class:`.PartialRowsData` a generator for consuming
the streamed results.
|
[
"Read",
"rows",
"from",
"this",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L367-L436
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.yield_rows
|
def yield_rows(self, **kwargs):
"""Read rows from this table.
.. warning::
This method will be removed in future releases. Please use
``read_rows`` instead.
:type start_key: bytes
:param start_key: (Optional) The beginning of a range of row keys to
read from. The range will include ``start_key``. If
left empty, will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) The end of a range of row keys to read from.
The range will not include ``end_key``. If left empty,
will be interpreted as an infinite string.
:type limit: int
:param limit: (Optional) The read will terminate after committing to N
rows' worth of results. The default (zero) is to return
all results.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
specified row(s). If unset, reads every column in
each row.
:type row_set: :class:`row_set.RowSet`
:param row_set: (Optional) The row set containing multiple row keys and
row_ranges.
:rtype: :class:`.PartialRowData`
:returns: A :class:`.PartialRowData` for each row returned
"""
warnings.warn(
"`yield_rows()` is depricated; use `red_rows()` instead",
DeprecationWarning,
stacklevel=2,
)
return self.read_rows(**kwargs)
|
python
|
def yield_rows(self, **kwargs):
"""Read rows from this table.
.. warning::
This method will be removed in future releases. Please use
``read_rows`` instead.
:type start_key: bytes
:param start_key: (Optional) The beginning of a range of row keys to
read from. The range will include ``start_key``. If
left empty, will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) The end of a range of row keys to read from.
The range will not include ``end_key``. If left empty,
will be interpreted as an infinite string.
:type limit: int
:param limit: (Optional) The read will terminate after committing to N
rows' worth of results. The default (zero) is to return
all results.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
specified row(s). If unset, reads every column in
each row.
:type row_set: :class:`row_set.RowSet`
:param row_set: (Optional) The row set containing multiple row keys and
row_ranges.
:rtype: :class:`.PartialRowData`
:returns: A :class:`.PartialRowData` for each row returned
"""
warnings.warn(
"`yield_rows()` is depricated; use `red_rows()` instead",
DeprecationWarning,
stacklevel=2,
)
return self.read_rows(**kwargs)
|
[
"def",
"yield_rows",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`yield_rows()` is depricated; use `red_rows()` instead\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"return",
"self",
".",
"read_rows",
"(",
"*",
"*",
"kwargs",
")"
] |
Read rows from this table.
.. warning::
This method will be removed in future releases. Please use
``read_rows`` instead.
:type start_key: bytes
:param start_key: (Optional) The beginning of a range of row keys to
read from. The range will include ``start_key``. If
left empty, will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) The end of a range of row keys to read from.
The range will not include ``end_key``. If left empty,
will be interpreted as an infinite string.
:type limit: int
:param limit: (Optional) The read will terminate after committing to N
rows' worth of results. The default (zero) is to return
all results.
:type filter_: :class:`.RowFilter`
:param filter_: (Optional) The filter to apply to the contents of the
specified row(s). If unset, reads every column in
each row.
:type row_set: :class:`row_set.RowSet`
:param row_set: (Optional) The row set containing multiple row keys and
row_ranges.
:rtype: :class:`.PartialRowData`
:returns: A :class:`.PartialRowData` for each row returned
|
[
"Read",
"rows",
"from",
"this",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L438-L477
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.mutate_rows
|
def mutate_rows(self, rows, retry=DEFAULT_RETRY):
"""Mutates multiple rows in bulk.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_mutate_rows]
:end-before: [END bigtable_mutate_rows]
The method tries to update all specified rows.
If some of the rows weren't updated, it would not remove mutations.
They can be applied to the row separately.
If row mutations finished successfully, they would be cleaned up.
Optionally, a ``retry`` strategy can be specified to re-attempt
mutations on rows that return transient errors. This method will retry
until all rows succeed or until the request deadline is reached. To
specify a ``retry`` strategy of "do-nothing", a deadline of ``0.0``
can be specified.
:type rows: list
:param rows: List or other iterable of :class:`.DirectRow` instances.
:type retry: :class:`~google.api_core.retry.Retry`
:param retry:
(Optional) Retry delay and deadline arguments. To override, the
default value :attr:`DEFAULT_RETRY` can be used and modified with
the :meth:`~google.api_core.retry.Retry.with_delay` method or the
:meth:`~google.api_core.retry.Retry.with_deadline` method.
:rtype: list
:returns: A list of response statuses (`google.rpc.status_pb2.Status`)
corresponding to success or failure of each row mutation
sent. These will be in the same order as the `rows`.
"""
retryable_mutate_rows = _RetryableMutateRowsWorker(
self._instance._client,
self.name,
rows,
app_profile_id=self._app_profile_id,
timeout=self.mutation_timeout,
)
return retryable_mutate_rows(retry=retry)
|
python
|
def mutate_rows(self, rows, retry=DEFAULT_RETRY):
"""Mutates multiple rows in bulk.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_mutate_rows]
:end-before: [END bigtable_mutate_rows]
The method tries to update all specified rows.
If some of the rows weren't updated, it would not remove mutations.
They can be applied to the row separately.
If row mutations finished successfully, they would be cleaned up.
Optionally, a ``retry`` strategy can be specified to re-attempt
mutations on rows that return transient errors. This method will retry
until all rows succeed or until the request deadline is reached. To
specify a ``retry`` strategy of "do-nothing", a deadline of ``0.0``
can be specified.
:type rows: list
:param rows: List or other iterable of :class:`.DirectRow` instances.
:type retry: :class:`~google.api_core.retry.Retry`
:param retry:
(Optional) Retry delay and deadline arguments. To override, the
default value :attr:`DEFAULT_RETRY` can be used and modified with
the :meth:`~google.api_core.retry.Retry.with_delay` method or the
:meth:`~google.api_core.retry.Retry.with_deadline` method.
:rtype: list
:returns: A list of response statuses (`google.rpc.status_pb2.Status`)
corresponding to success or failure of each row mutation
sent. These will be in the same order as the `rows`.
"""
retryable_mutate_rows = _RetryableMutateRowsWorker(
self._instance._client,
self.name,
rows,
app_profile_id=self._app_profile_id,
timeout=self.mutation_timeout,
)
return retryable_mutate_rows(retry=retry)
|
[
"def",
"mutate_rows",
"(",
"self",
",",
"rows",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"retryable_mutate_rows",
"=",
"_RetryableMutateRowsWorker",
"(",
"self",
".",
"_instance",
".",
"_client",
",",
"self",
".",
"name",
",",
"rows",
",",
"app_profile_id",
"=",
"self",
".",
"_app_profile_id",
",",
"timeout",
"=",
"self",
".",
"mutation_timeout",
",",
")",
"return",
"retryable_mutate_rows",
"(",
"retry",
"=",
"retry",
")"
] |
Mutates multiple rows in bulk.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_mutate_rows]
:end-before: [END bigtable_mutate_rows]
The method tries to update all specified rows.
If some of the rows weren't updated, it would not remove mutations.
They can be applied to the row separately.
If row mutations finished successfully, they would be cleaned up.
Optionally, a ``retry`` strategy can be specified to re-attempt
mutations on rows that return transient errors. This method will retry
until all rows succeed or until the request deadline is reached. To
specify a ``retry`` strategy of "do-nothing", a deadline of ``0.0``
can be specified.
:type rows: list
:param rows: List or other iterable of :class:`.DirectRow` instances.
:type retry: :class:`~google.api_core.retry.Retry`
:param retry:
(Optional) Retry delay and deadline arguments. To override, the
default value :attr:`DEFAULT_RETRY` can be used and modified with
the :meth:`~google.api_core.retry.Retry.with_delay` method or the
:meth:`~google.api_core.retry.Retry.with_deadline` method.
:rtype: list
:returns: A list of response statuses (`google.rpc.status_pb2.Status`)
corresponding to success or failure of each row mutation
sent. These will be in the same order as the `rows`.
|
[
"Mutates",
"multiple",
"rows",
"in",
"bulk",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L479-L521
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.sample_row_keys
|
def sample_row_keys(self):
"""Read a sample of row keys in the table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_sample_row_keys]
:end-before: [END bigtable_sample_row_keys]
The returned row keys will delimit contiguous sections of the table of
approximately equal size, which can be used to break up the data for
distributed tasks like mapreduces.
The elements in the iterator are a SampleRowKeys response and they have
the properties ``offset_bytes`` and ``row_key``. They occur in sorted
order. The table might have contents before the first row key in the
list and after the last one, but a key containing the empty string
indicates "end of table" and will be the last response given, if
present.
.. note::
Row keys in this list may not have ever been written to or read
from, and users should therefore not make any assumptions about the
row key structure that are specific to their use case.
The ``offset_bytes`` field on a response indicates the approximate
total storage space used by all rows in the table which precede
``row_key``. Buffering the contents of all rows between two subsequent
samples would require space roughly equal to the difference in their
``offset_bytes`` fields.
:rtype: :class:`~google.cloud.exceptions.GrpcRendezvous`
:returns: A cancel-able iterator. Can be consumed by calling ``next()``
or by casting to a :class:`list` and can be cancelled by
calling ``cancel()``.
"""
data_client = self._instance._client.table_data_client
response_iterator = data_client.sample_row_keys(
self.name, app_profile_id=self._app_profile_id
)
return response_iterator
|
python
|
def sample_row_keys(self):
"""Read a sample of row keys in the table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_sample_row_keys]
:end-before: [END bigtable_sample_row_keys]
The returned row keys will delimit contiguous sections of the table of
approximately equal size, which can be used to break up the data for
distributed tasks like mapreduces.
The elements in the iterator are a SampleRowKeys response and they have
the properties ``offset_bytes`` and ``row_key``. They occur in sorted
order. The table might have contents before the first row key in the
list and after the last one, but a key containing the empty string
indicates "end of table" and will be the last response given, if
present.
.. note::
Row keys in this list may not have ever been written to or read
from, and users should therefore not make any assumptions about the
row key structure that are specific to their use case.
The ``offset_bytes`` field on a response indicates the approximate
total storage space used by all rows in the table which precede
``row_key``. Buffering the contents of all rows between two subsequent
samples would require space roughly equal to the difference in their
``offset_bytes`` fields.
:rtype: :class:`~google.cloud.exceptions.GrpcRendezvous`
:returns: A cancel-able iterator. Can be consumed by calling ``next()``
or by casting to a :class:`list` and can be cancelled by
calling ``cancel()``.
"""
data_client = self._instance._client.table_data_client
response_iterator = data_client.sample_row_keys(
self.name, app_profile_id=self._app_profile_id
)
return response_iterator
|
[
"def",
"sample_row_keys",
"(",
"self",
")",
":",
"data_client",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"table_data_client",
"response_iterator",
"=",
"data_client",
".",
"sample_row_keys",
"(",
"self",
".",
"name",
",",
"app_profile_id",
"=",
"self",
".",
"_app_profile_id",
")",
"return",
"response_iterator"
] |
Read a sample of row keys in the table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_sample_row_keys]
:end-before: [END bigtable_sample_row_keys]
The returned row keys will delimit contiguous sections of the table of
approximately equal size, which can be used to break up the data for
distributed tasks like mapreduces.
The elements in the iterator are a SampleRowKeys response and they have
the properties ``offset_bytes`` and ``row_key``. They occur in sorted
order. The table might have contents before the first row key in the
list and after the last one, but a key containing the empty string
indicates "end of table" and will be the last response given, if
present.
.. note::
Row keys in this list may not have ever been written to or read
from, and users should therefore not make any assumptions about the
row key structure that are specific to their use case.
The ``offset_bytes`` field on a response indicates the approximate
total storage space used by all rows in the table which precede
``row_key``. Buffering the contents of all rows between two subsequent
samples would require space roughly equal to the difference in their
``offset_bytes`` fields.
:rtype: :class:`~google.cloud.exceptions.GrpcRendezvous`
:returns: A cancel-able iterator. Can be consumed by calling ``next()``
or by casting to a :class:`list` and can be cancelled by
calling ``cancel()``.
|
[
"Read",
"a",
"sample",
"of",
"row",
"keys",
"in",
"the",
"table",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L523-L565
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.truncate
|
def truncate(self, timeout=None):
"""Truncate the table
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_truncate_table]
:end-before: [END bigtable_truncate_table]
:type timeout: float
:param timeout: (Optional) The amount of time, in seconds, to wait
for the request to complete.
:raise: google.api_core.exceptions.GoogleAPICallError: If the
request failed for any reason.
google.api_core.exceptions.RetryError: If the request failed
due to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
client = self._instance._client
table_admin_client = client.table_admin_client
if timeout:
table_admin_client.drop_row_range(
self.name, delete_all_data_from_table=True, timeout=timeout
)
else:
table_admin_client.drop_row_range(
self.name, delete_all_data_from_table=True
)
|
python
|
def truncate(self, timeout=None):
"""Truncate the table
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_truncate_table]
:end-before: [END bigtable_truncate_table]
:type timeout: float
:param timeout: (Optional) The amount of time, in seconds, to wait
for the request to complete.
:raise: google.api_core.exceptions.GoogleAPICallError: If the
request failed for any reason.
google.api_core.exceptions.RetryError: If the request failed
due to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
client = self._instance._client
table_admin_client = client.table_admin_client
if timeout:
table_admin_client.drop_row_range(
self.name, delete_all_data_from_table=True, timeout=timeout
)
else:
table_admin_client.drop_row_range(
self.name, delete_all_data_from_table=True
)
|
[
"def",
"truncate",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_instance",
".",
"_client",
"table_admin_client",
"=",
"client",
".",
"table_admin_client",
"if",
"timeout",
":",
"table_admin_client",
".",
"drop_row_range",
"(",
"self",
".",
"name",
",",
"delete_all_data_from_table",
"=",
"True",
",",
"timeout",
"=",
"timeout",
")",
"else",
":",
"table_admin_client",
".",
"drop_row_range",
"(",
"self",
".",
"name",
",",
"delete_all_data_from_table",
"=",
"True",
")"
] |
Truncate the table
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_truncate_table]
:end-before: [END bigtable_truncate_table]
:type timeout: float
:param timeout: (Optional) The amount of time, in seconds, to wait
for the request to complete.
:raise: google.api_core.exceptions.GoogleAPICallError: If the
request failed for any reason.
google.api_core.exceptions.RetryError: If the request failed
due to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
|
[
"Truncate",
"the",
"table"
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L567-L595
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
Table.mutations_batcher
|
def mutations_batcher(self, flush_count=FLUSH_COUNT, max_row_bytes=MAX_ROW_BYTES):
"""Factory to create a mutation batcher associated with this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_mutations_batcher]
:end-before: [END bigtable_mutations_batcher]
:type table: class
:param table: class:`~google.cloud.bigtable.table.Table`.
:type flush_count: int
:param flush_count: (Optional) Maximum number of rows per batch. If it
reaches the max number of rows it calls finish_batch() to
mutate the current row batch. Default is FLUSH_COUNT (1000
rows).
:type max_row_bytes: int
:param max_row_bytes: (Optional) Max number of row mutations size to
flush. If it reaches the max number of row mutations size it
calls finish_batch() to mutate the current row batch.
Default is MAX_ROW_BYTES (5 MB).
"""
return MutationsBatcher(self, flush_count, max_row_bytes)
|
python
|
def mutations_batcher(self, flush_count=FLUSH_COUNT, max_row_bytes=MAX_ROW_BYTES):
"""Factory to create a mutation batcher associated with this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_mutations_batcher]
:end-before: [END bigtable_mutations_batcher]
:type table: class
:param table: class:`~google.cloud.bigtable.table.Table`.
:type flush_count: int
:param flush_count: (Optional) Maximum number of rows per batch. If it
reaches the max number of rows it calls finish_batch() to
mutate the current row batch. Default is FLUSH_COUNT (1000
rows).
:type max_row_bytes: int
:param max_row_bytes: (Optional) Max number of row mutations size to
flush. If it reaches the max number of row mutations size it
calls finish_batch() to mutate the current row batch.
Default is MAX_ROW_BYTES (5 MB).
"""
return MutationsBatcher(self, flush_count, max_row_bytes)
|
[
"def",
"mutations_batcher",
"(",
"self",
",",
"flush_count",
"=",
"FLUSH_COUNT",
",",
"max_row_bytes",
"=",
"MAX_ROW_BYTES",
")",
":",
"return",
"MutationsBatcher",
"(",
"self",
",",
"flush_count",
",",
"max_row_bytes",
")"
] |
Factory to create a mutation batcher associated with this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_mutations_batcher]
:end-before: [END bigtable_mutations_batcher]
:type table: class
:param table: class:`~google.cloud.bigtable.table.Table`.
:type flush_count: int
:param flush_count: (Optional) Maximum number of rows per batch. If it
reaches the max number of rows it calls finish_batch() to
mutate the current row batch. Default is FLUSH_COUNT (1000
rows).
:type max_row_bytes: int
:param max_row_bytes: (Optional) Max number of row mutations size to
flush. If it reaches the max number of row mutations size it
calls finish_batch() to mutate the current row batch.
Default is MAX_ROW_BYTES (5 MB).
|
[
"Factory",
"to",
"create",
"a",
"mutation",
"batcher",
"associated",
"with",
"this",
"instance",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L631-L655
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/table.py
|
_RetryableMutateRowsWorker._do_mutate_retryable_rows
|
def _do_mutate_retryable_rows(self):
"""Mutate all the rows that are eligible for retry.
A row is eligible for retry if it has not been tried or if it resulted
in a transient error in a previous call.
:rtype: list
:return: The responses statuses, which is a list of
:class:`~google.rpc.status_pb2.Status`.
:raises: One of the following:
* :exc:`~.table._BigtableRetryableError` if any
row returned a transient error.
* :exc:`RuntimeError` if the number of responses doesn't
match the number of rows that were retried
"""
retryable_rows = []
index_into_all_rows = []
for index, status in enumerate(self.responses_statuses):
if self._is_retryable(status):
retryable_rows.append(self.rows[index])
index_into_all_rows.append(index)
if not retryable_rows:
# All mutations are either successful or non-retryable now.
return self.responses_statuses
mutate_rows_request = _mutate_rows_request(
self.table_name, retryable_rows, app_profile_id=self.app_profile_id
)
data_client = self.client.table_data_client
inner_api_calls = data_client._inner_api_calls
if "mutate_rows" not in inner_api_calls:
default_retry = (data_client._method_configs["MutateRows"].retry,)
if self.timeout is None:
default_timeout = data_client._method_configs["MutateRows"].timeout
else:
default_timeout = timeout.ExponentialTimeout(deadline=self.timeout)
data_client._inner_api_calls["mutate_rows"] = wrap_method(
data_client.transport.mutate_rows,
default_retry=default_retry,
default_timeout=default_timeout,
client_info=data_client._client_info,
)
responses = data_client._inner_api_calls["mutate_rows"](
mutate_rows_request, retry=None
)
num_responses = 0
num_retryable_responses = 0
for response in responses:
for entry in response.entries:
num_responses += 1
index = index_into_all_rows[entry.index]
self.responses_statuses[index] = entry.status
if self._is_retryable(entry.status):
num_retryable_responses += 1
if entry.status.code == 0:
self.rows[index].clear()
if len(retryable_rows) != num_responses:
raise RuntimeError(
"Unexpected number of responses",
num_responses,
"Expected",
len(retryable_rows),
)
if num_retryable_responses:
raise _BigtableRetryableError
return self.responses_statuses
|
python
|
def _do_mutate_retryable_rows(self):
"""Mutate all the rows that are eligible for retry.
A row is eligible for retry if it has not been tried or if it resulted
in a transient error in a previous call.
:rtype: list
:return: The responses statuses, which is a list of
:class:`~google.rpc.status_pb2.Status`.
:raises: One of the following:
* :exc:`~.table._BigtableRetryableError` if any
row returned a transient error.
* :exc:`RuntimeError` if the number of responses doesn't
match the number of rows that were retried
"""
retryable_rows = []
index_into_all_rows = []
for index, status in enumerate(self.responses_statuses):
if self._is_retryable(status):
retryable_rows.append(self.rows[index])
index_into_all_rows.append(index)
if not retryable_rows:
# All mutations are either successful or non-retryable now.
return self.responses_statuses
mutate_rows_request = _mutate_rows_request(
self.table_name, retryable_rows, app_profile_id=self.app_profile_id
)
data_client = self.client.table_data_client
inner_api_calls = data_client._inner_api_calls
if "mutate_rows" not in inner_api_calls:
default_retry = (data_client._method_configs["MutateRows"].retry,)
if self.timeout is None:
default_timeout = data_client._method_configs["MutateRows"].timeout
else:
default_timeout = timeout.ExponentialTimeout(deadline=self.timeout)
data_client._inner_api_calls["mutate_rows"] = wrap_method(
data_client.transport.mutate_rows,
default_retry=default_retry,
default_timeout=default_timeout,
client_info=data_client._client_info,
)
responses = data_client._inner_api_calls["mutate_rows"](
mutate_rows_request, retry=None
)
num_responses = 0
num_retryable_responses = 0
for response in responses:
for entry in response.entries:
num_responses += 1
index = index_into_all_rows[entry.index]
self.responses_statuses[index] = entry.status
if self._is_retryable(entry.status):
num_retryable_responses += 1
if entry.status.code == 0:
self.rows[index].clear()
if len(retryable_rows) != num_responses:
raise RuntimeError(
"Unexpected number of responses",
num_responses,
"Expected",
len(retryable_rows),
)
if num_retryable_responses:
raise _BigtableRetryableError
return self.responses_statuses
|
[
"def",
"_do_mutate_retryable_rows",
"(",
"self",
")",
":",
"retryable_rows",
"=",
"[",
"]",
"index_into_all_rows",
"=",
"[",
"]",
"for",
"index",
",",
"status",
"in",
"enumerate",
"(",
"self",
".",
"responses_statuses",
")",
":",
"if",
"self",
".",
"_is_retryable",
"(",
"status",
")",
":",
"retryable_rows",
".",
"append",
"(",
"self",
".",
"rows",
"[",
"index",
"]",
")",
"index_into_all_rows",
".",
"append",
"(",
"index",
")",
"if",
"not",
"retryable_rows",
":",
"# All mutations are either successful or non-retryable now.",
"return",
"self",
".",
"responses_statuses",
"mutate_rows_request",
"=",
"_mutate_rows_request",
"(",
"self",
".",
"table_name",
",",
"retryable_rows",
",",
"app_profile_id",
"=",
"self",
".",
"app_profile_id",
")",
"data_client",
"=",
"self",
".",
"client",
".",
"table_data_client",
"inner_api_calls",
"=",
"data_client",
".",
"_inner_api_calls",
"if",
"\"mutate_rows\"",
"not",
"in",
"inner_api_calls",
":",
"default_retry",
"=",
"(",
"data_client",
".",
"_method_configs",
"[",
"\"MutateRows\"",
"]",
".",
"retry",
",",
")",
"if",
"self",
".",
"timeout",
"is",
"None",
":",
"default_timeout",
"=",
"data_client",
".",
"_method_configs",
"[",
"\"MutateRows\"",
"]",
".",
"timeout",
"else",
":",
"default_timeout",
"=",
"timeout",
".",
"ExponentialTimeout",
"(",
"deadline",
"=",
"self",
".",
"timeout",
")",
"data_client",
".",
"_inner_api_calls",
"[",
"\"mutate_rows\"",
"]",
"=",
"wrap_method",
"(",
"data_client",
".",
"transport",
".",
"mutate_rows",
",",
"default_retry",
"=",
"default_retry",
",",
"default_timeout",
"=",
"default_timeout",
",",
"client_info",
"=",
"data_client",
".",
"_client_info",
",",
")",
"responses",
"=",
"data_client",
".",
"_inner_api_calls",
"[",
"\"mutate_rows\"",
"]",
"(",
"mutate_rows_request",
",",
"retry",
"=",
"None",
")",
"num_responses",
"=",
"0",
"num_retryable_responses",
"=",
"0",
"for",
"response",
"in",
"responses",
":",
"for",
"entry",
"in",
"response",
".",
"entries",
":",
"num_responses",
"+=",
"1",
"index",
"=",
"index_into_all_rows",
"[",
"entry",
".",
"index",
"]",
"self",
".",
"responses_statuses",
"[",
"index",
"]",
"=",
"entry",
".",
"status",
"if",
"self",
".",
"_is_retryable",
"(",
"entry",
".",
"status",
")",
":",
"num_retryable_responses",
"+=",
"1",
"if",
"entry",
".",
"status",
".",
"code",
"==",
"0",
":",
"self",
".",
"rows",
"[",
"index",
"]",
".",
"clear",
"(",
")",
"if",
"len",
"(",
"retryable_rows",
")",
"!=",
"num_responses",
":",
"raise",
"RuntimeError",
"(",
"\"Unexpected number of responses\"",
",",
"num_responses",
",",
"\"Expected\"",
",",
"len",
"(",
"retryable_rows",
")",
",",
")",
"if",
"num_retryable_responses",
":",
"raise",
"_BigtableRetryableError",
"return",
"self",
".",
"responses_statuses"
] |
Mutate all the rows that are eligible for retry.
A row is eligible for retry if it has not been tried or if it resulted
in a transient error in a previous call.
:rtype: list
:return: The responses statuses, which is a list of
:class:`~google.rpc.status_pb2.Status`.
:raises: One of the following:
* :exc:`~.table._BigtableRetryableError` if any
row returned a transient error.
* :exc:`RuntimeError` if the number of responses doesn't
match the number of rows that were retried
|
[
"Mutate",
"all",
"the",
"rows",
"that",
"are",
"eligible",
"for",
"retry",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/table.py#L712-L784
|
train
|
googleapis/google-cloud-python
|
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/heartbeater.py
|
Heartbeater.heartbeat
|
def heartbeat(self):
"""Periodically send heartbeats."""
while self._manager.is_active and not self._stop_event.is_set():
self._manager.heartbeat()
_LOGGER.debug("Sent heartbeat.")
self._stop_event.wait(timeout=self._period)
_LOGGER.info("%s exiting.", _HEARTBEAT_WORKER_NAME)
|
python
|
def heartbeat(self):
"""Periodically send heartbeats."""
while self._manager.is_active and not self._stop_event.is_set():
self._manager.heartbeat()
_LOGGER.debug("Sent heartbeat.")
self._stop_event.wait(timeout=self._period)
_LOGGER.info("%s exiting.", _HEARTBEAT_WORKER_NAME)
|
[
"def",
"heartbeat",
"(",
"self",
")",
":",
"while",
"self",
".",
"_manager",
".",
"is_active",
"and",
"not",
"self",
".",
"_stop_event",
".",
"is_set",
"(",
")",
":",
"self",
".",
"_manager",
".",
"heartbeat",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Sent heartbeat.\"",
")",
"self",
".",
"_stop_event",
".",
"wait",
"(",
"timeout",
"=",
"self",
".",
"_period",
")",
"_LOGGER",
".",
"info",
"(",
"\"%s exiting.\"",
",",
"_HEARTBEAT_WORKER_NAME",
")"
] |
Periodically send heartbeats.
|
[
"Periodically",
"send",
"heartbeats",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/heartbeater.py#L37-L44
|
train
|
googleapis/google-cloud-python
|
error_reporting/google/cloud/errorreporting_v1beta1/gapic/report_errors_service_client.py
|
ReportErrorsServiceClient.report_error_event
|
def report_error_event(
self,
project_name,
event,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Report an individual error event.
Example:
>>> from google.cloud import errorreporting_v1beta1
>>>
>>> client = errorreporting_v1beta1.ReportErrorsServiceClient()
>>>
>>> project_name = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `event`:
>>> event = {}
>>>
>>> response = client.report_error_event(project_name, event)
Args:
project_name (str): [Required] The resource name of the Google Cloud Platform project.
Written as ``projects/`` plus the `Google Cloud Platform project
ID <https://support.google.com/cloud/answer/6158840>`__. Example:
``projects/my-project-123``.
event (Union[dict, ~google.cloud.errorreporting_v1beta1.types.ReportedErrorEvent]): [Required] The error event to be reported.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.errorreporting_v1beta1.types.ReportedErrorEvent`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.errorreporting_v1beta1.types.ReportErrorEventResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "report_error_event" not in self._inner_api_calls:
self._inner_api_calls[
"report_error_event"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.report_error_event,
default_retry=self._method_configs["ReportErrorEvent"].retry,
default_timeout=self._method_configs["ReportErrorEvent"].timeout,
client_info=self._client_info,
)
request = report_errors_service_pb2.ReportErrorEventRequest(
project_name=project_name, event=event
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("project_name", project_name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["report_error_event"](
request, retry=retry, timeout=timeout, metadata=metadata
)
|
python
|
def report_error_event(
self,
project_name,
event,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Report an individual error event.
Example:
>>> from google.cloud import errorreporting_v1beta1
>>>
>>> client = errorreporting_v1beta1.ReportErrorsServiceClient()
>>>
>>> project_name = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `event`:
>>> event = {}
>>>
>>> response = client.report_error_event(project_name, event)
Args:
project_name (str): [Required] The resource name of the Google Cloud Platform project.
Written as ``projects/`` plus the `Google Cloud Platform project
ID <https://support.google.com/cloud/answer/6158840>`__. Example:
``projects/my-project-123``.
event (Union[dict, ~google.cloud.errorreporting_v1beta1.types.ReportedErrorEvent]): [Required] The error event to be reported.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.errorreporting_v1beta1.types.ReportedErrorEvent`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.errorreporting_v1beta1.types.ReportErrorEventResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "report_error_event" not in self._inner_api_calls:
self._inner_api_calls[
"report_error_event"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.report_error_event,
default_retry=self._method_configs["ReportErrorEvent"].retry,
default_timeout=self._method_configs["ReportErrorEvent"].timeout,
client_info=self._client_info,
)
request = report_errors_service_pb2.ReportErrorEventRequest(
project_name=project_name, event=event
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("project_name", project_name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["report_error_event"](
request, retry=retry, timeout=timeout, metadata=metadata
)
|
[
"def",
"report_error_event",
"(",
"self",
",",
"project_name",
",",
"event",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"report_error_event\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"report_error_event\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"report_error_event",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"ReportErrorEvent\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"ReportErrorEvent\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"report_errors_service_pb2",
".",
"ReportErrorEventRequest",
"(",
"project_name",
"=",
"project_name",
",",
"event",
"=",
"event",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"project_name\"",
",",
"project_name",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"report_error_event\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] |
Report an individual error event.
Example:
>>> from google.cloud import errorreporting_v1beta1
>>>
>>> client = errorreporting_v1beta1.ReportErrorsServiceClient()
>>>
>>> project_name = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `event`:
>>> event = {}
>>>
>>> response = client.report_error_event(project_name, event)
Args:
project_name (str): [Required] The resource name of the Google Cloud Platform project.
Written as ``projects/`` plus the `Google Cloud Platform project
ID <https://support.google.com/cloud/answer/6158840>`__. Example:
``projects/my-project-123``.
event (Union[dict, ~google.cloud.errorreporting_v1beta1.types.ReportedErrorEvent]): [Required] The error event to be reported.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.errorreporting_v1beta1.types.ReportedErrorEvent`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.errorreporting_v1beta1.types.ReportErrorEventResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
|
[
"Report",
"an",
"individual",
"error",
"event",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/errorreporting_v1beta1/gapic/report_errors_service_client.py#L188-L268
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/dbapi/_helpers.py
|
scalar_to_query_parameter
|
def scalar_to_query_parameter(value, name=None):
"""Convert a scalar value into a query parameter.
:type value: any
:param value: A scalar value to convert into a query parameter.
:type name: str
:param name: (Optional) Name of the query parameter.
:rtype: :class:`~google.cloud.bigquery.ScalarQueryParameter`
:returns:
A query parameter corresponding with the type and value of the plain
Python object.
:raises: :class:`~google.cloud.bigquery.dbapi.exceptions.ProgrammingError`
if the type cannot be determined.
"""
parameter_type = None
if isinstance(value, bool):
parameter_type = "BOOL"
elif isinstance(value, numbers.Integral):
parameter_type = "INT64"
elif isinstance(value, numbers.Real):
parameter_type = "FLOAT64"
elif isinstance(value, decimal.Decimal):
parameter_type = "NUMERIC"
elif isinstance(value, six.text_type):
parameter_type = "STRING"
elif isinstance(value, six.binary_type):
parameter_type = "BYTES"
elif isinstance(value, datetime.datetime):
parameter_type = "DATETIME" if value.tzinfo is None else "TIMESTAMP"
elif isinstance(value, datetime.date):
parameter_type = "DATE"
elif isinstance(value, datetime.time):
parameter_type = "TIME"
else:
raise exceptions.ProgrammingError(
"encountered parameter {} with value {} of unexpected type".format(
name, value
)
)
return bigquery.ScalarQueryParameter(name, parameter_type, value)
|
python
|
def scalar_to_query_parameter(value, name=None):
"""Convert a scalar value into a query parameter.
:type value: any
:param value: A scalar value to convert into a query parameter.
:type name: str
:param name: (Optional) Name of the query parameter.
:rtype: :class:`~google.cloud.bigquery.ScalarQueryParameter`
:returns:
A query parameter corresponding with the type and value of the plain
Python object.
:raises: :class:`~google.cloud.bigquery.dbapi.exceptions.ProgrammingError`
if the type cannot be determined.
"""
parameter_type = None
if isinstance(value, bool):
parameter_type = "BOOL"
elif isinstance(value, numbers.Integral):
parameter_type = "INT64"
elif isinstance(value, numbers.Real):
parameter_type = "FLOAT64"
elif isinstance(value, decimal.Decimal):
parameter_type = "NUMERIC"
elif isinstance(value, six.text_type):
parameter_type = "STRING"
elif isinstance(value, six.binary_type):
parameter_type = "BYTES"
elif isinstance(value, datetime.datetime):
parameter_type = "DATETIME" if value.tzinfo is None else "TIMESTAMP"
elif isinstance(value, datetime.date):
parameter_type = "DATE"
elif isinstance(value, datetime.time):
parameter_type = "TIME"
else:
raise exceptions.ProgrammingError(
"encountered parameter {} with value {} of unexpected type".format(
name, value
)
)
return bigquery.ScalarQueryParameter(name, parameter_type, value)
|
[
"def",
"scalar_to_query_parameter",
"(",
"value",
",",
"name",
"=",
"None",
")",
":",
"parameter_type",
"=",
"None",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"parameter_type",
"=",
"\"BOOL\"",
"elif",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Integral",
")",
":",
"parameter_type",
"=",
"\"INT64\"",
"elif",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Real",
")",
":",
"parameter_type",
"=",
"\"FLOAT64\"",
"elif",
"isinstance",
"(",
"value",
",",
"decimal",
".",
"Decimal",
")",
":",
"parameter_type",
"=",
"\"NUMERIC\"",
"elif",
"isinstance",
"(",
"value",
",",
"six",
".",
"text_type",
")",
":",
"parameter_type",
"=",
"\"STRING\"",
"elif",
"isinstance",
"(",
"value",
",",
"six",
".",
"binary_type",
")",
":",
"parameter_type",
"=",
"\"BYTES\"",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"parameter_type",
"=",
"\"DATETIME\"",
"if",
"value",
".",
"tzinfo",
"is",
"None",
"else",
"\"TIMESTAMP\"",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"date",
")",
":",
"parameter_type",
"=",
"\"DATE\"",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"time",
")",
":",
"parameter_type",
"=",
"\"TIME\"",
"else",
":",
"raise",
"exceptions",
".",
"ProgrammingError",
"(",
"\"encountered parameter {} with value {} of unexpected type\"",
".",
"format",
"(",
"name",
",",
"value",
")",
")",
"return",
"bigquery",
".",
"ScalarQueryParameter",
"(",
"name",
",",
"parameter_type",
",",
"value",
")"
] |
Convert a scalar value into a query parameter.
:type value: any
:param value: A scalar value to convert into a query parameter.
:type name: str
:param name: (Optional) Name of the query parameter.
:rtype: :class:`~google.cloud.bigquery.ScalarQueryParameter`
:returns:
A query parameter corresponding with the type and value of the plain
Python object.
:raises: :class:`~google.cloud.bigquery.dbapi.exceptions.ProgrammingError`
if the type cannot be determined.
|
[
"Convert",
"a",
"scalar",
"value",
"into",
"a",
"query",
"parameter",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/dbapi/_helpers.py#L30-L72
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/dbapi/_helpers.py
|
to_query_parameters_dict
|
def to_query_parameters_dict(parameters):
"""Converts a dictionary of parameter values into query parameters.
:type parameters: Mapping[str, Any]
:param parameters: Dictionary of query parameter values.
:rtype: List[google.cloud.bigquery.query._AbstractQueryParameter]
:returns: A list of named query parameters.
"""
return [
scalar_to_query_parameter(value, name=name)
for name, value in six.iteritems(parameters)
]
|
python
|
def to_query_parameters_dict(parameters):
"""Converts a dictionary of parameter values into query parameters.
:type parameters: Mapping[str, Any]
:param parameters: Dictionary of query parameter values.
:rtype: List[google.cloud.bigquery.query._AbstractQueryParameter]
:returns: A list of named query parameters.
"""
return [
scalar_to_query_parameter(value, name=name)
for name, value in six.iteritems(parameters)
]
|
[
"def",
"to_query_parameters_dict",
"(",
"parameters",
")",
":",
"return",
"[",
"scalar_to_query_parameter",
"(",
"value",
",",
"name",
"=",
"name",
")",
"for",
"name",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"parameters",
")",
"]"
] |
Converts a dictionary of parameter values into query parameters.
:type parameters: Mapping[str, Any]
:param parameters: Dictionary of query parameter values.
:rtype: List[google.cloud.bigquery.query._AbstractQueryParameter]
:returns: A list of named query parameters.
|
[
"Converts",
"a",
"dictionary",
"of",
"parameter",
"values",
"into",
"query",
"parameters",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/dbapi/_helpers.py#L87-L99
|
train
|
googleapis/google-cloud-python
|
bigquery/google/cloud/bigquery/dbapi/_helpers.py
|
to_query_parameters
|
def to_query_parameters(parameters):
"""Converts DB-API parameter values into query parameters.
:type parameters: Mapping[str, Any] or Sequence[Any]
:param parameters: A dictionary or sequence of query parameter values.
:rtype: List[google.cloud.bigquery.query._AbstractQueryParameter]
:returns: A list of query parameters.
"""
if parameters is None:
return []
if isinstance(parameters, collections_abc.Mapping):
return to_query_parameters_dict(parameters)
return to_query_parameters_list(parameters)
|
python
|
def to_query_parameters(parameters):
"""Converts DB-API parameter values into query parameters.
:type parameters: Mapping[str, Any] or Sequence[Any]
:param parameters: A dictionary or sequence of query parameter values.
:rtype: List[google.cloud.bigquery.query._AbstractQueryParameter]
:returns: A list of query parameters.
"""
if parameters is None:
return []
if isinstance(parameters, collections_abc.Mapping):
return to_query_parameters_dict(parameters)
return to_query_parameters_list(parameters)
|
[
"def",
"to_query_parameters",
"(",
"parameters",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"isinstance",
"(",
"parameters",
",",
"collections_abc",
".",
"Mapping",
")",
":",
"return",
"to_query_parameters_dict",
"(",
"parameters",
")",
"return",
"to_query_parameters_list",
"(",
"parameters",
")"
] |
Converts DB-API parameter values into query parameters.
:type parameters: Mapping[str, Any] or Sequence[Any]
:param parameters: A dictionary or sequence of query parameter values.
:rtype: List[google.cloud.bigquery.query._AbstractQueryParameter]
:returns: A list of query parameters.
|
[
"Converts",
"DB",
"-",
"API",
"parameter",
"values",
"into",
"query",
"parameters",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/dbapi/_helpers.py#L102-L117
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/operation.py
|
_refresh_http
|
def _refresh_http(api_request, operation_name):
"""Refresh an operation using a JSON/HTTP client.
Args:
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
operation_name (str): The name of the operation.
Returns:
google.longrunning.operations_pb2.Operation: The operation.
"""
path = "operations/{}".format(operation_name)
api_response = api_request(method="GET", path=path)
return json_format.ParseDict(api_response, operations_pb2.Operation())
|
python
|
def _refresh_http(api_request, operation_name):
"""Refresh an operation using a JSON/HTTP client.
Args:
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
operation_name (str): The name of the operation.
Returns:
google.longrunning.operations_pb2.Operation: The operation.
"""
path = "operations/{}".format(operation_name)
api_response = api_request(method="GET", path=path)
return json_format.ParseDict(api_response, operations_pb2.Operation())
|
[
"def",
"_refresh_http",
"(",
"api_request",
",",
"operation_name",
")",
":",
"path",
"=",
"\"operations/{}\"",
".",
"format",
"(",
"operation_name",
")",
"api_response",
"=",
"api_request",
"(",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"path",
")",
"return",
"json_format",
".",
"ParseDict",
"(",
"api_response",
",",
"operations_pb2",
".",
"Operation",
"(",
")",
")"
] |
Refresh an operation using a JSON/HTTP client.
Args:
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
operation_name (str): The name of the operation.
Returns:
google.longrunning.operations_pb2.Operation: The operation.
|
[
"Refresh",
"an",
"operation",
"using",
"a",
"JSON",
"/",
"HTTP",
"client",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operation.py#L187-L201
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/operation.py
|
_cancel_http
|
def _cancel_http(api_request, operation_name):
"""Cancel an operation using a JSON/HTTP client.
Args:
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
operation_name (str): The name of the operation.
"""
path = "operations/{}:cancel".format(operation_name)
api_request(method="POST", path=path)
|
python
|
def _cancel_http(api_request, operation_name):
"""Cancel an operation using a JSON/HTTP client.
Args:
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
operation_name (str): The name of the operation.
"""
path = "operations/{}:cancel".format(operation_name)
api_request(method="POST", path=path)
|
[
"def",
"_cancel_http",
"(",
"api_request",
",",
"operation_name",
")",
":",
"path",
"=",
"\"operations/{}:cancel\"",
".",
"format",
"(",
"operation_name",
")",
"api_request",
"(",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"path",
")"
] |
Cancel an operation using a JSON/HTTP client.
Args:
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
operation_name (str): The name of the operation.
|
[
"Cancel",
"an",
"operation",
"using",
"a",
"JSON",
"/",
"HTTP",
"client",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operation.py#L204-L214
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/operation.py
|
from_http_json
|
def from_http_json(operation, api_request, result_type, **kwargs):
"""Create an operation future using a HTTP/JSON client.
This interacts with the long-running operations `service`_ (specific
to a given API) via `HTTP/JSON`_.
.. _HTTP/JSON: https://cloud.google.com/speech/reference/rest/\
v1beta1/operations#Operation
Args:
operation (dict): Operation as a dictionary.
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
result_type (:func:`type`): The protobuf result type.
kwargs: Keyword args passed into the :class:`Operation` constructor.
Returns:
~.api_core.operation.Operation: The operation future to track the given
operation.
"""
operation_proto = json_format.ParseDict(operation, operations_pb2.Operation())
refresh = functools.partial(_refresh_http, api_request, operation_proto.name)
cancel = functools.partial(_cancel_http, api_request, operation_proto.name)
return Operation(operation_proto, refresh, cancel, result_type, **kwargs)
|
python
|
def from_http_json(operation, api_request, result_type, **kwargs):
"""Create an operation future using a HTTP/JSON client.
This interacts with the long-running operations `service`_ (specific
to a given API) via `HTTP/JSON`_.
.. _HTTP/JSON: https://cloud.google.com/speech/reference/rest/\
v1beta1/operations#Operation
Args:
operation (dict): Operation as a dictionary.
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
result_type (:func:`type`): The protobuf result type.
kwargs: Keyword args passed into the :class:`Operation` constructor.
Returns:
~.api_core.operation.Operation: The operation future to track the given
operation.
"""
operation_proto = json_format.ParseDict(operation, operations_pb2.Operation())
refresh = functools.partial(_refresh_http, api_request, operation_proto.name)
cancel = functools.partial(_cancel_http, api_request, operation_proto.name)
return Operation(operation_proto, refresh, cancel, result_type, **kwargs)
|
[
"def",
"from_http_json",
"(",
"operation",
",",
"api_request",
",",
"result_type",
",",
"*",
"*",
"kwargs",
")",
":",
"operation_proto",
"=",
"json_format",
".",
"ParseDict",
"(",
"operation",
",",
"operations_pb2",
".",
"Operation",
"(",
")",
")",
"refresh",
"=",
"functools",
".",
"partial",
"(",
"_refresh_http",
",",
"api_request",
",",
"operation_proto",
".",
"name",
")",
"cancel",
"=",
"functools",
".",
"partial",
"(",
"_cancel_http",
",",
"api_request",
",",
"operation_proto",
".",
"name",
")",
"return",
"Operation",
"(",
"operation_proto",
",",
"refresh",
",",
"cancel",
",",
"result_type",
",",
"*",
"*",
"kwargs",
")"
] |
Create an operation future using a HTTP/JSON client.
This interacts with the long-running operations `service`_ (specific
to a given API) via `HTTP/JSON`_.
.. _HTTP/JSON: https://cloud.google.com/speech/reference/rest/\
v1beta1/operations#Operation
Args:
operation (dict): Operation as a dictionary.
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
result_type (:func:`type`): The protobuf result type.
kwargs: Keyword args passed into the :class:`Operation` constructor.
Returns:
~.api_core.operation.Operation: The operation future to track the given
operation.
|
[
"Create",
"an",
"operation",
"future",
"using",
"a",
"HTTP",
"/",
"JSON",
"client",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operation.py#L217-L241
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/operation.py
|
_refresh_grpc
|
def _refresh_grpc(operations_stub, operation_name):
"""Refresh an operation using a gRPC client.
Args:
operations_stub (google.longrunning.operations_pb2.OperationsStub):
The gRPC operations stub.
operation_name (str): The name of the operation.
Returns:
google.longrunning.operations_pb2.Operation: The operation.
"""
request_pb = operations_pb2.GetOperationRequest(name=operation_name)
return operations_stub.GetOperation(request_pb)
|
python
|
def _refresh_grpc(operations_stub, operation_name):
"""Refresh an operation using a gRPC client.
Args:
operations_stub (google.longrunning.operations_pb2.OperationsStub):
The gRPC operations stub.
operation_name (str): The name of the operation.
Returns:
google.longrunning.operations_pb2.Operation: The operation.
"""
request_pb = operations_pb2.GetOperationRequest(name=operation_name)
return operations_stub.GetOperation(request_pb)
|
[
"def",
"_refresh_grpc",
"(",
"operations_stub",
",",
"operation_name",
")",
":",
"request_pb",
"=",
"operations_pb2",
".",
"GetOperationRequest",
"(",
"name",
"=",
"operation_name",
")",
"return",
"operations_stub",
".",
"GetOperation",
"(",
"request_pb",
")"
] |
Refresh an operation using a gRPC client.
Args:
operations_stub (google.longrunning.operations_pb2.OperationsStub):
The gRPC operations stub.
operation_name (str): The name of the operation.
Returns:
google.longrunning.operations_pb2.Operation: The operation.
|
[
"Refresh",
"an",
"operation",
"using",
"a",
"gRPC",
"client",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operation.py#L244-L256
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/operation.py
|
_cancel_grpc
|
def _cancel_grpc(operations_stub, operation_name):
"""Cancel an operation using a gRPC client.
Args:
operations_stub (google.longrunning.operations_pb2.OperationsStub):
The gRPC operations stub.
operation_name (str): The name of the operation.
"""
request_pb = operations_pb2.CancelOperationRequest(name=operation_name)
operations_stub.CancelOperation(request_pb)
|
python
|
def _cancel_grpc(operations_stub, operation_name):
"""Cancel an operation using a gRPC client.
Args:
operations_stub (google.longrunning.operations_pb2.OperationsStub):
The gRPC operations stub.
operation_name (str): The name of the operation.
"""
request_pb = operations_pb2.CancelOperationRequest(name=operation_name)
operations_stub.CancelOperation(request_pb)
|
[
"def",
"_cancel_grpc",
"(",
"operations_stub",
",",
"operation_name",
")",
":",
"request_pb",
"=",
"operations_pb2",
".",
"CancelOperationRequest",
"(",
"name",
"=",
"operation_name",
")",
"operations_stub",
".",
"CancelOperation",
"(",
"request_pb",
")"
] |
Cancel an operation using a gRPC client.
Args:
operations_stub (google.longrunning.operations_pb2.OperationsStub):
The gRPC operations stub.
operation_name (str): The name of the operation.
|
[
"Cancel",
"an",
"operation",
"using",
"a",
"gRPC",
"client",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operation.py#L259-L268
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/operation.py
|
from_grpc
|
def from_grpc(operation, operations_stub, result_type, **kwargs):
"""Create an operation future using a gRPC client.
This interacts with the long-running operations `service`_ (specific
to a given API) via gRPC.
.. _service: https://github.com/googleapis/googleapis/blob/\
050400df0fdb16f63b63e9dee53819044bffc857/\
google/longrunning/operations.proto#L38
Args:
operation (google.longrunning.operations_pb2.Operation): The operation.
operations_stub (google.longrunning.operations_pb2.OperationsStub):
The operations stub.
result_type (:func:`type`): The protobuf result type.
kwargs: Keyword args passed into the :class:`Operation` constructor.
Returns:
~.api_core.operation.Operation: The operation future to track the given
operation.
"""
refresh = functools.partial(_refresh_grpc, operations_stub, operation.name)
cancel = functools.partial(_cancel_grpc, operations_stub, operation.name)
return Operation(operation, refresh, cancel, result_type, **kwargs)
|
python
|
def from_grpc(operation, operations_stub, result_type, **kwargs):
"""Create an operation future using a gRPC client.
This interacts with the long-running operations `service`_ (specific
to a given API) via gRPC.
.. _service: https://github.com/googleapis/googleapis/blob/\
050400df0fdb16f63b63e9dee53819044bffc857/\
google/longrunning/operations.proto#L38
Args:
operation (google.longrunning.operations_pb2.Operation): The operation.
operations_stub (google.longrunning.operations_pb2.OperationsStub):
The operations stub.
result_type (:func:`type`): The protobuf result type.
kwargs: Keyword args passed into the :class:`Operation` constructor.
Returns:
~.api_core.operation.Operation: The operation future to track the given
operation.
"""
refresh = functools.partial(_refresh_grpc, operations_stub, operation.name)
cancel = functools.partial(_cancel_grpc, operations_stub, operation.name)
return Operation(operation, refresh, cancel, result_type, **kwargs)
|
[
"def",
"from_grpc",
"(",
"operation",
",",
"operations_stub",
",",
"result_type",
",",
"*",
"*",
"kwargs",
")",
":",
"refresh",
"=",
"functools",
".",
"partial",
"(",
"_refresh_grpc",
",",
"operations_stub",
",",
"operation",
".",
"name",
")",
"cancel",
"=",
"functools",
".",
"partial",
"(",
"_cancel_grpc",
",",
"operations_stub",
",",
"operation",
".",
"name",
")",
"return",
"Operation",
"(",
"operation",
",",
"refresh",
",",
"cancel",
",",
"result_type",
",",
"*",
"*",
"kwargs",
")"
] |
Create an operation future using a gRPC client.
This interacts with the long-running operations `service`_ (specific
to a given API) via gRPC.
.. _service: https://github.com/googleapis/googleapis/blob/\
050400df0fdb16f63b63e9dee53819044bffc857/\
google/longrunning/operations.proto#L38
Args:
operation (google.longrunning.operations_pb2.Operation): The operation.
operations_stub (google.longrunning.operations_pb2.OperationsStub):
The operations stub.
result_type (:func:`type`): The protobuf result type.
kwargs: Keyword args passed into the :class:`Operation` constructor.
Returns:
~.api_core.operation.Operation: The operation future to track the given
operation.
|
[
"Create",
"an",
"operation",
"future",
"using",
"a",
"gRPC",
"client",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operation.py#L271-L294
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/operation.py
|
from_gapic
|
def from_gapic(operation, operations_client, result_type, **kwargs):
"""Create an operation future from a gapic client.
This interacts with the long-running operations `service`_ (specific
to a given API) via a gapic client.
.. _service: https://github.com/googleapis/googleapis/blob/\
050400df0fdb16f63b63e9dee53819044bffc857/\
google/longrunning/operations.proto#L38
Args:
operation (google.longrunning.operations_pb2.Operation): The operation.
operations_client (google.api_core.operations_v1.OperationsClient):
The operations client.
result_type (:func:`type`): The protobuf result type.
kwargs: Keyword args passed into the :class:`Operation` constructor.
Returns:
~.api_core.operation.Operation: The operation future to track the given
operation.
"""
refresh = functools.partial(operations_client.get_operation, operation.name)
cancel = functools.partial(operations_client.cancel_operation, operation.name)
return Operation(operation, refresh, cancel, result_type, **kwargs)
|
python
|
def from_gapic(operation, operations_client, result_type, **kwargs):
"""Create an operation future from a gapic client.
This interacts with the long-running operations `service`_ (specific
to a given API) via a gapic client.
.. _service: https://github.com/googleapis/googleapis/blob/\
050400df0fdb16f63b63e9dee53819044bffc857/\
google/longrunning/operations.proto#L38
Args:
operation (google.longrunning.operations_pb2.Operation): The operation.
operations_client (google.api_core.operations_v1.OperationsClient):
The operations client.
result_type (:func:`type`): The protobuf result type.
kwargs: Keyword args passed into the :class:`Operation` constructor.
Returns:
~.api_core.operation.Operation: The operation future to track the given
operation.
"""
refresh = functools.partial(operations_client.get_operation, operation.name)
cancel = functools.partial(operations_client.cancel_operation, operation.name)
return Operation(operation, refresh, cancel, result_type, **kwargs)
|
[
"def",
"from_gapic",
"(",
"operation",
",",
"operations_client",
",",
"result_type",
",",
"*",
"*",
"kwargs",
")",
":",
"refresh",
"=",
"functools",
".",
"partial",
"(",
"operations_client",
".",
"get_operation",
",",
"operation",
".",
"name",
")",
"cancel",
"=",
"functools",
".",
"partial",
"(",
"operations_client",
".",
"cancel_operation",
",",
"operation",
".",
"name",
")",
"return",
"Operation",
"(",
"operation",
",",
"refresh",
",",
"cancel",
",",
"result_type",
",",
"*",
"*",
"kwargs",
")"
] |
Create an operation future from a gapic client.
This interacts with the long-running operations `service`_ (specific
to a given API) via a gapic client.
.. _service: https://github.com/googleapis/googleapis/blob/\
050400df0fdb16f63b63e9dee53819044bffc857/\
google/longrunning/operations.proto#L38
Args:
operation (google.longrunning.operations_pb2.Operation): The operation.
operations_client (google.api_core.operations_v1.OperationsClient):
The operations client.
result_type (:func:`type`): The protobuf result type.
kwargs: Keyword args passed into the :class:`Operation` constructor.
Returns:
~.api_core.operation.Operation: The operation future to track the given
operation.
|
[
"Create",
"an",
"operation",
"future",
"from",
"a",
"gapic",
"client",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operation.py#L297-L320
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/operation.py
|
Operation.metadata
|
def metadata(self):
"""google.protobuf.Message: the current operation metadata."""
if not self._operation.HasField("metadata"):
return None
return protobuf_helpers.from_any_pb(
self._metadata_type, self._operation.metadata
)
|
python
|
def metadata(self):
"""google.protobuf.Message: the current operation metadata."""
if not self._operation.HasField("metadata"):
return None
return protobuf_helpers.from_any_pb(
self._metadata_type, self._operation.metadata
)
|
[
"def",
"metadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_operation",
".",
"HasField",
"(",
"\"metadata\"",
")",
":",
"return",
"None",
"return",
"protobuf_helpers",
".",
"from_any_pb",
"(",
"self",
".",
"_metadata_type",
",",
"self",
".",
"_operation",
".",
"metadata",
")"
] |
google.protobuf.Message: the current operation metadata.
|
[
"google",
".",
"protobuf",
".",
"Message",
":",
"the",
"current",
"operation",
"metadata",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operation.py#L95-L102
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/operation.py
|
Operation._set_result_from_operation
|
def _set_result_from_operation(self):
"""Set the result or exception from the operation if it is complete."""
# This must be done in a lock to prevent the polling thread
# and main thread from both executing the completion logic
# at the same time.
with self._completion_lock:
# If the operation isn't complete or if the result has already been
# set, do not call set_result/set_exception again.
# Note: self._result_set is set to True in set_result and
# set_exception, in case those methods are invoked directly.
if not self._operation.done or self._result_set:
return
if self._operation.HasField("response"):
response = protobuf_helpers.from_any_pb(
self._result_type, self._operation.response
)
self.set_result(response)
elif self._operation.HasField("error"):
exception = exceptions.GoogleAPICallError(
self._operation.error.message,
errors=(self._operation.error,),
response=self._operation,
)
self.set_exception(exception)
else:
exception = exceptions.GoogleAPICallError(
"Unexpected state: Long-running operation had neither "
"response nor error set."
)
self.set_exception(exception)
|
python
|
def _set_result_from_operation(self):
"""Set the result or exception from the operation if it is complete."""
# This must be done in a lock to prevent the polling thread
# and main thread from both executing the completion logic
# at the same time.
with self._completion_lock:
# If the operation isn't complete or if the result has already been
# set, do not call set_result/set_exception again.
# Note: self._result_set is set to True in set_result and
# set_exception, in case those methods are invoked directly.
if not self._operation.done or self._result_set:
return
if self._operation.HasField("response"):
response = protobuf_helpers.from_any_pb(
self._result_type, self._operation.response
)
self.set_result(response)
elif self._operation.HasField("error"):
exception = exceptions.GoogleAPICallError(
self._operation.error.message,
errors=(self._operation.error,),
response=self._operation,
)
self.set_exception(exception)
else:
exception = exceptions.GoogleAPICallError(
"Unexpected state: Long-running operation had neither "
"response nor error set."
)
self.set_exception(exception)
|
[
"def",
"_set_result_from_operation",
"(",
"self",
")",
":",
"# This must be done in a lock to prevent the polling thread",
"# and main thread from both executing the completion logic",
"# at the same time.",
"with",
"self",
".",
"_completion_lock",
":",
"# If the operation isn't complete or if the result has already been",
"# set, do not call set_result/set_exception again.",
"# Note: self._result_set is set to True in set_result and",
"# set_exception, in case those methods are invoked directly.",
"if",
"not",
"self",
".",
"_operation",
".",
"done",
"or",
"self",
".",
"_result_set",
":",
"return",
"if",
"self",
".",
"_operation",
".",
"HasField",
"(",
"\"response\"",
")",
":",
"response",
"=",
"protobuf_helpers",
".",
"from_any_pb",
"(",
"self",
".",
"_result_type",
",",
"self",
".",
"_operation",
".",
"response",
")",
"self",
".",
"set_result",
"(",
"response",
")",
"elif",
"self",
".",
"_operation",
".",
"HasField",
"(",
"\"error\"",
")",
":",
"exception",
"=",
"exceptions",
".",
"GoogleAPICallError",
"(",
"self",
".",
"_operation",
".",
"error",
".",
"message",
",",
"errors",
"=",
"(",
"self",
".",
"_operation",
".",
"error",
",",
")",
",",
"response",
"=",
"self",
".",
"_operation",
",",
")",
"self",
".",
"set_exception",
"(",
"exception",
")",
"else",
":",
"exception",
"=",
"exceptions",
".",
"GoogleAPICallError",
"(",
"\"Unexpected state: Long-running operation had neither \"",
"\"response nor error set.\"",
")",
"self",
".",
"set_exception",
"(",
"exception",
")"
] |
Set the result or exception from the operation if it is complete.
|
[
"Set",
"the",
"result",
"or",
"exception",
"from",
"the",
"operation",
"if",
"it",
"is",
"complete",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operation.py#L116-L146
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/operation.py
|
Operation._refresh_and_update
|
def _refresh_and_update(self):
"""Refresh the operation and update the result if needed."""
# If the currently cached operation is done, no need to make another
# RPC as it will not change once done.
if not self._operation.done:
self._operation = self._refresh()
self._set_result_from_operation()
|
python
|
def _refresh_and_update(self):
"""Refresh the operation and update the result if needed."""
# If the currently cached operation is done, no need to make another
# RPC as it will not change once done.
if not self._operation.done:
self._operation = self._refresh()
self._set_result_from_operation()
|
[
"def",
"_refresh_and_update",
"(",
"self",
")",
":",
"# If the currently cached operation is done, no need to make another",
"# RPC as it will not change once done.",
"if",
"not",
"self",
".",
"_operation",
".",
"done",
":",
"self",
".",
"_operation",
"=",
"self",
".",
"_refresh",
"(",
")",
"self",
".",
"_set_result_from_operation",
"(",
")"
] |
Refresh the operation and update the result if needed.
|
[
"Refresh",
"the",
"operation",
"and",
"update",
"the",
"result",
"if",
"needed",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operation.py#L148-L154
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/operation.py
|
Operation.cancelled
|
def cancelled(self):
"""True if the operation was cancelled."""
self._refresh_and_update()
return (
self._operation.HasField("error")
and self._operation.error.code == code_pb2.CANCELLED
)
|
python
|
def cancelled(self):
"""True if the operation was cancelled."""
self._refresh_and_update()
return (
self._operation.HasField("error")
and self._operation.error.code == code_pb2.CANCELLED
)
|
[
"def",
"cancelled",
"(",
"self",
")",
":",
"self",
".",
"_refresh_and_update",
"(",
")",
"return",
"(",
"self",
".",
"_operation",
".",
"HasField",
"(",
"\"error\"",
")",
"and",
"self",
".",
"_operation",
".",
"error",
".",
"code",
"==",
"code_pb2",
".",
"CANCELLED",
")"
] |
True if the operation was cancelled.
|
[
"True",
"if",
"the",
"operation",
"was",
"cancelled",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/operation.py#L178-L184
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/acl.py
|
_ACLEntity.revoke
|
def revoke(self, role):
"""Remove a role from the entity.
:type role: str
:param role: The role to remove from the entity.
"""
if role in self.roles:
self.roles.remove(role)
|
python
|
def revoke(self, role):
"""Remove a role from the entity.
:type role: str
:param role: The role to remove from the entity.
"""
if role in self.roles:
self.roles.remove(role)
|
[
"def",
"revoke",
"(",
"self",
",",
"role",
")",
":",
"if",
"role",
"in",
"self",
".",
"roles",
":",
"self",
".",
"roles",
".",
"remove",
"(",
"role",
")"
] |
Remove a role from the entity.
:type role: str
:param role: The role to remove from the entity.
|
[
"Remove",
"a",
"role",
"from",
"the",
"entity",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L133-L140
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/acl.py
|
ACL.validate_predefined
|
def validate_predefined(cls, predefined):
"""Ensures predefined is in list of predefined json values
:type predefined: str
:param predefined: name of a predefined acl
:type predefined: str
:param predefined: validated JSON name of predefined acl
:raises: :exc: `ValueError`: If predefined is not a valid acl
"""
predefined = cls.PREDEFINED_XML_ACLS.get(predefined, predefined)
if predefined and predefined not in cls.PREDEFINED_JSON_ACLS:
raise ValueError("Invalid predefined ACL: %s" % (predefined,))
return predefined
|
python
|
def validate_predefined(cls, predefined):
"""Ensures predefined is in list of predefined json values
:type predefined: str
:param predefined: name of a predefined acl
:type predefined: str
:param predefined: validated JSON name of predefined acl
:raises: :exc: `ValueError`: If predefined is not a valid acl
"""
predefined = cls.PREDEFINED_XML_ACLS.get(predefined, predefined)
if predefined and predefined not in cls.PREDEFINED_JSON_ACLS:
raise ValueError("Invalid predefined ACL: %s" % (predefined,))
return predefined
|
[
"def",
"validate_predefined",
"(",
"cls",
",",
"predefined",
")",
":",
"predefined",
"=",
"cls",
".",
"PREDEFINED_XML_ACLS",
".",
"get",
"(",
"predefined",
",",
"predefined",
")",
"if",
"predefined",
"and",
"predefined",
"not",
"in",
"cls",
".",
"PREDEFINED_JSON_ACLS",
":",
"raise",
"ValueError",
"(",
"\"Invalid predefined ACL: %s\"",
"%",
"(",
"predefined",
",",
")",
")",
"return",
"predefined"
] |
Ensures predefined is in list of predefined json values
:type predefined: str
:param predefined: name of a predefined acl
:type predefined: str
:param predefined: validated JSON name of predefined acl
:raises: :exc: `ValueError`: If predefined is not a valid acl
|
[
"Ensures",
"predefined",
"is",
"in",
"list",
"of",
"predefined",
"json",
"values"
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L215-L229
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/acl.py
|
ACL.entity_from_dict
|
def entity_from_dict(self, entity_dict):
"""Build an _ACLEntity object from a dictionary of data.
An entity is a mutable object that represents a list of roles
belonging to either a user or group or the special types for all
users and all authenticated users.
:type entity_dict: dict
:param entity_dict: Dictionary full of data from an ACL lookup.
:rtype: :class:`_ACLEntity`
:returns: An Entity constructed from the dictionary.
"""
entity = entity_dict["entity"]
role = entity_dict["role"]
if entity == "allUsers":
entity = self.all()
elif entity == "allAuthenticatedUsers":
entity = self.all_authenticated()
elif "-" in entity:
entity_type, identifier = entity.split("-", 1)
entity = self.entity(entity_type=entity_type, identifier=identifier)
if not isinstance(entity, _ACLEntity):
raise ValueError("Invalid dictionary: %s" % entity_dict)
entity.grant(role)
return entity
|
python
|
def entity_from_dict(self, entity_dict):
"""Build an _ACLEntity object from a dictionary of data.
An entity is a mutable object that represents a list of roles
belonging to either a user or group or the special types for all
users and all authenticated users.
:type entity_dict: dict
:param entity_dict: Dictionary full of data from an ACL lookup.
:rtype: :class:`_ACLEntity`
:returns: An Entity constructed from the dictionary.
"""
entity = entity_dict["entity"]
role = entity_dict["role"]
if entity == "allUsers":
entity = self.all()
elif entity == "allAuthenticatedUsers":
entity = self.all_authenticated()
elif "-" in entity:
entity_type, identifier = entity.split("-", 1)
entity = self.entity(entity_type=entity_type, identifier=identifier)
if not isinstance(entity, _ACLEntity):
raise ValueError("Invalid dictionary: %s" % entity_dict)
entity.grant(role)
return entity
|
[
"def",
"entity_from_dict",
"(",
"self",
",",
"entity_dict",
")",
":",
"entity",
"=",
"entity_dict",
"[",
"\"entity\"",
"]",
"role",
"=",
"entity_dict",
"[",
"\"role\"",
"]",
"if",
"entity",
"==",
"\"allUsers\"",
":",
"entity",
"=",
"self",
".",
"all",
"(",
")",
"elif",
"entity",
"==",
"\"allAuthenticatedUsers\"",
":",
"entity",
"=",
"self",
".",
"all_authenticated",
"(",
")",
"elif",
"\"-\"",
"in",
"entity",
":",
"entity_type",
",",
"identifier",
"=",
"entity",
".",
"split",
"(",
"\"-\"",
",",
"1",
")",
"entity",
"=",
"self",
".",
"entity",
"(",
"entity_type",
"=",
"entity_type",
",",
"identifier",
"=",
"identifier",
")",
"if",
"not",
"isinstance",
"(",
"entity",
",",
"_ACLEntity",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid dictionary: %s\"",
"%",
"entity_dict",
")",
"entity",
".",
"grant",
"(",
"role",
")",
"return",
"entity"
] |
Build an _ACLEntity object from a dictionary of data.
An entity is a mutable object that represents a list of roles
belonging to either a user or group or the special types for all
users and all authenticated users.
:type entity_dict: dict
:param entity_dict: Dictionary full of data from an ACL lookup.
:rtype: :class:`_ACLEntity`
:returns: An Entity constructed from the dictionary.
|
[
"Build",
"an",
"_ACLEntity",
"object",
"from",
"a",
"dictionary",
"of",
"data",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L244-L274
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/acl.py
|
ACL.get_entity
|
def get_entity(self, entity, default=None):
"""Gets an entity object from the ACL.
:type entity: :class:`_ACLEntity` or string
:param entity: The entity to get lookup in the ACL.
:type default: anything
:param default: This value will be returned if the entity
doesn't exist.
:rtype: :class:`_ACLEntity`
:returns: The corresponding entity or the value provided
to ``default``.
"""
self._ensure_loaded()
return self.entities.get(str(entity), default)
|
python
|
def get_entity(self, entity, default=None):
"""Gets an entity object from the ACL.
:type entity: :class:`_ACLEntity` or string
:param entity: The entity to get lookup in the ACL.
:type default: anything
:param default: This value will be returned if the entity
doesn't exist.
:rtype: :class:`_ACLEntity`
:returns: The corresponding entity or the value provided
to ``default``.
"""
self._ensure_loaded()
return self.entities.get(str(entity), default)
|
[
"def",
"get_entity",
"(",
"self",
",",
"entity",
",",
"default",
"=",
"None",
")",
":",
"self",
".",
"_ensure_loaded",
"(",
")",
"return",
"self",
".",
"entities",
".",
"get",
"(",
"str",
"(",
"entity",
")",
",",
"default",
")"
] |
Gets an entity object from the ACL.
:type entity: :class:`_ACLEntity` or string
:param entity: The entity to get lookup in the ACL.
:type default: anything
:param default: This value will be returned if the entity
doesn't exist.
:rtype: :class:`_ACLEntity`
:returns: The corresponding entity or the value provided
to ``default``.
|
[
"Gets",
"an",
"entity",
"object",
"from",
"the",
"ACL",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L288-L303
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/acl.py
|
ACL.add_entity
|
def add_entity(self, entity):
"""Add an entity to the ACL.
:type entity: :class:`_ACLEntity`
:param entity: The entity to add to this ACL.
"""
self._ensure_loaded()
self.entities[str(entity)] = entity
|
python
|
def add_entity(self, entity):
"""Add an entity to the ACL.
:type entity: :class:`_ACLEntity`
:param entity: The entity to add to this ACL.
"""
self._ensure_loaded()
self.entities[str(entity)] = entity
|
[
"def",
"add_entity",
"(",
"self",
",",
"entity",
")",
":",
"self",
".",
"_ensure_loaded",
"(",
")",
"self",
".",
"entities",
"[",
"str",
"(",
"entity",
")",
"]",
"=",
"entity"
] |
Add an entity to the ACL.
:type entity: :class:`_ACLEntity`
:param entity: The entity to add to this ACL.
|
[
"Add",
"an",
"entity",
"to",
"the",
"ACL",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L305-L312
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/acl.py
|
ACL.entity
|
def entity(self, entity_type, identifier=None):
"""Factory method for creating an Entity.
If an entity with the same type and identifier already exists,
this will return a reference to that entity. If not, it will
create a new one and add it to the list of known entities for
this ACL.
:type entity_type: str
:param entity_type: The type of entity to create
(ie, ``user``, ``group``, etc)
:type identifier: str
:param identifier: The ID of the entity (if applicable).
This can be either an ID or an e-mail address.
:rtype: :class:`_ACLEntity`
:returns: A new Entity or a reference to an existing identical entity.
"""
entity = _ACLEntity(entity_type=entity_type, identifier=identifier)
if self.has_entity(entity):
entity = self.get_entity(entity)
else:
self.add_entity(entity)
return entity
|
python
|
def entity(self, entity_type, identifier=None):
"""Factory method for creating an Entity.
If an entity with the same type and identifier already exists,
this will return a reference to that entity. If not, it will
create a new one and add it to the list of known entities for
this ACL.
:type entity_type: str
:param entity_type: The type of entity to create
(ie, ``user``, ``group``, etc)
:type identifier: str
:param identifier: The ID of the entity (if applicable).
This can be either an ID or an e-mail address.
:rtype: :class:`_ACLEntity`
:returns: A new Entity or a reference to an existing identical entity.
"""
entity = _ACLEntity(entity_type=entity_type, identifier=identifier)
if self.has_entity(entity):
entity = self.get_entity(entity)
else:
self.add_entity(entity)
return entity
|
[
"def",
"entity",
"(",
"self",
",",
"entity_type",
",",
"identifier",
"=",
"None",
")",
":",
"entity",
"=",
"_ACLEntity",
"(",
"entity_type",
"=",
"entity_type",
",",
"identifier",
"=",
"identifier",
")",
"if",
"self",
".",
"has_entity",
"(",
"entity",
")",
":",
"entity",
"=",
"self",
".",
"get_entity",
"(",
"entity",
")",
"else",
":",
"self",
".",
"add_entity",
"(",
"entity",
")",
"return",
"entity"
] |
Factory method for creating an Entity.
If an entity with the same type and identifier already exists,
this will return a reference to that entity. If not, it will
create a new one and add it to the list of known entities for
this ACL.
:type entity_type: str
:param entity_type: The type of entity to create
(ie, ``user``, ``group``, etc)
:type identifier: str
:param identifier: The ID of the entity (if applicable).
This can be either an ID or an e-mail address.
:rtype: :class:`_ACLEntity`
:returns: A new Entity or a reference to an existing identical entity.
|
[
"Factory",
"method",
"for",
"creating",
"an",
"Entity",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L314-L338
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/acl.py
|
ACL.reload
|
def reload(self, client=None):
"""Reload the ACL data from Cloud Storage.
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the ACL's parent.
"""
path = self.reload_path
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
self.entities.clear()
found = client._connection.api_request(
method="GET", path=path, query_params=query_params
)
self.loaded = True
for entry in found.get("items", ()):
self.add_entity(self.entity_from_dict(entry))
|
python
|
def reload(self, client=None):
"""Reload the ACL data from Cloud Storage.
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the ACL's parent.
"""
path = self.reload_path
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
self.entities.clear()
found = client._connection.api_request(
method="GET", path=path, query_params=query_params
)
self.loaded = True
for entry in found.get("items", ()):
self.add_entity(self.entity_from_dict(entry))
|
[
"def",
"reload",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"reload_path",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"query_params",
"=",
"{",
"}",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"query_params",
"[",
"\"userProject\"",
"]",
"=",
"self",
".",
"user_project",
"self",
".",
"entities",
".",
"clear",
"(",
")",
"found",
"=",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"path",
",",
"query_params",
"=",
"query_params",
")",
"self",
".",
"loaded",
"=",
"True",
"for",
"entry",
"in",
"found",
".",
"get",
"(",
"\"items\"",
",",
"(",
")",
")",
":",
"self",
".",
"add_entity",
"(",
"self",
".",
"entity_from_dict",
"(",
"entry",
")",
")"
] |
Reload the ACL data from Cloud Storage.
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the ACL's parent.
|
[
"Reload",
"the",
"ACL",
"data",
"from",
"Cloud",
"Storage",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L418-L442
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/acl.py
|
ACL._save
|
def _save(self, acl, predefined, client):
"""Helper for :meth:`save` and :meth:`save_predefined`.
:type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.
:param acl: The ACL object to save. If left blank, this will save
current entries.
:type predefined: str
:param predefined:
(Optional) An identifier for a predefined ACL. Must be one of the
keys in :attr:`PREDEFINED_JSON_ACLS` If passed, `acl` must be None.
: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 ACL's parent.
"""
query_params = {"projection": "full"}
if predefined is not None:
acl = []
query_params[self._PREDEFINED_QUERY_PARAM] = predefined
if self.user_project is not None:
query_params["userProject"] = self.user_project
path = self.save_path
client = self._require_client(client)
result = client._connection.api_request(
method="PATCH",
path=path,
data={self._URL_PATH_ELEM: list(acl)},
query_params=query_params,
)
self.entities.clear()
for entry in result.get(self._URL_PATH_ELEM, ()):
self.add_entity(self.entity_from_dict(entry))
self.loaded = True
|
python
|
def _save(self, acl, predefined, client):
"""Helper for :meth:`save` and :meth:`save_predefined`.
:type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.
:param acl: The ACL object to save. If left blank, this will save
current entries.
:type predefined: str
:param predefined:
(Optional) An identifier for a predefined ACL. Must be one of the
keys in :attr:`PREDEFINED_JSON_ACLS` If passed, `acl` must be None.
: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 ACL's parent.
"""
query_params = {"projection": "full"}
if predefined is not None:
acl = []
query_params[self._PREDEFINED_QUERY_PARAM] = predefined
if self.user_project is not None:
query_params["userProject"] = self.user_project
path = self.save_path
client = self._require_client(client)
result = client._connection.api_request(
method="PATCH",
path=path,
data={self._URL_PATH_ELEM: list(acl)},
query_params=query_params,
)
self.entities.clear()
for entry in result.get(self._URL_PATH_ELEM, ()):
self.add_entity(self.entity_from_dict(entry))
self.loaded = True
|
[
"def",
"_save",
"(",
"self",
",",
"acl",
",",
"predefined",
",",
"client",
")",
":",
"query_params",
"=",
"{",
"\"projection\"",
":",
"\"full\"",
"}",
"if",
"predefined",
"is",
"not",
"None",
":",
"acl",
"=",
"[",
"]",
"query_params",
"[",
"self",
".",
"_PREDEFINED_QUERY_PARAM",
"]",
"=",
"predefined",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"query_params",
"[",
"\"userProject\"",
"]",
"=",
"self",
".",
"user_project",
"path",
"=",
"self",
".",
"save_path",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"result",
"=",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"PATCH\"",
",",
"path",
"=",
"path",
",",
"data",
"=",
"{",
"self",
".",
"_URL_PATH_ELEM",
":",
"list",
"(",
"acl",
")",
"}",
",",
"query_params",
"=",
"query_params",
",",
")",
"self",
".",
"entities",
".",
"clear",
"(",
")",
"for",
"entry",
"in",
"result",
".",
"get",
"(",
"self",
".",
"_URL_PATH_ELEM",
",",
"(",
")",
")",
":",
"self",
".",
"add_entity",
"(",
"self",
".",
"entity_from_dict",
"(",
"entry",
")",
")",
"self",
".",
"loaded",
"=",
"True"
] |
Helper for :meth:`save` and :meth:`save_predefined`.
:type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.
:param acl: The ACL object to save. If left blank, this will save
current entries.
:type predefined: str
:param predefined:
(Optional) An identifier for a predefined ACL. Must be one of the
keys in :attr:`PREDEFINED_JSON_ACLS` If passed, `acl` must be None.
: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 ACL's parent.
|
[
"Helper",
"for",
":",
"meth",
":",
"save",
"and",
":",
"meth",
":",
"save_predefined",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L444-L481
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/acl.py
|
ACL.save
|
def save(self, acl=None, client=None):
"""Save this ACL for the current bucket.
If :attr:`user_project` is set, bills the API request to that project.
:type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.
:param acl: The ACL object to save. If left blank, this will save
current entries.
: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 ACL's parent.
"""
if acl is None:
acl = self
save_to_backend = acl.loaded
else:
save_to_backend = True
if save_to_backend:
self._save(acl, None, client)
|
python
|
def save(self, acl=None, client=None):
"""Save this ACL for the current bucket.
If :attr:`user_project` is set, bills the API request to that project.
:type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.
:param acl: The ACL object to save. If left blank, this will save
current entries.
: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 ACL's parent.
"""
if acl is None:
acl = self
save_to_backend = acl.loaded
else:
save_to_backend = True
if save_to_backend:
self._save(acl, None, client)
|
[
"def",
"save",
"(",
"self",
",",
"acl",
"=",
"None",
",",
"client",
"=",
"None",
")",
":",
"if",
"acl",
"is",
"None",
":",
"acl",
"=",
"self",
"save_to_backend",
"=",
"acl",
".",
"loaded",
"else",
":",
"save_to_backend",
"=",
"True",
"if",
"save_to_backend",
":",
"self",
".",
"_save",
"(",
"acl",
",",
"None",
",",
"client",
")"
] |
Save this ACL for the current bucket.
If :attr:`user_project` is set, bills the API request to that project.
:type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.
:param acl: The ACL object to save. If left blank, this will save
current entries.
: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 ACL's parent.
|
[
"Save",
"this",
"ACL",
"for",
"the",
"current",
"bucket",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L483-L504
|
train
|
googleapis/google-cloud-python
|
storage/google/cloud/storage/acl.py
|
ACL.save_predefined
|
def save_predefined(self, predefined, client=None):
"""Save this ACL for the current bucket using a predefined ACL.
If :attr:`user_project` is set, bills the API request to that project.
:type predefined: str
:param predefined: An identifier for a predefined ACL. Must be one
of the keys in :attr:`PREDEFINED_JSON_ACLS`
or :attr:`PREDEFINED_XML_ACLS` (which will be
aliased to the corresponding JSON name).
If passed, `acl` must be None.
: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 ACL's parent.
"""
predefined = self.validate_predefined(predefined)
self._save(None, predefined, client)
|
python
|
def save_predefined(self, predefined, client=None):
"""Save this ACL for the current bucket using a predefined ACL.
If :attr:`user_project` is set, bills the API request to that project.
:type predefined: str
:param predefined: An identifier for a predefined ACL. Must be one
of the keys in :attr:`PREDEFINED_JSON_ACLS`
or :attr:`PREDEFINED_XML_ACLS` (which will be
aliased to the corresponding JSON name).
If passed, `acl` must be None.
: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 ACL's parent.
"""
predefined = self.validate_predefined(predefined)
self._save(None, predefined, client)
|
[
"def",
"save_predefined",
"(",
"self",
",",
"predefined",
",",
"client",
"=",
"None",
")",
":",
"predefined",
"=",
"self",
".",
"validate_predefined",
"(",
"predefined",
")",
"self",
".",
"_save",
"(",
"None",
",",
"predefined",
",",
"client",
")"
] |
Save this ACL for the current bucket using a predefined ACL.
If :attr:`user_project` is set, bills the API request to that project.
:type predefined: str
:param predefined: An identifier for a predefined ACL. Must be one
of the keys in :attr:`PREDEFINED_JSON_ACLS`
or :attr:`PREDEFINED_XML_ACLS` (which will be
aliased to the corresponding JSON name).
If passed, `acl` must be None.
: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 ACL's parent.
|
[
"Save",
"this",
"ACL",
"for",
"the",
"current",
"bucket",
"using",
"a",
"predefined",
"ACL",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L506-L524
|
train
|
googleapis/google-cloud-python
|
irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py
|
IncidentServiceClient.incident_path
|
def incident_path(cls, project, incident):
"""Return a fully-qualified incident string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}",
project=project,
incident=incident,
)
|
python
|
def incident_path(cls, project, incident):
"""Return a fully-qualified incident string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}",
project=project,
incident=incident,
)
|
[
"def",
"incident_path",
"(",
"cls",
",",
"project",
",",
"incident",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/incidents/{incident}\"",
",",
"project",
"=",
"project",
",",
"incident",
"=",
"incident",
",",
")"
] |
Return a fully-qualified incident string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"incident",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L82-L88
|
train
|
googleapis/google-cloud-python
|
irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py
|
IncidentServiceClient.annotation_path
|
def annotation_path(cls, project, incident, annotation):
"""Return a fully-qualified annotation string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/annotations/{annotation}",
project=project,
incident=incident,
annotation=annotation,
)
|
python
|
def annotation_path(cls, project, incident, annotation):
"""Return a fully-qualified annotation string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/annotations/{annotation}",
project=project,
incident=incident,
annotation=annotation,
)
|
[
"def",
"annotation_path",
"(",
"cls",
",",
"project",
",",
"incident",
",",
"annotation",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/incidents/{incident}/annotations/{annotation}\"",
",",
"project",
"=",
"project",
",",
"incident",
"=",
"incident",
",",
"annotation",
"=",
"annotation",
",",
")"
] |
Return a fully-qualified annotation string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"annotation",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L91-L98
|
train
|
googleapis/google-cloud-python
|
irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py
|
IncidentServiceClient.artifact_path
|
def artifact_path(cls, project, incident, artifact):
"""Return a fully-qualified artifact string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/artifacts/{artifact}",
project=project,
incident=incident,
artifact=artifact,
)
|
python
|
def artifact_path(cls, project, incident, artifact):
"""Return a fully-qualified artifact string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/artifacts/{artifact}",
project=project,
incident=incident,
artifact=artifact,
)
|
[
"def",
"artifact_path",
"(",
"cls",
",",
"project",
",",
"incident",
",",
"artifact",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/incidents/{incident}/artifacts/{artifact}\"",
",",
"project",
"=",
"project",
",",
"incident",
"=",
"incident",
",",
"artifact",
"=",
"artifact",
",",
")"
] |
Return a fully-qualified artifact string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"artifact",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L101-L108
|
train
|
googleapis/google-cloud-python
|
irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py
|
IncidentServiceClient.role_assignment_path
|
def role_assignment_path(cls, project, incident, role_assignment):
"""Return a fully-qualified role_assignment string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/roleAssignments/{role_assignment}",
project=project,
incident=incident,
role_assignment=role_assignment,
)
|
python
|
def role_assignment_path(cls, project, incident, role_assignment):
"""Return a fully-qualified role_assignment string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/roleAssignments/{role_assignment}",
project=project,
incident=incident,
role_assignment=role_assignment,
)
|
[
"def",
"role_assignment_path",
"(",
"cls",
",",
"project",
",",
"incident",
",",
"role_assignment",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/incidents/{incident}/roleAssignments/{role_assignment}\"",
",",
"project",
"=",
"project",
",",
"incident",
"=",
"incident",
",",
"role_assignment",
"=",
"role_assignment",
",",
")"
] |
Return a fully-qualified role_assignment string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"role_assignment",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L111-L118
|
train
|
googleapis/google-cloud-python
|
irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py
|
IncidentServiceClient.subscription_path
|
def subscription_path(cls, project, incident, subscription):
"""Return a fully-qualified subscription string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/subscriptions/{subscription}",
project=project,
incident=incident,
subscription=subscription,
)
|
python
|
def subscription_path(cls, project, incident, subscription):
"""Return a fully-qualified subscription string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/subscriptions/{subscription}",
project=project,
incident=incident,
subscription=subscription,
)
|
[
"def",
"subscription_path",
"(",
"cls",
",",
"project",
",",
"incident",
",",
"subscription",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/incidents/{incident}/subscriptions/{subscription}\"",
",",
"project",
"=",
"project",
",",
"incident",
"=",
"incident",
",",
"subscription",
"=",
"subscription",
",",
")"
] |
Return a fully-qualified subscription string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"subscription",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L121-L128
|
train
|
googleapis/google-cloud-python
|
irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py
|
IncidentServiceClient.tag_path
|
def tag_path(cls, project, incident, tag):
"""Return a fully-qualified tag string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/tags/{tag}",
project=project,
incident=incident,
tag=tag,
)
|
python
|
def tag_path(cls, project, incident, tag):
"""Return a fully-qualified tag string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/tags/{tag}",
project=project,
incident=incident,
tag=tag,
)
|
[
"def",
"tag_path",
"(",
"cls",
",",
"project",
",",
"incident",
",",
"tag",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/incidents/{incident}/tags/{tag}\"",
",",
"project",
"=",
"project",
",",
"incident",
"=",
"incident",
",",
"tag",
"=",
"tag",
",",
")"
] |
Return a fully-qualified tag string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"tag",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L131-L138
|
train
|
googleapis/google-cloud-python
|
irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py
|
IncidentServiceClient.signal_path
|
def signal_path(cls, project, signal):
"""Return a fully-qualified signal string."""
return google.api_core.path_template.expand(
"projects/{project}/signals/{signal}", project=project, signal=signal
)
|
python
|
def signal_path(cls, project, signal):
"""Return a fully-qualified signal string."""
return google.api_core.path_template.expand(
"projects/{project}/signals/{signal}", project=project, signal=signal
)
|
[
"def",
"signal_path",
"(",
"cls",
",",
"project",
",",
"signal",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/signals/{signal}\"",
",",
"project",
"=",
"project",
",",
"signal",
"=",
"signal",
")"
] |
Return a fully-qualified signal string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"signal",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L141-L145
|
train
|
googleapis/google-cloud-python
|
irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py
|
IncidentServiceClient.create_annotation
|
def create_annotation(
self,
parent,
annotation,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates an annotation on an existing incident. Only 'text/plain' and
'text/markdown' annotations can be created via this method.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')
>>>
>>> # TODO: Initialize `annotation`:
>>> annotation = {}
>>>
>>> response = client.create_annotation(parent, annotation)
Args:
parent (str): Resource name of the incident, for example,
"projects/{project_id}/incidents/{incident_id}".
annotation (Union[dict, ~google.cloud.irm_v1alpha2.types.Annotation]): Only annotation.content is an input argument.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Annotation`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.irm_v1alpha2.types.Annotation` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "create_annotation" not in self._inner_api_calls:
self._inner_api_calls[
"create_annotation"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_annotation,
default_retry=self._method_configs["CreateAnnotation"].retry,
default_timeout=self._method_configs["CreateAnnotation"].timeout,
client_info=self._client_info,
)
request = incidents_service_pb2.CreateAnnotationRequest(
parent=parent, annotation=annotation
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["create_annotation"](
request, retry=retry, timeout=timeout, metadata=metadata
)
|
python
|
def create_annotation(
self,
parent,
annotation,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates an annotation on an existing incident. Only 'text/plain' and
'text/markdown' annotations can be created via this method.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')
>>>
>>> # TODO: Initialize `annotation`:
>>> annotation = {}
>>>
>>> response = client.create_annotation(parent, annotation)
Args:
parent (str): Resource name of the incident, for example,
"projects/{project_id}/incidents/{incident_id}".
annotation (Union[dict, ~google.cloud.irm_v1alpha2.types.Annotation]): Only annotation.content is an input argument.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Annotation`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.irm_v1alpha2.types.Annotation` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "create_annotation" not in self._inner_api_calls:
self._inner_api_calls[
"create_annotation"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_annotation,
default_retry=self._method_configs["CreateAnnotation"].retry,
default_timeout=self._method_configs["CreateAnnotation"].timeout,
client_info=self._client_info,
)
request = incidents_service_pb2.CreateAnnotationRequest(
parent=parent, annotation=annotation
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["create_annotation"](
request, retry=retry, timeout=timeout, metadata=metadata
)
|
[
"def",
"create_annotation",
"(",
"self",
",",
"parent",
",",
"annotation",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"create_annotation\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"create_annotation\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_annotation",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateAnnotation\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateAnnotation\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"incidents_service_pb2",
".",
"CreateAnnotationRequest",
"(",
"parent",
"=",
"parent",
",",
"annotation",
"=",
"annotation",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"parent\"",
",",
"parent",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"create_annotation\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] |
Creates an annotation on an existing incident. Only 'text/plain' and
'text/markdown' annotations can be created via this method.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')
>>>
>>> # TODO: Initialize `annotation`:
>>> annotation = {}
>>>
>>> response = client.create_annotation(parent, annotation)
Args:
parent (str): Resource name of the incident, for example,
"projects/{project_id}/incidents/{incident_id}".
annotation (Union[dict, ~google.cloud.irm_v1alpha2.types.Annotation]): Only annotation.content is an input argument.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Annotation`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.irm_v1alpha2.types.Annotation` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
|
[
"Creates",
"an",
"annotation",
"on",
"an",
"existing",
"incident",
".",
"Only",
"text",
"/",
"plain",
"and",
"text",
"/",
"markdown",
"annotations",
"can",
"be",
"created",
"via",
"this",
"method",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L755-L834
|
train
|
googleapis/google-cloud-python
|
irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py
|
IncidentServiceClient.escalate_incident
|
def escalate_incident(
self,
incident,
update_mask=None,
subscriptions=None,
tags=None,
roles=None,
artifacts=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Escalates an incident.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> # TODO: Initialize `incident`:
>>> incident = {}
>>>
>>> response = client.escalate_incident(incident)
Args:
incident (Union[dict, ~google.cloud.irm_v1alpha2.types.Incident]): The incident to escalate with the new values.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Incident`
update_mask (Union[dict, ~google.cloud.irm_v1alpha2.types.FieldMask]): List of fields that should be updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.FieldMask`
subscriptions (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Subscription]]): Subscriptions to add or update. Existing subscriptions with the same
channel and address as a subscription in the list will be updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Subscription`
tags (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Tag]]): Tags to add. Tags identical to existing tags will be ignored.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Tag`
roles (list[Union[dict, ~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment]]): Roles to add or update. Existing roles with the same type (and title,
for TYPE_OTHER roles) will be updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment`
artifacts (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Artifact]]): Artifacts to add. All artifacts are added without checking for duplicates.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Artifact`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.irm_v1alpha2.types.EscalateIncidentResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "escalate_incident" not in self._inner_api_calls:
self._inner_api_calls[
"escalate_incident"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.escalate_incident,
default_retry=self._method_configs["EscalateIncident"].retry,
default_timeout=self._method_configs["EscalateIncident"].timeout,
client_info=self._client_info,
)
request = incidents_service_pb2.EscalateIncidentRequest(
incident=incident,
update_mask=update_mask,
subscriptions=subscriptions,
tags=tags,
roles=roles,
artifacts=artifacts,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("incident.name", incident.name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["escalate_incident"](
request, retry=retry, timeout=timeout, metadata=metadata
)
|
python
|
def escalate_incident(
self,
incident,
update_mask=None,
subscriptions=None,
tags=None,
roles=None,
artifacts=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Escalates an incident.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> # TODO: Initialize `incident`:
>>> incident = {}
>>>
>>> response = client.escalate_incident(incident)
Args:
incident (Union[dict, ~google.cloud.irm_v1alpha2.types.Incident]): The incident to escalate with the new values.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Incident`
update_mask (Union[dict, ~google.cloud.irm_v1alpha2.types.FieldMask]): List of fields that should be updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.FieldMask`
subscriptions (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Subscription]]): Subscriptions to add or update. Existing subscriptions with the same
channel and address as a subscription in the list will be updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Subscription`
tags (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Tag]]): Tags to add. Tags identical to existing tags will be ignored.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Tag`
roles (list[Union[dict, ~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment]]): Roles to add or update. Existing roles with the same type (and title,
for TYPE_OTHER roles) will be updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment`
artifacts (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Artifact]]): Artifacts to add. All artifacts are added without checking for duplicates.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Artifact`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.irm_v1alpha2.types.EscalateIncidentResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "escalate_incident" not in self._inner_api_calls:
self._inner_api_calls[
"escalate_incident"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.escalate_incident,
default_retry=self._method_configs["EscalateIncident"].retry,
default_timeout=self._method_configs["EscalateIncident"].timeout,
client_info=self._client_info,
)
request = incidents_service_pb2.EscalateIncidentRequest(
incident=incident,
update_mask=update_mask,
subscriptions=subscriptions,
tags=tags,
roles=roles,
artifacts=artifacts,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("incident.name", incident.name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["escalate_incident"](
request, retry=retry, timeout=timeout, metadata=metadata
)
|
[
"def",
"escalate_incident",
"(",
"self",
",",
"incident",
",",
"update_mask",
"=",
"None",
",",
"subscriptions",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"artifacts",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"escalate_incident\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"escalate_incident\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"escalate_incident",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"EscalateIncident\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"EscalateIncident\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"incidents_service_pb2",
".",
"EscalateIncidentRequest",
"(",
"incident",
"=",
"incident",
",",
"update_mask",
"=",
"update_mask",
",",
"subscriptions",
"=",
"subscriptions",
",",
"tags",
"=",
"tags",
",",
"roles",
"=",
"roles",
",",
"artifacts",
"=",
"artifacts",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"incident.name\"",
",",
"incident",
".",
"name",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"escalate_incident\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] |
Escalates an incident.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> # TODO: Initialize `incident`:
>>> incident = {}
>>>
>>> response = client.escalate_incident(incident)
Args:
incident (Union[dict, ~google.cloud.irm_v1alpha2.types.Incident]): The incident to escalate with the new values.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Incident`
update_mask (Union[dict, ~google.cloud.irm_v1alpha2.types.FieldMask]): List of fields that should be updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.FieldMask`
subscriptions (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Subscription]]): Subscriptions to add or update. Existing subscriptions with the same
channel and address as a subscription in the list will be updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Subscription`
tags (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Tag]]): Tags to add. Tags identical to existing tags will be ignored.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Tag`
roles (list[Union[dict, ~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment]]): Roles to add or update. Existing roles with the same type (and title,
for TYPE_OTHER roles) will be updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment`
artifacts (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Artifact]]): Artifacts to add. All artifacts are added without checking for duplicates.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Artifact`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.irm_v1alpha2.types.EscalateIncidentResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
|
[
"Escalates",
"an",
"incident",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L1527-L1632
|
train
|
googleapis/google-cloud-python
|
irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py
|
IncidentServiceClient.send_shift_handoff
|
def send_shift_handoff(
self,
parent,
recipients,
subject,
cc=None,
notes_content_type=None,
notes_content=None,
incidents=None,
preview_only=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Sends a summary of the shift for oncall handoff.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `recipients`:
>>> recipients = []
>>>
>>> # TODO: Initialize `subject`:
>>> subject = ''
>>>
>>> response = client.send_shift_handoff(parent, recipients, subject)
Args:
parent (str): The resource name of the Stackdriver project that the handoff is being
sent from. for example, ``projects/{project_id}``
recipients (list[str]): Email addresses of the recipients of the handoff, for example,
"user@example.com". Must contain at least one entry.
subject (str): The subject of the email. Required.
cc (list[str]): Email addresses that should be CC'd on the handoff. Optional.
notes_content_type (str): Content type string, for example, 'text/plain' or 'text/html'.
notes_content (str): Additional notes to be included in the handoff. Optional.
incidents (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Incident]]): The set of incidents that should be included in the handoff. Optional.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Incident`
preview_only (bool): If set to true a ShiftHandoffResponse will be returned but the handoff
will not actually be sent.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.irm_v1alpha2.types.SendShiftHandoffResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "send_shift_handoff" not in self._inner_api_calls:
self._inner_api_calls[
"send_shift_handoff"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.send_shift_handoff,
default_retry=self._method_configs["SendShiftHandoff"].retry,
default_timeout=self._method_configs["SendShiftHandoff"].timeout,
client_info=self._client_info,
)
request = incidents_service_pb2.SendShiftHandoffRequest(
parent=parent,
recipients=recipients,
subject=subject,
cc=cc,
notes_content_type=notes_content_type,
notes_content=notes_content,
incidents=incidents,
preview_only=preview_only,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["send_shift_handoff"](
request, retry=retry, timeout=timeout, metadata=metadata
)
|
python
|
def send_shift_handoff(
self,
parent,
recipients,
subject,
cc=None,
notes_content_type=None,
notes_content=None,
incidents=None,
preview_only=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Sends a summary of the shift for oncall handoff.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `recipients`:
>>> recipients = []
>>>
>>> # TODO: Initialize `subject`:
>>> subject = ''
>>>
>>> response = client.send_shift_handoff(parent, recipients, subject)
Args:
parent (str): The resource name of the Stackdriver project that the handoff is being
sent from. for example, ``projects/{project_id}``
recipients (list[str]): Email addresses of the recipients of the handoff, for example,
"user@example.com". Must contain at least one entry.
subject (str): The subject of the email. Required.
cc (list[str]): Email addresses that should be CC'd on the handoff. Optional.
notes_content_type (str): Content type string, for example, 'text/plain' or 'text/html'.
notes_content (str): Additional notes to be included in the handoff. Optional.
incidents (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Incident]]): The set of incidents that should be included in the handoff. Optional.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Incident`
preview_only (bool): If set to true a ShiftHandoffResponse will be returned but the handoff
will not actually be sent.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.irm_v1alpha2.types.SendShiftHandoffResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "send_shift_handoff" not in self._inner_api_calls:
self._inner_api_calls[
"send_shift_handoff"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.send_shift_handoff,
default_retry=self._method_configs["SendShiftHandoff"].retry,
default_timeout=self._method_configs["SendShiftHandoff"].timeout,
client_info=self._client_info,
)
request = incidents_service_pb2.SendShiftHandoffRequest(
parent=parent,
recipients=recipients,
subject=subject,
cc=cc,
notes_content_type=notes_content_type,
notes_content=notes_content,
incidents=incidents,
preview_only=preview_only,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["send_shift_handoff"](
request, retry=retry, timeout=timeout, metadata=metadata
)
|
[
"def",
"send_shift_handoff",
"(",
"self",
",",
"parent",
",",
"recipients",
",",
"subject",
",",
"cc",
"=",
"None",
",",
"notes_content_type",
"=",
"None",
",",
"notes_content",
"=",
"None",
",",
"incidents",
"=",
"None",
",",
"preview_only",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"send_shift_handoff\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"send_shift_handoff\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"send_shift_handoff",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"SendShiftHandoff\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"SendShiftHandoff\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"incidents_service_pb2",
".",
"SendShiftHandoffRequest",
"(",
"parent",
"=",
"parent",
",",
"recipients",
"=",
"recipients",
",",
"subject",
"=",
"subject",
",",
"cc",
"=",
"cc",
",",
"notes_content_type",
"=",
"notes_content_type",
",",
"notes_content",
"=",
"notes_content",
",",
"incidents",
"=",
"incidents",
",",
"preview_only",
"=",
"preview_only",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"parent\"",
",",
"parent",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"send_shift_handoff\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] |
Sends a summary of the shift for oncall handoff.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `recipients`:
>>> recipients = []
>>>
>>> # TODO: Initialize `subject`:
>>> subject = ''
>>>
>>> response = client.send_shift_handoff(parent, recipients, subject)
Args:
parent (str): The resource name of the Stackdriver project that the handoff is being
sent from. for example, ``projects/{project_id}``
recipients (list[str]): Email addresses of the recipients of the handoff, for example,
"user@example.com". Must contain at least one entry.
subject (str): The subject of the email. Required.
cc (list[str]): Email addresses that should be CC'd on the handoff. Optional.
notes_content_type (str): Content type string, for example, 'text/plain' or 'text/html'.
notes_content (str): Additional notes to be included in the handoff. Optional.
incidents (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Incident]]): The set of incidents that should be included in the handoff. Optional.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.irm_v1alpha2.types.Incident`
preview_only (bool): If set to true a ShiftHandoffResponse will be returned but the handoff
will not actually be sent.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.irm_v1alpha2.types.SendShiftHandoffResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
|
[
"Sends",
"a",
"summary",
"of",
"the",
"shift",
"for",
"oncall",
"handoff",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L1964-L2066
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/policy.py
|
Policy.bigtable_admins
|
def bigtable_admins(self):
"""Access to bigtable.admin role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_admins_policy]
:end-before: [END bigtable_admins_policy]
"""
result = set()
for member in self._bindings.get(BIGTABLE_ADMIN_ROLE, ()):
result.add(member)
return frozenset(result)
|
python
|
def bigtable_admins(self):
"""Access to bigtable.admin role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_admins_policy]
:end-before: [END bigtable_admins_policy]
"""
result = set()
for member in self._bindings.get(BIGTABLE_ADMIN_ROLE, ()):
result.add(member)
return frozenset(result)
|
[
"def",
"bigtable_admins",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"member",
"in",
"self",
".",
"_bindings",
".",
"get",
"(",
"BIGTABLE_ADMIN_ROLE",
",",
"(",
")",
")",
":",
"result",
".",
"add",
"(",
"member",
")",
"return",
"frozenset",
"(",
"result",
")"
] |
Access to bigtable.admin role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_admins_policy]
:end-before: [END bigtable_admins_policy]
|
[
"Access",
"to",
"bigtable",
".",
"admin",
"role",
"memebers"
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/policy.py#L83-L95
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/policy.py
|
Policy.bigtable_readers
|
def bigtable_readers(self):
"""Access to bigtable.reader role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_readers_policy]
:end-before: [END bigtable_readers_policy]
"""
result = set()
for member in self._bindings.get(BIGTABLE_READER_ROLE, ()):
result.add(member)
return frozenset(result)
|
python
|
def bigtable_readers(self):
"""Access to bigtable.reader role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_readers_policy]
:end-before: [END bigtable_readers_policy]
"""
result = set()
for member in self._bindings.get(BIGTABLE_READER_ROLE, ()):
result.add(member)
return frozenset(result)
|
[
"def",
"bigtable_readers",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"member",
"in",
"self",
".",
"_bindings",
".",
"get",
"(",
"BIGTABLE_READER_ROLE",
",",
"(",
")",
")",
":",
"result",
".",
"add",
"(",
"member",
")",
"return",
"frozenset",
"(",
"result",
")"
] |
Access to bigtable.reader role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_readers_policy]
:end-before: [END bigtable_readers_policy]
|
[
"Access",
"to",
"bigtable",
".",
"reader",
"role",
"memebers"
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/policy.py#L98-L110
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/policy.py
|
Policy.bigtable_users
|
def bigtable_users(self):
"""Access to bigtable.user role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_users_policy]
:end-before: [END bigtable_users_policy]
"""
result = set()
for member in self._bindings.get(BIGTABLE_USER_ROLE, ()):
result.add(member)
return frozenset(result)
|
python
|
def bigtable_users(self):
"""Access to bigtable.user role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_users_policy]
:end-before: [END bigtable_users_policy]
"""
result = set()
for member in self._bindings.get(BIGTABLE_USER_ROLE, ()):
result.add(member)
return frozenset(result)
|
[
"def",
"bigtable_users",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"member",
"in",
"self",
".",
"_bindings",
".",
"get",
"(",
"BIGTABLE_USER_ROLE",
",",
"(",
")",
")",
":",
"result",
".",
"add",
"(",
"member",
")",
"return",
"frozenset",
"(",
"result",
")"
] |
Access to bigtable.user role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_users_policy]
:end-before: [END bigtable_users_policy]
|
[
"Access",
"to",
"bigtable",
".",
"user",
"role",
"memebers"
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/policy.py#L113-L125
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/policy.py
|
Policy.bigtable_viewers
|
def bigtable_viewers(self):
"""Access to bigtable.viewer role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_viewers_policy]
:end-before: [END bigtable_viewers_policy]
"""
result = set()
for member in self._bindings.get(BIGTABLE_VIEWER_ROLE, ()):
result.add(member)
return frozenset(result)
|
python
|
def bigtable_viewers(self):
"""Access to bigtable.viewer role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_viewers_policy]
:end-before: [END bigtable_viewers_policy]
"""
result = set()
for member in self._bindings.get(BIGTABLE_VIEWER_ROLE, ()):
result.add(member)
return frozenset(result)
|
[
"def",
"bigtable_viewers",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"member",
"in",
"self",
".",
"_bindings",
".",
"get",
"(",
"BIGTABLE_VIEWER_ROLE",
",",
"(",
")",
")",
":",
"result",
".",
"add",
"(",
"member",
")",
"return",
"frozenset",
"(",
"result",
")"
] |
Access to bigtable.viewer role memebers
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_viewers_policy]
:end-before: [END bigtable_viewers_policy]
|
[
"Access",
"to",
"bigtable",
".",
"viewer",
"role",
"memebers"
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/policy.py#L128-L140
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/policy.py
|
Policy.from_pb
|
def from_pb(cls, policy_pb):
"""Factory: create a policy from a protobuf message.
Args:
policy_pb (google.iam.policy_pb2.Policy): message returned by
``get_iam_policy`` gRPC API.
Returns:
:class:`Policy`: the parsed policy
"""
policy = cls(policy_pb.etag, policy_pb.version)
for binding in policy_pb.bindings:
policy[binding.role] = sorted(binding.members)
return policy
|
python
|
def from_pb(cls, policy_pb):
"""Factory: create a policy from a protobuf message.
Args:
policy_pb (google.iam.policy_pb2.Policy): message returned by
``get_iam_policy`` gRPC API.
Returns:
:class:`Policy`: the parsed policy
"""
policy = cls(policy_pb.etag, policy_pb.version)
for binding in policy_pb.bindings:
policy[binding.role] = sorted(binding.members)
return policy
|
[
"def",
"from_pb",
"(",
"cls",
",",
"policy_pb",
")",
":",
"policy",
"=",
"cls",
"(",
"policy_pb",
".",
"etag",
",",
"policy_pb",
".",
"version",
")",
"for",
"binding",
"in",
"policy_pb",
".",
"bindings",
":",
"policy",
"[",
"binding",
".",
"role",
"]",
"=",
"sorted",
"(",
"binding",
".",
"members",
")",
"return",
"policy"
] |
Factory: create a policy from a protobuf message.
Args:
policy_pb (google.iam.policy_pb2.Policy): message returned by
``get_iam_policy`` gRPC API.
Returns:
:class:`Policy`: the parsed policy
|
[
"Factory",
":",
"create",
"a",
"policy",
"from",
"a",
"protobuf",
"message",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/policy.py#L143-L158
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/policy.py
|
Policy.to_pb
|
def to_pb(self):
"""Render a protobuf message.
Returns:
google.iam.policy_pb2.Policy: a message to be passed to the
``set_iam_policy`` gRPC API.
"""
return policy_pb2.Policy(
etag=self.etag,
version=self.version or 0,
bindings=[
policy_pb2.Binding(role=role, members=sorted(self[role]))
for role in self
],
)
|
python
|
def to_pb(self):
"""Render a protobuf message.
Returns:
google.iam.policy_pb2.Policy: a message to be passed to the
``set_iam_policy`` gRPC API.
"""
return policy_pb2.Policy(
etag=self.etag,
version=self.version or 0,
bindings=[
policy_pb2.Binding(role=role, members=sorted(self[role]))
for role in self
],
)
|
[
"def",
"to_pb",
"(",
"self",
")",
":",
"return",
"policy_pb2",
".",
"Policy",
"(",
"etag",
"=",
"self",
".",
"etag",
",",
"version",
"=",
"self",
".",
"version",
"or",
"0",
",",
"bindings",
"=",
"[",
"policy_pb2",
".",
"Binding",
"(",
"role",
"=",
"role",
",",
"members",
"=",
"sorted",
"(",
"self",
"[",
"role",
"]",
")",
")",
"for",
"role",
"in",
"self",
"]",
",",
")"
] |
Render a protobuf message.
Returns:
google.iam.policy_pb2.Policy: a message to be passed to the
``set_iam_policy`` gRPC API.
|
[
"Render",
"a",
"protobuf",
"message",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/policy.py#L160-L175
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/policy.py
|
Policy.from_api_repr
|
def from_api_repr(cls, resource):
"""Factory: create a policy from a JSON resource.
Overrides the base class version to store :attr:`etag` as bytes.
Args:
resource (dict): JSON policy resource returned by the
``getIamPolicy`` REST API.
Returns:
:class:`Policy`: the parsed policy
"""
etag = resource.get("etag")
if etag is not None:
resource = resource.copy()
resource["etag"] = base64.b64decode(etag.encode("ascii"))
return super(Policy, cls).from_api_repr(resource)
|
python
|
def from_api_repr(cls, resource):
"""Factory: create a policy from a JSON resource.
Overrides the base class version to store :attr:`etag` as bytes.
Args:
resource (dict): JSON policy resource returned by the
``getIamPolicy`` REST API.
Returns:
:class:`Policy`: the parsed policy
"""
etag = resource.get("etag")
if etag is not None:
resource = resource.copy()
resource["etag"] = base64.b64decode(etag.encode("ascii"))
return super(Policy, cls).from_api_repr(resource)
|
[
"def",
"from_api_repr",
"(",
"cls",
",",
"resource",
")",
":",
"etag",
"=",
"resource",
".",
"get",
"(",
"\"etag\"",
")",
"if",
"etag",
"is",
"not",
"None",
":",
"resource",
"=",
"resource",
".",
"copy",
"(",
")",
"resource",
"[",
"\"etag\"",
"]",
"=",
"base64",
".",
"b64decode",
"(",
"etag",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
"return",
"super",
"(",
"Policy",
",",
"cls",
")",
".",
"from_api_repr",
"(",
"resource",
")"
] |
Factory: create a policy from a JSON resource.
Overrides the base class version to store :attr:`etag` as bytes.
Args:
resource (dict): JSON policy resource returned by the
``getIamPolicy`` REST API.
Returns:
:class:`Policy`: the parsed policy
|
[
"Factory",
":",
"create",
"a",
"policy",
"from",
"a",
"JSON",
"resource",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/policy.py#L178-L196
|
train
|
googleapis/google-cloud-python
|
bigtable/google/cloud/bigtable/policy.py
|
Policy.to_api_repr
|
def to_api_repr(self):
"""Render a JSON policy resource.
Overrides the base class version to convert :attr:`etag` from bytes
to JSON-compatible base64-encoded text.
Returns:
dict: a JSON resource to be passed to the
``setIamPolicy`` REST API.
"""
resource = super(Policy, self).to_api_repr()
if self.etag is not None:
resource["etag"] = base64.b64encode(self.etag).decode("ascii")
return resource
|
python
|
def to_api_repr(self):
"""Render a JSON policy resource.
Overrides the base class version to convert :attr:`etag` from bytes
to JSON-compatible base64-encoded text.
Returns:
dict: a JSON resource to be passed to the
``setIamPolicy`` REST API.
"""
resource = super(Policy, self).to_api_repr()
if self.etag is not None:
resource["etag"] = base64.b64encode(self.etag).decode("ascii")
return resource
|
[
"def",
"to_api_repr",
"(",
"self",
")",
":",
"resource",
"=",
"super",
"(",
"Policy",
",",
"self",
")",
".",
"to_api_repr",
"(",
")",
"if",
"self",
".",
"etag",
"is",
"not",
"None",
":",
"resource",
"[",
"\"etag\"",
"]",
"=",
"base64",
".",
"b64encode",
"(",
"self",
".",
"etag",
")",
".",
"decode",
"(",
"\"ascii\"",
")",
"return",
"resource"
] |
Render a JSON policy resource.
Overrides the base class version to convert :attr:`etag` from bytes
to JSON-compatible base64-encoded text.
Returns:
dict: a JSON resource to be passed to the
``setIamPolicy`` REST API.
|
[
"Render",
"a",
"JSON",
"policy",
"resource",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/policy.py#L198-L213
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
_check_ddl_statements
|
def _check_ddl_statements(value):
"""Validate DDL Statements used to define database schema.
See
https://cloud.google.com/spanner/docs/data-definition-language
:type value: list of string
:param value: DDL statements, excluding the 'CREATE DATABSE' statement
:rtype: tuple
:returns: tuple of validated DDL statement strings.
:raises ValueError:
if elements in ``value`` are not strings, or if ``value`` contains
a ``CREATE DATABASE`` statement.
"""
if not all(isinstance(line, six.string_types) for line in value):
raise ValueError("Pass a list of strings")
if any("create database" in line.lower() for line in value):
raise ValueError("Do not pass a 'CREATE DATABASE' statement")
return tuple(value)
|
python
|
def _check_ddl_statements(value):
"""Validate DDL Statements used to define database schema.
See
https://cloud.google.com/spanner/docs/data-definition-language
:type value: list of string
:param value: DDL statements, excluding the 'CREATE DATABSE' statement
:rtype: tuple
:returns: tuple of validated DDL statement strings.
:raises ValueError:
if elements in ``value`` are not strings, or if ``value`` contains
a ``CREATE DATABASE`` statement.
"""
if not all(isinstance(line, six.string_types) for line in value):
raise ValueError("Pass a list of strings")
if any("create database" in line.lower() for line in value):
raise ValueError("Do not pass a 'CREATE DATABASE' statement")
return tuple(value)
|
[
"def",
"_check_ddl_statements",
"(",
"value",
")",
":",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"line",
",",
"six",
".",
"string_types",
")",
"for",
"line",
"in",
"value",
")",
":",
"raise",
"ValueError",
"(",
"\"Pass a list of strings\"",
")",
"if",
"any",
"(",
"\"create database\"",
"in",
"line",
".",
"lower",
"(",
")",
"for",
"line",
"in",
"value",
")",
":",
"raise",
"ValueError",
"(",
"\"Do not pass a 'CREATE DATABASE' statement\"",
")",
"return",
"tuple",
"(",
"value",
")"
] |
Validate DDL Statements used to define database schema.
See
https://cloud.google.com/spanner/docs/data-definition-language
:type value: list of string
:param value: DDL statements, excluding the 'CREATE DATABSE' statement
:rtype: tuple
:returns: tuple of validated DDL statement strings.
:raises ValueError:
if elements in ``value`` are not strings, or if ``value`` contains
a ``CREATE DATABASE`` statement.
|
[
"Validate",
"DDL",
"Statements",
"used",
"to",
"define",
"database",
"schema",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L790-L811
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
Database.from_pb
|
def from_pb(cls, database_pb, instance, pool=None):
"""Creates an instance of this class from a protobuf.
:type database_pb:
:class:`google.spanner.v2.spanner_instance_admin_pb2.Instance`
:param database_pb: A instance protobuf object.
:type instance: :class:`~google.cloud.spanner_v1.instance.Instance`
:param instance: The instance that owns the database.
:type pool: concrete subclass of
:class:`~google.cloud.spanner_v1.pool.AbstractSessionPool`.
:param pool: (Optional) session pool to be used by database.
:rtype: :class:`Database`
:returns: The database parsed from the protobuf response.
:raises ValueError:
if the instance name does not match the expected format
or if the parsed project ID does not match the project ID
on the instance's client, or if the parsed instance ID does
not match the instance's ID.
"""
match = _DATABASE_NAME_RE.match(database_pb.name)
if match is None:
raise ValueError(
"Database protobuf name was not in the " "expected format.",
database_pb.name,
)
if match.group("project") != instance._client.project:
raise ValueError(
"Project ID on database does not match the "
"project ID on the instance's client"
)
instance_id = match.group("instance_id")
if instance_id != instance.instance_id:
raise ValueError(
"Instance ID on database does not match the "
"Instance ID on the instance"
)
database_id = match.group("database_id")
return cls(database_id, instance, pool=pool)
|
python
|
def from_pb(cls, database_pb, instance, pool=None):
"""Creates an instance of this class from a protobuf.
:type database_pb:
:class:`google.spanner.v2.spanner_instance_admin_pb2.Instance`
:param database_pb: A instance protobuf object.
:type instance: :class:`~google.cloud.spanner_v1.instance.Instance`
:param instance: The instance that owns the database.
:type pool: concrete subclass of
:class:`~google.cloud.spanner_v1.pool.AbstractSessionPool`.
:param pool: (Optional) session pool to be used by database.
:rtype: :class:`Database`
:returns: The database parsed from the protobuf response.
:raises ValueError:
if the instance name does not match the expected format
or if the parsed project ID does not match the project ID
on the instance's client, or if the parsed instance ID does
not match the instance's ID.
"""
match = _DATABASE_NAME_RE.match(database_pb.name)
if match is None:
raise ValueError(
"Database protobuf name was not in the " "expected format.",
database_pb.name,
)
if match.group("project") != instance._client.project:
raise ValueError(
"Project ID on database does not match the "
"project ID on the instance's client"
)
instance_id = match.group("instance_id")
if instance_id != instance.instance_id:
raise ValueError(
"Instance ID on database does not match the "
"Instance ID on the instance"
)
database_id = match.group("database_id")
return cls(database_id, instance, pool=pool)
|
[
"def",
"from_pb",
"(",
"cls",
",",
"database_pb",
",",
"instance",
",",
"pool",
"=",
"None",
")",
":",
"match",
"=",
"_DATABASE_NAME_RE",
".",
"match",
"(",
"database_pb",
".",
"name",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Database protobuf name was not in the \"",
"\"expected format.\"",
",",
"database_pb",
".",
"name",
",",
")",
"if",
"match",
".",
"group",
"(",
"\"project\"",
")",
"!=",
"instance",
".",
"_client",
".",
"project",
":",
"raise",
"ValueError",
"(",
"\"Project ID on database does not match the \"",
"\"project ID on the instance's client\"",
")",
"instance_id",
"=",
"match",
".",
"group",
"(",
"\"instance_id\"",
")",
"if",
"instance_id",
"!=",
"instance",
".",
"instance_id",
":",
"raise",
"ValueError",
"(",
"\"Instance ID on database does not match the \"",
"\"Instance ID on the instance\"",
")",
"database_id",
"=",
"match",
".",
"group",
"(",
"\"database_id\"",
")",
"return",
"cls",
"(",
"database_id",
",",
"instance",
",",
"pool",
"=",
"pool",
")"
] |
Creates an instance of this class from a protobuf.
:type database_pb:
:class:`google.spanner.v2.spanner_instance_admin_pb2.Instance`
:param database_pb: A instance protobuf object.
:type instance: :class:`~google.cloud.spanner_v1.instance.Instance`
:param instance: The instance that owns the database.
:type pool: concrete subclass of
:class:`~google.cloud.spanner_v1.pool.AbstractSessionPool`.
:param pool: (Optional) session pool to be used by database.
:rtype: :class:`Database`
:returns: The database parsed from the protobuf response.
:raises ValueError:
if the instance name does not match the expected format
or if the parsed project ID does not match the project ID
on the instance's client, or if the parsed instance ID does
not match the instance's ID.
|
[
"Creates",
"an",
"instance",
"of",
"this",
"class",
"from",
"a",
"protobuf",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L102-L143
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
Database.spanner_api
|
def spanner_api(self):
"""Helper for session-related API calls."""
if self._spanner_api is None:
credentials = self._instance._client.credentials
if isinstance(credentials, google.auth.credentials.Scoped):
credentials = credentials.with_scopes((SPANNER_DATA_SCOPE,))
self._spanner_api = SpannerClient(
credentials=credentials, client_info=_CLIENT_INFO
)
return self._spanner_api
|
python
|
def spanner_api(self):
"""Helper for session-related API calls."""
if self._spanner_api is None:
credentials = self._instance._client.credentials
if isinstance(credentials, google.auth.credentials.Scoped):
credentials = credentials.with_scopes((SPANNER_DATA_SCOPE,))
self._spanner_api = SpannerClient(
credentials=credentials, client_info=_CLIENT_INFO
)
return self._spanner_api
|
[
"def",
"spanner_api",
"(",
"self",
")",
":",
"if",
"self",
".",
"_spanner_api",
"is",
"None",
":",
"credentials",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"credentials",
"if",
"isinstance",
"(",
"credentials",
",",
"google",
".",
"auth",
".",
"credentials",
".",
"Scoped",
")",
":",
"credentials",
"=",
"credentials",
".",
"with_scopes",
"(",
"(",
"SPANNER_DATA_SCOPE",
",",
")",
")",
"self",
".",
"_spanner_api",
"=",
"SpannerClient",
"(",
"credentials",
"=",
"credentials",
",",
"client_info",
"=",
"_CLIENT_INFO",
")",
"return",
"self",
".",
"_spanner_api"
] |
Helper for session-related API calls.
|
[
"Helper",
"for",
"session",
"-",
"related",
"API",
"calls",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L176-L185
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
Database.create
|
def create(self):
"""Create this database within its instance
Inclues any configured schema assigned to :attr:`ddl_statements`.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase
:rtype: :class:`~google.api_core.operation.Operation`
:returns: a future used to poll the status of the create request
:raises Conflict: if the database already exists
:raises NotFound: if the instance owning the database does not exist
"""
api = self._instance._client.database_admin_api
metadata = _metadata_with_prefix(self.name)
db_name = self.database_id
if "-" in db_name:
db_name = "`%s`" % (db_name,)
future = api.create_database(
parent=self._instance.name,
create_statement="CREATE DATABASE %s" % (db_name,),
extra_statements=list(self._ddl_statements),
metadata=metadata,
)
return future
|
python
|
def create(self):
"""Create this database within its instance
Inclues any configured schema assigned to :attr:`ddl_statements`.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase
:rtype: :class:`~google.api_core.operation.Operation`
:returns: a future used to poll the status of the create request
:raises Conflict: if the database already exists
:raises NotFound: if the instance owning the database does not exist
"""
api = self._instance._client.database_admin_api
metadata = _metadata_with_prefix(self.name)
db_name = self.database_id
if "-" in db_name:
db_name = "`%s`" % (db_name,)
future = api.create_database(
parent=self._instance.name,
create_statement="CREATE DATABASE %s" % (db_name,),
extra_statements=list(self._ddl_statements),
metadata=metadata,
)
return future
|
[
"def",
"create",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"database_admin_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"db_name",
"=",
"self",
".",
"database_id",
"if",
"\"-\"",
"in",
"db_name",
":",
"db_name",
"=",
"\"`%s`\"",
"%",
"(",
"db_name",
",",
")",
"future",
"=",
"api",
".",
"create_database",
"(",
"parent",
"=",
"self",
".",
"_instance",
".",
"name",
",",
"create_statement",
"=",
"\"CREATE DATABASE %s\"",
"%",
"(",
"db_name",
",",
")",
",",
"extra_statements",
"=",
"list",
"(",
"self",
".",
"_ddl_statements",
")",
",",
"metadata",
"=",
"metadata",
",",
")",
"return",
"future"
] |
Create this database within its instance
Inclues any configured schema assigned to :attr:`ddl_statements`.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase
:rtype: :class:`~google.api_core.operation.Operation`
:returns: a future used to poll the status of the create request
:raises Conflict: if the database already exists
:raises NotFound: if the instance owning the database does not exist
|
[
"Create",
"this",
"database",
"within",
"its",
"instance"
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L197-L222
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
Database.exists
|
def exists(self):
"""Test whether this database exists.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDDL
:rtype: bool
:returns: True if the database exists, else false.
"""
api = self._instance._client.database_admin_api
metadata = _metadata_with_prefix(self.name)
try:
api.get_database_ddl(self.name, metadata=metadata)
except NotFound:
return False
return True
|
python
|
def exists(self):
"""Test whether this database exists.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDDL
:rtype: bool
:returns: True if the database exists, else false.
"""
api = self._instance._client.database_admin_api
metadata = _metadata_with_prefix(self.name)
try:
api.get_database_ddl(self.name, metadata=metadata)
except NotFound:
return False
return True
|
[
"def",
"exists",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"database_admin_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"try",
":",
"api",
".",
"get_database_ddl",
"(",
"self",
".",
"name",
",",
"metadata",
"=",
"metadata",
")",
"except",
"NotFound",
":",
"return",
"False",
"return",
"True"
] |
Test whether this database exists.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDDL
:rtype: bool
:returns: True if the database exists, else false.
|
[
"Test",
"whether",
"this",
"database",
"exists",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L224-L240
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
Database.reload
|
def reload(self):
"""Reload this database.
Refresh any configured schema into :attr:`ddl_statements`.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDDL
:raises NotFound: if the database does not exist
"""
api = self._instance._client.database_admin_api
metadata = _metadata_with_prefix(self.name)
response = api.get_database_ddl(self.name, metadata=metadata)
self._ddl_statements = tuple(response.statements)
|
python
|
def reload(self):
"""Reload this database.
Refresh any configured schema into :attr:`ddl_statements`.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDDL
:raises NotFound: if the database does not exist
"""
api = self._instance._client.database_admin_api
metadata = _metadata_with_prefix(self.name)
response = api.get_database_ddl(self.name, metadata=metadata)
self._ddl_statements = tuple(response.statements)
|
[
"def",
"reload",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"database_admin_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"response",
"=",
"api",
".",
"get_database_ddl",
"(",
"self",
".",
"name",
",",
"metadata",
"=",
"metadata",
")",
"self",
".",
"_ddl_statements",
"=",
"tuple",
"(",
"response",
".",
"statements",
")"
] |
Reload this database.
Refresh any configured schema into :attr:`ddl_statements`.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDDL
:raises NotFound: if the database does not exist
|
[
"Reload",
"this",
"database",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L242-L255
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
Database.update_ddl
|
def update_ddl(self, ddl_statements, operation_id=""):
"""Update DDL for this database.
Apply any configured schema from :attr:`ddl_statements`.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabase
:type ddl_statements: Sequence[str]
:param ddl_statements: a list of DDL statements to use on this database
:type operation_id: str
:param operation_id: (optional) a string ID for the long-running operation
:rtype: :class:`google.api_core.operation.Operation`
:returns: an operation instance
:raises NotFound: if the database does not exist
"""
client = self._instance._client
api = client.database_admin_api
metadata = _metadata_with_prefix(self.name)
future = api.update_database_ddl(
self.name, ddl_statements, operation_id=operation_id, metadata=metadata
)
return future
|
python
|
def update_ddl(self, ddl_statements, operation_id=""):
"""Update DDL for this database.
Apply any configured schema from :attr:`ddl_statements`.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabase
:type ddl_statements: Sequence[str]
:param ddl_statements: a list of DDL statements to use on this database
:type operation_id: str
:param operation_id: (optional) a string ID for the long-running operation
:rtype: :class:`google.api_core.operation.Operation`
:returns: an operation instance
:raises NotFound: if the database does not exist
"""
client = self._instance._client
api = client.database_admin_api
metadata = _metadata_with_prefix(self.name)
future = api.update_database_ddl(
self.name, ddl_statements, operation_id=operation_id, metadata=metadata
)
return future
|
[
"def",
"update_ddl",
"(",
"self",
",",
"ddl_statements",
",",
"operation_id",
"=",
"\"\"",
")",
":",
"client",
"=",
"self",
".",
"_instance",
".",
"_client",
"api",
"=",
"client",
".",
"database_admin_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"future",
"=",
"api",
".",
"update_database_ddl",
"(",
"self",
".",
"name",
",",
"ddl_statements",
",",
"operation_id",
"=",
"operation_id",
",",
"metadata",
"=",
"metadata",
")",
"return",
"future"
] |
Update DDL for this database.
Apply any configured schema from :attr:`ddl_statements`.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabase
:type ddl_statements: Sequence[str]
:param ddl_statements: a list of DDL statements to use on this database
:type operation_id: str
:param operation_id: (optional) a string ID for the long-running operation
:rtype: :class:`google.api_core.operation.Operation`
:returns: an operation instance
:raises NotFound: if the database does not exist
|
[
"Update",
"DDL",
"for",
"this",
"database",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L257-L281
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
Database.drop
|
def drop(self):
"""Drop this database.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase
"""
api = self._instance._client.database_admin_api
metadata = _metadata_with_prefix(self.name)
api.drop_database(self.name, metadata=metadata)
|
python
|
def drop(self):
"""Drop this database.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase
"""
api = self._instance._client.database_admin_api
metadata = _metadata_with_prefix(self.name)
api.drop_database(self.name, metadata=metadata)
|
[
"def",
"drop",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"database_admin_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"api",
".",
"drop_database",
"(",
"self",
".",
"name",
",",
"metadata",
"=",
"metadata",
")"
] |
Drop this database.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase
|
[
"Drop",
"this",
"database",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L283-L291
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
Database.execute_partitioned_dml
|
def execute_partitioned_dml(self, dml, params=None, param_types=None):
"""Execute a partitionable DML statement.
:type dml: str
:param dml: DML statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``dml``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:rtype: int
:returns: Count of rows affected by the DML statement.
"""
if params is not None:
if param_types is None:
raise ValueError("Specify 'param_types' when passing 'params'.")
params_pb = Struct(
fields={key: _make_value_pb(value) for key, value in params.items()}
)
else:
params_pb = None
api = self.spanner_api
txn_options = TransactionOptions(
partitioned_dml=TransactionOptions.PartitionedDml()
)
metadata = _metadata_with_prefix(self.name)
with SessionCheckout(self._pool) as session:
txn = api.begin_transaction(session.name, txn_options, metadata=metadata)
txn_selector = TransactionSelector(id=txn.id)
restart = functools.partial(
api.execute_streaming_sql,
session.name,
dml,
transaction=txn_selector,
params=params_pb,
param_types=param_types,
metadata=metadata,
)
iterator = _restart_on_unavailable(restart)
result_set = StreamedResultSet(iterator)
list(result_set) # consume all partials
return result_set.stats.row_count_lower_bound
|
python
|
def execute_partitioned_dml(self, dml, params=None, param_types=None):
"""Execute a partitionable DML statement.
:type dml: str
:param dml: DML statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``dml``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:rtype: int
:returns: Count of rows affected by the DML statement.
"""
if params is not None:
if param_types is None:
raise ValueError("Specify 'param_types' when passing 'params'.")
params_pb = Struct(
fields={key: _make_value_pb(value) for key, value in params.items()}
)
else:
params_pb = None
api = self.spanner_api
txn_options = TransactionOptions(
partitioned_dml=TransactionOptions.PartitionedDml()
)
metadata = _metadata_with_prefix(self.name)
with SessionCheckout(self._pool) as session:
txn = api.begin_transaction(session.name, txn_options, metadata=metadata)
txn_selector = TransactionSelector(id=txn.id)
restart = functools.partial(
api.execute_streaming_sql,
session.name,
dml,
transaction=txn_selector,
params=params_pb,
param_types=param_types,
metadata=metadata,
)
iterator = _restart_on_unavailable(restart)
result_set = StreamedResultSet(iterator)
list(result_set) # consume all partials
return result_set.stats.row_count_lower_bound
|
[
"def",
"execute_partitioned_dml",
"(",
"self",
",",
"dml",
",",
"params",
"=",
"None",
",",
"param_types",
"=",
"None",
")",
":",
"if",
"params",
"is",
"not",
"None",
":",
"if",
"param_types",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Specify 'param_types' when passing 'params'.\"",
")",
"params_pb",
"=",
"Struct",
"(",
"fields",
"=",
"{",
"key",
":",
"_make_value_pb",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
"}",
")",
"else",
":",
"params_pb",
"=",
"None",
"api",
"=",
"self",
".",
"spanner_api",
"txn_options",
"=",
"TransactionOptions",
"(",
"partitioned_dml",
"=",
"TransactionOptions",
".",
"PartitionedDml",
"(",
")",
")",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"with",
"SessionCheckout",
"(",
"self",
".",
"_pool",
")",
"as",
"session",
":",
"txn",
"=",
"api",
".",
"begin_transaction",
"(",
"session",
".",
"name",
",",
"txn_options",
",",
"metadata",
"=",
"metadata",
")",
"txn_selector",
"=",
"TransactionSelector",
"(",
"id",
"=",
"txn",
".",
"id",
")",
"restart",
"=",
"functools",
".",
"partial",
"(",
"api",
".",
"execute_streaming_sql",
",",
"session",
".",
"name",
",",
"dml",
",",
"transaction",
"=",
"txn_selector",
",",
"params",
"=",
"params_pb",
",",
"param_types",
"=",
"param_types",
",",
"metadata",
"=",
"metadata",
",",
")",
"iterator",
"=",
"_restart_on_unavailable",
"(",
"restart",
")",
"result_set",
"=",
"StreamedResultSet",
"(",
"iterator",
")",
"list",
"(",
"result_set",
")",
"# consume all partials",
"return",
"result_set",
".",
"stats",
".",
"row_count_lower_bound"
] |
Execute a partitionable DML statement.
:type dml: str
:param dml: DML statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``dml``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:rtype: int
:returns: Count of rows affected by the DML statement.
|
[
"Execute",
"a",
"partitionable",
"DML",
"statement",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L293-L349
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
Database.batch_snapshot
|
def batch_snapshot(self, read_timestamp=None, exact_staleness=None):
"""Return an object which wraps a batch read / query.
:type read_timestamp: :class:`datetime.datetime`
:param read_timestamp: Execute all reads at the given timestamp.
:type exact_staleness: :class:`datetime.timedelta`
:param exact_staleness: Execute all reads at a timestamp that is
``exact_staleness`` old.
:rtype: :class:`~google.cloud.spanner_v1.database.BatchSnapshot`
:returns: new wrapper
"""
return BatchSnapshot(
self, read_timestamp=read_timestamp, exact_staleness=exact_staleness
)
|
python
|
def batch_snapshot(self, read_timestamp=None, exact_staleness=None):
"""Return an object which wraps a batch read / query.
:type read_timestamp: :class:`datetime.datetime`
:param read_timestamp: Execute all reads at the given timestamp.
:type exact_staleness: :class:`datetime.timedelta`
:param exact_staleness: Execute all reads at a timestamp that is
``exact_staleness`` old.
:rtype: :class:`~google.cloud.spanner_v1.database.BatchSnapshot`
:returns: new wrapper
"""
return BatchSnapshot(
self, read_timestamp=read_timestamp, exact_staleness=exact_staleness
)
|
[
"def",
"batch_snapshot",
"(",
"self",
",",
"read_timestamp",
"=",
"None",
",",
"exact_staleness",
"=",
"None",
")",
":",
"return",
"BatchSnapshot",
"(",
"self",
",",
"read_timestamp",
"=",
"read_timestamp",
",",
"exact_staleness",
"=",
"exact_staleness",
")"
] |
Return an object which wraps a batch read / query.
:type read_timestamp: :class:`datetime.datetime`
:param read_timestamp: Execute all reads at the given timestamp.
:type exact_staleness: :class:`datetime.timedelta`
:param exact_staleness: Execute all reads at a timestamp that is
``exact_staleness`` old.
:rtype: :class:`~google.cloud.spanner_v1.database.BatchSnapshot`
:returns: new wrapper
|
[
"Return",
"an",
"object",
"which",
"wraps",
"a",
"batch",
"read",
"/",
"query",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L392-L407
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
Database.run_in_transaction
|
def run_in_transaction(self, func, *args, **kw):
"""Perform a unit of work in a transaction, retrying on abort.
:type func: callable
:param func: takes a required positional argument, the transaction,
and additional positional / keyword arguments as supplied
by the caller.
:type args: tuple
:param args: additional positional arguments to be passed to ``func``.
:type kw: dict
:param kw: optional keyword arguments to be passed to ``func``.
If passed, "timeout_secs" will be removed and used to
override the default timeout.
:rtype: :class:`datetime.datetime`
:returns: timestamp of committed transaction
"""
# Sanity check: Is there a transaction already running?
# If there is, then raise a red flag. Otherwise, mark that this one
# is running.
if getattr(self._local, "transaction_running", False):
raise RuntimeError("Spanner does not support nested transactions.")
self._local.transaction_running = True
# Check out a session and run the function in a transaction; once
# done, flip the sanity check bit back.
try:
with SessionCheckout(self._pool) as session:
return session.run_in_transaction(func, *args, **kw)
finally:
self._local.transaction_running = False
|
python
|
def run_in_transaction(self, func, *args, **kw):
"""Perform a unit of work in a transaction, retrying on abort.
:type func: callable
:param func: takes a required positional argument, the transaction,
and additional positional / keyword arguments as supplied
by the caller.
:type args: tuple
:param args: additional positional arguments to be passed to ``func``.
:type kw: dict
:param kw: optional keyword arguments to be passed to ``func``.
If passed, "timeout_secs" will be removed and used to
override the default timeout.
:rtype: :class:`datetime.datetime`
:returns: timestamp of committed transaction
"""
# Sanity check: Is there a transaction already running?
# If there is, then raise a red flag. Otherwise, mark that this one
# is running.
if getattr(self._local, "transaction_running", False):
raise RuntimeError("Spanner does not support nested transactions.")
self._local.transaction_running = True
# Check out a session and run the function in a transaction; once
# done, flip the sanity check bit back.
try:
with SessionCheckout(self._pool) as session:
return session.run_in_transaction(func, *args, **kw)
finally:
self._local.transaction_running = False
|
[
"def",
"run_in_transaction",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Sanity check: Is there a transaction already running?",
"# If there is, then raise a red flag. Otherwise, mark that this one",
"# is running.",
"if",
"getattr",
"(",
"self",
".",
"_local",
",",
"\"transaction_running\"",
",",
"False",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Spanner does not support nested transactions.\"",
")",
"self",
".",
"_local",
".",
"transaction_running",
"=",
"True",
"# Check out a session and run the function in a transaction; once",
"# done, flip the sanity check bit back.",
"try",
":",
"with",
"SessionCheckout",
"(",
"self",
".",
"_pool",
")",
"as",
"session",
":",
"return",
"session",
".",
"run_in_transaction",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"finally",
":",
"self",
".",
"_local",
".",
"transaction_running",
"=",
"False"
] |
Perform a unit of work in a transaction, retrying on abort.
:type func: callable
:param func: takes a required positional argument, the transaction,
and additional positional / keyword arguments as supplied
by the caller.
:type args: tuple
:param args: additional positional arguments to be passed to ``func``.
:type kw: dict
:param kw: optional keyword arguments to be passed to ``func``.
If passed, "timeout_secs" will be removed and used to
override the default timeout.
:rtype: :class:`datetime.datetime`
:returns: timestamp of committed transaction
|
[
"Perform",
"a",
"unit",
"of",
"work",
"in",
"a",
"transaction",
"retrying",
"on",
"abort",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L409-L441
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
BatchSnapshot.from_dict
|
def from_dict(cls, database, mapping):
"""Reconstruct an instance from a mapping.
:type database: :class:`~google.cloud.spanner.database.Database`
:param database: database to use
:type mapping: mapping
:param mapping: serialized state of the instance
:rtype: :class:`BatchSnapshot`
"""
instance = cls(database)
session = instance._session = database.session()
session._session_id = mapping["session_id"]
snapshot = instance._snapshot = session.snapshot()
snapshot._transaction_id = mapping["transaction_id"]
return instance
|
python
|
def from_dict(cls, database, mapping):
"""Reconstruct an instance from a mapping.
:type database: :class:`~google.cloud.spanner.database.Database`
:param database: database to use
:type mapping: mapping
:param mapping: serialized state of the instance
:rtype: :class:`BatchSnapshot`
"""
instance = cls(database)
session = instance._session = database.session()
session._session_id = mapping["session_id"]
snapshot = instance._snapshot = session.snapshot()
snapshot._transaction_id = mapping["transaction_id"]
return instance
|
[
"def",
"from_dict",
"(",
"cls",
",",
"database",
",",
"mapping",
")",
":",
"instance",
"=",
"cls",
"(",
"database",
")",
"session",
"=",
"instance",
".",
"_session",
"=",
"database",
".",
"session",
"(",
")",
"session",
".",
"_session_id",
"=",
"mapping",
"[",
"\"session_id\"",
"]",
"snapshot",
"=",
"instance",
".",
"_snapshot",
"=",
"session",
".",
"snapshot",
"(",
")",
"snapshot",
".",
"_transaction_id",
"=",
"mapping",
"[",
"\"transaction_id\"",
"]",
"return",
"instance"
] |
Reconstruct an instance from a mapping.
:type database: :class:`~google.cloud.spanner.database.Database`
:param database: database to use
:type mapping: mapping
:param mapping: serialized state of the instance
:rtype: :class:`BatchSnapshot`
|
[
"Reconstruct",
"an",
"instance",
"from",
"a",
"mapping",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L531-L547
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
BatchSnapshot.to_dict
|
def to_dict(self):
"""Return state as a dictionary.
Result can be used to serialize the instance and reconstitute
it later using :meth:`from_dict`.
:rtype: dict
"""
session = self._get_session()
snapshot = self._get_snapshot()
return {
"session_id": session._session_id,
"transaction_id": snapshot._transaction_id,
}
|
python
|
def to_dict(self):
"""Return state as a dictionary.
Result can be used to serialize the instance and reconstitute
it later using :meth:`from_dict`.
:rtype: dict
"""
session = self._get_session()
snapshot = self._get_snapshot()
return {
"session_id": session._session_id,
"transaction_id": snapshot._transaction_id,
}
|
[
"def",
"to_dict",
"(",
"self",
")",
":",
"session",
"=",
"self",
".",
"_get_session",
"(",
")",
"snapshot",
"=",
"self",
".",
"_get_snapshot",
"(",
")",
"return",
"{",
"\"session_id\"",
":",
"session",
".",
"_session_id",
",",
"\"transaction_id\"",
":",
"snapshot",
".",
"_transaction_id",
",",
"}"
] |
Return state as a dictionary.
Result can be used to serialize the instance and reconstitute
it later using :meth:`from_dict`.
:rtype: dict
|
[
"Return",
"state",
"as",
"a",
"dictionary",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L549-L562
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
BatchSnapshot._get_session
|
def _get_session(self):
"""Create session as needed.
.. note::
Caller is responsible for cleaning up the session after
all partitions have been processed.
"""
if self._session is None:
session = self._session = self._database.session()
session.create()
return self._session
|
python
|
def _get_session(self):
"""Create session as needed.
.. note::
Caller is responsible for cleaning up the session after
all partitions have been processed.
"""
if self._session is None:
session = self._session = self._database.session()
session.create()
return self._session
|
[
"def",
"_get_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"is",
"None",
":",
"session",
"=",
"self",
".",
"_session",
"=",
"self",
".",
"_database",
".",
"session",
"(",
")",
"session",
".",
"create",
"(",
")",
"return",
"self",
".",
"_session"
] |
Create session as needed.
.. note::
Caller is responsible for cleaning up the session after
all partitions have been processed.
|
[
"Create",
"session",
"as",
"needed",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L564-L575
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
BatchSnapshot._get_snapshot
|
def _get_snapshot(self):
"""Create snapshot if needed."""
if self._snapshot is None:
self._snapshot = self._get_session().snapshot(
read_timestamp=self._read_timestamp,
exact_staleness=self._exact_staleness,
multi_use=True,
)
self._snapshot.begin()
return self._snapshot
|
python
|
def _get_snapshot(self):
"""Create snapshot if needed."""
if self._snapshot is None:
self._snapshot = self._get_session().snapshot(
read_timestamp=self._read_timestamp,
exact_staleness=self._exact_staleness,
multi_use=True,
)
self._snapshot.begin()
return self._snapshot
|
[
"def",
"_get_snapshot",
"(",
"self",
")",
":",
"if",
"self",
".",
"_snapshot",
"is",
"None",
":",
"self",
".",
"_snapshot",
"=",
"self",
".",
"_get_session",
"(",
")",
".",
"snapshot",
"(",
"read_timestamp",
"=",
"self",
".",
"_read_timestamp",
",",
"exact_staleness",
"=",
"self",
".",
"_exact_staleness",
",",
"multi_use",
"=",
"True",
",",
")",
"self",
".",
"_snapshot",
".",
"begin",
"(",
")",
"return",
"self",
".",
"_snapshot"
] |
Create snapshot if needed.
|
[
"Create",
"snapshot",
"if",
"needed",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L577-L586
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
BatchSnapshot.generate_read_batches
|
def generate_read_batches(
self,
table,
columns,
keyset,
index="",
partition_size_bytes=None,
max_partitions=None,
):
"""Start a partitioned batch read operation.
Uses the ``PartitionRead`` API request to initiate the partitioned
read. Returns a list of batch information needed to perform the
actual reads.
:type table: str
:param table: name of the table from which to fetch data
:type columns: list of str
:param columns: names of columns to be retrieved
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
:param keyset: keys / ranges identifying rows to be retrieved
:type index: str
:param index: (Optional) name of index to use, rather than the
table's primary key
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of dict
:returns:
mappings of information used peform actual partitioned reads via
:meth:`process_read_batch`.
"""
partitions = self._get_snapshot().partition_read(
table=table,
columns=columns,
keyset=keyset,
index=index,
partition_size_bytes=partition_size_bytes,
max_partitions=max_partitions,
)
read_info = {
"table": table,
"columns": columns,
"keyset": keyset._to_dict(),
"index": index,
}
for partition in partitions:
yield {"partition": partition, "read": read_info.copy()}
|
python
|
def generate_read_batches(
self,
table,
columns,
keyset,
index="",
partition_size_bytes=None,
max_partitions=None,
):
"""Start a partitioned batch read operation.
Uses the ``PartitionRead`` API request to initiate the partitioned
read. Returns a list of batch information needed to perform the
actual reads.
:type table: str
:param table: name of the table from which to fetch data
:type columns: list of str
:param columns: names of columns to be retrieved
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
:param keyset: keys / ranges identifying rows to be retrieved
:type index: str
:param index: (Optional) name of index to use, rather than the
table's primary key
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of dict
:returns:
mappings of information used peform actual partitioned reads via
:meth:`process_read_batch`.
"""
partitions = self._get_snapshot().partition_read(
table=table,
columns=columns,
keyset=keyset,
index=index,
partition_size_bytes=partition_size_bytes,
max_partitions=max_partitions,
)
read_info = {
"table": table,
"columns": columns,
"keyset": keyset._to_dict(),
"index": index,
}
for partition in partitions:
yield {"partition": partition, "read": read_info.copy()}
|
[
"def",
"generate_read_batches",
"(",
"self",
",",
"table",
",",
"columns",
",",
"keyset",
",",
"index",
"=",
"\"\"",
",",
"partition_size_bytes",
"=",
"None",
",",
"max_partitions",
"=",
"None",
",",
")",
":",
"partitions",
"=",
"self",
".",
"_get_snapshot",
"(",
")",
".",
"partition_read",
"(",
"table",
"=",
"table",
",",
"columns",
"=",
"columns",
",",
"keyset",
"=",
"keyset",
",",
"index",
"=",
"index",
",",
"partition_size_bytes",
"=",
"partition_size_bytes",
",",
"max_partitions",
"=",
"max_partitions",
",",
")",
"read_info",
"=",
"{",
"\"table\"",
":",
"table",
",",
"\"columns\"",
":",
"columns",
",",
"\"keyset\"",
":",
"keyset",
".",
"_to_dict",
"(",
")",
",",
"\"index\"",
":",
"index",
",",
"}",
"for",
"partition",
"in",
"partitions",
":",
"yield",
"{",
"\"partition\"",
":",
"partition",
",",
"\"read\"",
":",
"read_info",
".",
"copy",
"(",
")",
"}"
] |
Start a partitioned batch read operation.
Uses the ``PartitionRead`` API request to initiate the partitioned
read. Returns a list of batch information needed to perform the
actual reads.
:type table: str
:param table: name of the table from which to fetch data
:type columns: list of str
:param columns: names of columns to be retrieved
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
:param keyset: keys / ranges identifying rows to be retrieved
:type index: str
:param index: (Optional) name of index to use, rather than the
table's primary key
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of dict
:returns:
mappings of information used peform actual partitioned reads via
:meth:`process_read_batch`.
|
[
"Start",
"a",
"partitioned",
"batch",
"read",
"operation",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L602-L662
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
BatchSnapshot.process_read_batch
|
def process_read_batch(self, batch):
"""Process a single, partitioned read.
:type batch: mapping
:param batch:
one of the mappings returned from an earlier call to
:meth:`generate_read_batches`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
"""
kwargs = copy.deepcopy(batch["read"])
keyset_dict = kwargs.pop("keyset")
kwargs["keyset"] = KeySet._from_dict(keyset_dict)
return self._get_snapshot().read(partition=batch["partition"], **kwargs)
|
python
|
def process_read_batch(self, batch):
"""Process a single, partitioned read.
:type batch: mapping
:param batch:
one of the mappings returned from an earlier call to
:meth:`generate_read_batches`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
"""
kwargs = copy.deepcopy(batch["read"])
keyset_dict = kwargs.pop("keyset")
kwargs["keyset"] = KeySet._from_dict(keyset_dict)
return self._get_snapshot().read(partition=batch["partition"], **kwargs)
|
[
"def",
"process_read_batch",
"(",
"self",
",",
"batch",
")",
":",
"kwargs",
"=",
"copy",
".",
"deepcopy",
"(",
"batch",
"[",
"\"read\"",
"]",
")",
"keyset_dict",
"=",
"kwargs",
".",
"pop",
"(",
"\"keyset\"",
")",
"kwargs",
"[",
"\"keyset\"",
"]",
"=",
"KeySet",
".",
"_from_dict",
"(",
"keyset_dict",
")",
"return",
"self",
".",
"_get_snapshot",
"(",
")",
".",
"read",
"(",
"partition",
"=",
"batch",
"[",
"\"partition\"",
"]",
",",
"*",
"*",
"kwargs",
")"
] |
Process a single, partitioned read.
:type batch: mapping
:param batch:
one of the mappings returned from an earlier call to
:meth:`generate_read_batches`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
|
[
"Process",
"a",
"single",
"partitioned",
"read",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L664-L678
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
BatchSnapshot.generate_query_batches
|
def generate_query_batches(
self,
sql,
params=None,
param_types=None,
partition_size_bytes=None,
max_partitions=None,
):
"""Start a partitioned query operation.
Uses the ``PartitionQuery`` API request to start a partitioned
query operation. Returns a list of batch information needed to
peform the actual queries.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of dict
:returns:
mappings of information used peform actual partitioned reads via
:meth:`process_read_batch`.
"""
partitions = self._get_snapshot().partition_query(
sql=sql,
params=params,
param_types=param_types,
partition_size_bytes=partition_size_bytes,
max_partitions=max_partitions,
)
query_info = {"sql": sql}
if params:
query_info["params"] = params
query_info["param_types"] = param_types
for partition in partitions:
yield {"partition": partition, "query": query_info}
|
python
|
def generate_query_batches(
self,
sql,
params=None,
param_types=None,
partition_size_bytes=None,
max_partitions=None,
):
"""Start a partitioned query operation.
Uses the ``PartitionQuery`` API request to start a partitioned
query operation. Returns a list of batch information needed to
peform the actual queries.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of dict
:returns:
mappings of information used peform actual partitioned reads via
:meth:`process_read_batch`.
"""
partitions = self._get_snapshot().partition_query(
sql=sql,
params=params,
param_types=param_types,
partition_size_bytes=partition_size_bytes,
max_partitions=max_partitions,
)
query_info = {"sql": sql}
if params:
query_info["params"] = params
query_info["param_types"] = param_types
for partition in partitions:
yield {"partition": partition, "query": query_info}
|
[
"def",
"generate_query_batches",
"(",
"self",
",",
"sql",
",",
"params",
"=",
"None",
",",
"param_types",
"=",
"None",
",",
"partition_size_bytes",
"=",
"None",
",",
"max_partitions",
"=",
"None",
",",
")",
":",
"partitions",
"=",
"self",
".",
"_get_snapshot",
"(",
")",
".",
"partition_query",
"(",
"sql",
"=",
"sql",
",",
"params",
"=",
"params",
",",
"param_types",
"=",
"param_types",
",",
"partition_size_bytes",
"=",
"partition_size_bytes",
",",
"max_partitions",
"=",
"max_partitions",
",",
")",
"query_info",
"=",
"{",
"\"sql\"",
":",
"sql",
"}",
"if",
"params",
":",
"query_info",
"[",
"\"params\"",
"]",
"=",
"params",
"query_info",
"[",
"\"param_types\"",
"]",
"=",
"param_types",
"for",
"partition",
"in",
"partitions",
":",
"yield",
"{",
"\"partition\"",
":",
"partition",
",",
"\"query\"",
":",
"query_info",
"}"
] |
Start a partitioned query operation.
Uses the ``PartitionQuery`` API request to start a partitioned
query operation. Returns a list of batch information needed to
peform the actual queries.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:rtype: iterable of dict
:returns:
mappings of information used peform actual partitioned reads via
:meth:`process_read_batch`.
|
[
"Start",
"a",
"partitioned",
"query",
"operation",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L680-L741
|
train
|
googleapis/google-cloud-python
|
spanner/google/cloud/spanner_v1/database.py
|
BatchSnapshot.process
|
def process(self, batch):
"""Process a single, partitioned query or read.
:type batch: mapping
:param batch:
one of the mappings returned from an earlier call to
:meth:`generate_query_batches`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:raises ValueError: if batch does not contain either 'read' or 'query'
"""
if "query" in batch:
return self.process_query_batch(batch)
if "read" in batch:
return self.process_read_batch(batch)
raise ValueError("Invalid batch")
|
python
|
def process(self, batch):
"""Process a single, partitioned query or read.
:type batch: mapping
:param batch:
one of the mappings returned from an earlier call to
:meth:`generate_query_batches`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:raises ValueError: if batch does not contain either 'read' or 'query'
"""
if "query" in batch:
return self.process_query_batch(batch)
if "read" in batch:
return self.process_read_batch(batch)
raise ValueError("Invalid batch")
|
[
"def",
"process",
"(",
"self",
",",
"batch",
")",
":",
"if",
"\"query\"",
"in",
"batch",
":",
"return",
"self",
".",
"process_query_batch",
"(",
"batch",
")",
"if",
"\"read\"",
"in",
"batch",
":",
"return",
"self",
".",
"process_read_batch",
"(",
"batch",
")",
"raise",
"ValueError",
"(",
"\"Invalid batch\"",
")"
] |
Process a single, partitioned query or read.
:type batch: mapping
:param batch:
one of the mappings returned from an earlier call to
:meth:`generate_query_batches`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:raises ValueError: if batch does not contain either 'read' or 'query'
|
[
"Process",
"a",
"single",
"partitioned",
"query",
"or",
"read",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L758-L774
|
train
|
googleapis/google-cloud-python
|
automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py
|
AutoMlClient.location_path
|
def location_path(cls, project, location):
"""Return a fully-qualified location string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}",
project=project,
location=location,
)
|
python
|
def location_path(cls, project, location):
"""Return a fully-qualified location string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}",
project=project,
location=location,
)
|
[
"def",
"location_path",
"(",
"cls",
",",
"project",
",",
"location",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/locations/{location}\"",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
",",
")"
] |
Return a fully-qualified location string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"location",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py#L101-L107
|
train
|
googleapis/google-cloud-python
|
automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py
|
AutoMlClient.model_path
|
def model_path(cls, project, location, model):
"""Return a fully-qualified model string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/models/{model}",
project=project,
location=location,
model=model,
)
|
python
|
def model_path(cls, project, location, model):
"""Return a fully-qualified model string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/models/{model}",
project=project,
location=location,
model=model,
)
|
[
"def",
"model_path",
"(",
"cls",
",",
"project",
",",
"location",
",",
"model",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/locations/{location}/models/{model}\"",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
",",
"model",
"=",
"model",
",",
")"
] |
Return a fully-qualified model string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"model",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py#L120-L127
|
train
|
googleapis/google-cloud-python
|
automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py
|
AutoMlClient.model_evaluation_path
|
def model_evaluation_path(cls, project, location, model, model_evaluation):
"""Return a fully-qualified model_evaluation string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/models/{model}/modelEvaluations/{model_evaluation}",
project=project,
location=location,
model=model,
model_evaluation=model_evaluation,
)
|
python
|
def model_evaluation_path(cls, project, location, model, model_evaluation):
"""Return a fully-qualified model_evaluation string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/models/{model}/modelEvaluations/{model_evaluation}",
project=project,
location=location,
model=model,
model_evaluation=model_evaluation,
)
|
[
"def",
"model_evaluation_path",
"(",
"cls",
",",
"project",
",",
"location",
",",
"model",
",",
"model_evaluation",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/locations/{location}/models/{model}/modelEvaluations/{model_evaluation}\"",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
",",
"model",
"=",
"model",
",",
"model_evaluation",
"=",
"model_evaluation",
",",
")"
] |
Return a fully-qualified model_evaluation string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"model_evaluation",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py#L130-L138
|
train
|
googleapis/google-cloud-python
|
automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py
|
AutoMlClient.annotation_spec_path
|
def annotation_spec_path(cls, project, location, dataset, annotation_spec):
"""Return a fully-qualified annotation_spec string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}",
project=project,
location=location,
dataset=dataset,
annotation_spec=annotation_spec,
)
|
python
|
def annotation_spec_path(cls, project, location, dataset, annotation_spec):
"""Return a fully-qualified annotation_spec string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}",
project=project,
location=location,
dataset=dataset,
annotation_spec=annotation_spec,
)
|
[
"def",
"annotation_spec_path",
"(",
"cls",
",",
"project",
",",
"location",
",",
"dataset",
",",
"annotation_spec",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}\"",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
",",
"dataset",
"=",
"dataset",
",",
"annotation_spec",
"=",
"annotation_spec",
",",
")"
] |
Return a fully-qualified annotation_spec string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"annotation_spec",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py#L141-L149
|
train
|
googleapis/google-cloud-python
|
automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py
|
AutoMlClient.table_spec_path
|
def table_spec_path(cls, project, location, dataset, table_spec):
"""Return a fully-qualified table_spec string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}",
project=project,
location=location,
dataset=dataset,
table_spec=table_spec,
)
|
python
|
def table_spec_path(cls, project, location, dataset, table_spec):
"""Return a fully-qualified table_spec string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}",
project=project,
location=location,
dataset=dataset,
table_spec=table_spec,
)
|
[
"def",
"table_spec_path",
"(",
"cls",
",",
"project",
",",
"location",
",",
"dataset",
",",
"table_spec",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}\"",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
",",
"dataset",
"=",
"dataset",
",",
"table_spec",
"=",
"table_spec",
",",
")"
] |
Return a fully-qualified table_spec string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"table_spec",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py#L152-L160
|
train
|
googleapis/google-cloud-python
|
automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py
|
AutoMlClient.column_spec_path
|
def column_spec_path(cls, project, location, dataset, table_spec, column_spec):
"""Return a fully-qualified column_spec string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}/columnSpecs/{column_spec}",
project=project,
location=location,
dataset=dataset,
table_spec=table_spec,
column_spec=column_spec,
)
|
python
|
def column_spec_path(cls, project, location, dataset, table_spec, column_spec):
"""Return a fully-qualified column_spec string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}/columnSpecs/{column_spec}",
project=project,
location=location,
dataset=dataset,
table_spec=table_spec,
column_spec=column_spec,
)
|
[
"def",
"column_spec_path",
"(",
"cls",
",",
"project",
",",
"location",
",",
"dataset",
",",
"table_spec",
",",
"column_spec",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}/columnSpecs/{column_spec}\"",
",",
"project",
"=",
"project",
",",
"location",
"=",
"location",
",",
"dataset",
"=",
"dataset",
",",
"table_spec",
"=",
"table_spec",
",",
"column_spec",
"=",
"column_spec",
",",
")"
] |
Return a fully-qualified column_spec string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"column_spec",
"string",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py#L163-L172
|
train
|
googleapis/google-cloud-python
|
automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py
|
AutoMlClient.create_dataset
|
def create_dataset(
self,
parent,
dataset,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a dataset.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> client = automl_v1beta1.AutoMlClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `dataset`:
>>> dataset = {}
>>>
>>> response = client.create_dataset(parent, dataset)
Args:
parent (str): The resource name of the project to create the dataset for.
dataset (Union[dict, ~google.cloud.automl_v1beta1.types.Dataset]): The dataset to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.automl_v1beta1.types.Dataset`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.automl_v1beta1.types.Dataset` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "create_dataset" not in self._inner_api_calls:
self._inner_api_calls[
"create_dataset"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_dataset,
default_retry=self._method_configs["CreateDataset"].retry,
default_timeout=self._method_configs["CreateDataset"].timeout,
client_info=self._client_info,
)
request = service_pb2.CreateDatasetRequest(parent=parent, dataset=dataset)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["create_dataset"](
request, retry=retry, timeout=timeout, metadata=metadata
)
|
python
|
def create_dataset(
self,
parent,
dataset,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a dataset.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> client = automl_v1beta1.AutoMlClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `dataset`:
>>> dataset = {}
>>>
>>> response = client.create_dataset(parent, dataset)
Args:
parent (str): The resource name of the project to create the dataset for.
dataset (Union[dict, ~google.cloud.automl_v1beta1.types.Dataset]): The dataset to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.automl_v1beta1.types.Dataset`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.automl_v1beta1.types.Dataset` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "create_dataset" not in self._inner_api_calls:
self._inner_api_calls[
"create_dataset"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_dataset,
default_retry=self._method_configs["CreateDataset"].retry,
default_timeout=self._method_configs["CreateDataset"].timeout,
client_info=self._client_info,
)
request = service_pb2.CreateDatasetRequest(parent=parent, dataset=dataset)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["create_dataset"](
request, retry=retry, timeout=timeout, metadata=metadata
)
|
[
"def",
"create_dataset",
"(",
"self",
",",
"parent",
",",
"dataset",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"create_dataset\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"create_dataset\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_dataset",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateDataset\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateDataset\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"service_pb2",
".",
"CreateDatasetRequest",
"(",
"parent",
"=",
"parent",
",",
"dataset",
"=",
"dataset",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"parent\"",
",",
"parent",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"create_dataset\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] |
Creates a dataset.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> client = automl_v1beta1.AutoMlClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `dataset`:
>>> dataset = {}
>>>
>>> response = client.create_dataset(parent, dataset)
Args:
parent (str): The resource name of the project to create the dataset for.
dataset (Union[dict, ~google.cloud.automl_v1beta1.types.Dataset]): The dataset to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.automl_v1beta1.types.Dataset`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.automl_v1beta1.types.Dataset` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
|
[
"Creates",
"a",
"dataset",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py#L273-L348
|
train
|
googleapis/google-cloud-python
|
automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py
|
AutoMlClient.delete_dataset
|
def delete_dataset(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a dataset and all of its contents. Returns empty response in the
``response`` field when it completes, and ``delete_details`` in the
``metadata`` field.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> client = automl_v1beta1.AutoMlClient()
>>>
>>> name = client.dataset_path('[PROJECT]', '[LOCATION]', '[DATASET]')
>>>
>>> response = client.delete_dataset(name)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
name (str): The resource name of the dataset to delete.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.automl_v1beta1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "delete_dataset" not in self._inner_api_calls:
self._inner_api_calls[
"delete_dataset"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.delete_dataset,
default_retry=self._method_configs["DeleteDataset"].retry,
default_timeout=self._method_configs["DeleteDataset"].timeout,
client_info=self._client_info,
)
request = service_pb2.DeleteDatasetRequest(name=name)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("name", name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
operation = self._inner_api_calls["delete_dataset"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
empty_pb2.Empty,
metadata_type=proto_operations_pb2.OperationMetadata,
)
|
python
|
def delete_dataset(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a dataset and all of its contents. Returns empty response in the
``response`` field when it completes, and ``delete_details`` in the
``metadata`` field.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> client = automl_v1beta1.AutoMlClient()
>>>
>>> name = client.dataset_path('[PROJECT]', '[LOCATION]', '[DATASET]')
>>>
>>> response = client.delete_dataset(name)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
name (str): The resource name of the dataset to delete.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.automl_v1beta1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "delete_dataset" not in self._inner_api_calls:
self._inner_api_calls[
"delete_dataset"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.delete_dataset,
default_retry=self._method_configs["DeleteDataset"].retry,
default_timeout=self._method_configs["DeleteDataset"].timeout,
client_info=self._client_info,
)
request = service_pb2.DeleteDatasetRequest(name=name)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("name", name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
operation = self._inner_api_calls["delete_dataset"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
empty_pb2.Empty,
metadata_type=proto_operations_pb2.OperationMetadata,
)
|
[
"def",
"delete_dataset",
"(",
"self",
",",
"name",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"delete_dataset\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"delete_dataset\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"delete_dataset",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"DeleteDataset\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"DeleteDataset\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"service_pb2",
".",
"DeleteDatasetRequest",
"(",
"name",
"=",
"name",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"name\"",
",",
"name",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"operation",
"=",
"self",
".",
"_inner_api_calls",
"[",
"\"delete_dataset\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")",
"return",
"google",
".",
"api_core",
".",
"operation",
".",
"from_gapic",
"(",
"operation",
",",
"self",
".",
"transport",
".",
"_operations_client",
",",
"empty_pb2",
".",
"Empty",
",",
"metadata_type",
"=",
"proto_operations_pb2",
".",
"OperationMetadata",
",",
")"
] |
Deletes a dataset and all of its contents. Returns empty response in the
``response`` field when it completes, and ``delete_details`` in the
``metadata`` field.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> client = automl_v1beta1.AutoMlClient()
>>>
>>> name = client.dataset_path('[PROJECT]', '[LOCATION]', '[DATASET]')
>>>
>>> response = client.delete_dataset(name)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
name (str): The resource name of the dataset to delete.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.automl_v1beta1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
|
[
"Deletes",
"a",
"dataset",
"and",
"all",
"of",
"its",
"contents",
".",
"Returns",
"empty",
"response",
"in",
"the",
"response",
"field",
"when",
"it",
"completes",
"and",
"delete_details",
"in",
"the",
"metadata",
"field",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py#L615-L699
|
train
|
googleapis/google-cloud-python
|
automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py
|
AutoMlClient.create_model
|
def create_model(
self,
parent,
model,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a model. Returns a Model in the ``response`` field when it
completes. When you create a model, several model evaluations are
created for it: a global evaluation, and one evaluation for each
annotation spec.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> client = automl_v1beta1.AutoMlClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `model`:
>>> model = {}
>>>
>>> response = client.create_model(parent, model)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Resource name of the parent project where the model is being created.
model (Union[dict, ~google.cloud.automl_v1beta1.types.Model]): The model to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.automl_v1beta1.types.Model`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.automl_v1beta1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "create_model" not in self._inner_api_calls:
self._inner_api_calls[
"create_model"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_model,
default_retry=self._method_configs["CreateModel"].retry,
default_timeout=self._method_configs["CreateModel"].timeout,
client_info=self._client_info,
)
request = service_pb2.CreateModelRequest(parent=parent, model=model)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
operation = self._inner_api_calls["create_model"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
model_pb2.Model,
metadata_type=proto_operations_pb2.OperationMetadata,
)
|
python
|
def create_model(
self,
parent,
model,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a model. Returns a Model in the ``response`` field when it
completes. When you create a model, several model evaluations are
created for it: a global evaluation, and one evaluation for each
annotation spec.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> client = automl_v1beta1.AutoMlClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `model`:
>>> model = {}
>>>
>>> response = client.create_model(parent, model)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Resource name of the parent project where the model is being created.
model (Union[dict, ~google.cloud.automl_v1beta1.types.Model]): The model to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.automl_v1beta1.types.Model`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.automl_v1beta1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "create_model" not in self._inner_api_calls:
self._inner_api_calls[
"create_model"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_model,
default_retry=self._method_configs["CreateModel"].retry,
default_timeout=self._method_configs["CreateModel"].timeout,
client_info=self._client_info,
)
request = service_pb2.CreateModelRequest(parent=parent, model=model)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
operation = self._inner_api_calls["create_model"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
model_pb2.Model,
metadata_type=proto_operations_pb2.OperationMetadata,
)
|
[
"def",
"create_model",
"(",
"self",
",",
"parent",
",",
"model",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"create_model\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"create_model\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_model",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateModel\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateModel\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"service_pb2",
".",
"CreateModelRequest",
"(",
"parent",
"=",
"parent",
",",
"model",
"=",
"model",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"parent\"",
",",
"parent",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"operation",
"=",
"self",
".",
"_inner_api_calls",
"[",
"\"create_model\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")",
"return",
"google",
".",
"api_core",
".",
"operation",
".",
"from_gapic",
"(",
"operation",
",",
"self",
".",
"transport",
".",
"_operations_client",
",",
"model_pb2",
".",
"Model",
",",
"metadata_type",
"=",
"proto_operations_pb2",
".",
"OperationMetadata",
",",
")"
] |
Creates a model. Returns a Model in the ``response`` field when it
completes. When you create a model, several model evaluations are
created for it: a global evaluation, and one evaluation for each
annotation spec.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> client = automl_v1beta1.AutoMlClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>> # TODO: Initialize `model`:
>>> model = {}
>>>
>>> response = client.create_model(parent, model)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Resource name of the parent project where the model is being created.
model (Union[dict, ~google.cloud.automl_v1beta1.types.Model]): The model to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.automl_v1beta1.types.Model`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.automl_v1beta1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
|
[
"Creates",
"a",
"model",
".",
"Returns",
"a",
"Model",
"in",
"the",
"response",
"field",
"when",
"it",
"completes",
".",
"When",
"you",
"create",
"a",
"model",
"several",
"model",
"evaluations",
"are",
"created",
"for",
"it",
":",
"a",
"global",
"evaluation",
"and",
"one",
"evaluation",
"for",
"each",
"annotation",
"spec",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py#L895-L988
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/retry.py
|
exponential_sleep_generator
|
def exponential_sleep_generator(initial, maximum, multiplier=_DEFAULT_DELAY_MULTIPLIER):
"""Generates sleep intervals based on the exponential back-off algorithm.
This implements the `Truncated Exponential Back-off`_ algorithm.
.. _Truncated Exponential Back-off:
https://cloud.google.com/storage/docs/exponential-backoff
Args:
initial (float): The minimum about of time to delay. This must
be greater than 0.
maximum (float): The maximum about of time to delay.
multiplier (float): The multiplier applied to the delay.
Yields:
float: successive sleep intervals.
"""
delay = initial
while True:
# Introduce jitter by yielding a delay that is uniformly distributed
# to average out to the delay time.
yield min(random.uniform(0.0, delay * 2.0), maximum)
delay = delay * multiplier
|
python
|
def exponential_sleep_generator(initial, maximum, multiplier=_DEFAULT_DELAY_MULTIPLIER):
"""Generates sleep intervals based on the exponential back-off algorithm.
This implements the `Truncated Exponential Back-off`_ algorithm.
.. _Truncated Exponential Back-off:
https://cloud.google.com/storage/docs/exponential-backoff
Args:
initial (float): The minimum about of time to delay. This must
be greater than 0.
maximum (float): The maximum about of time to delay.
multiplier (float): The multiplier applied to the delay.
Yields:
float: successive sleep intervals.
"""
delay = initial
while True:
# Introduce jitter by yielding a delay that is uniformly distributed
# to average out to the delay time.
yield min(random.uniform(0.0, delay * 2.0), maximum)
delay = delay * multiplier
|
[
"def",
"exponential_sleep_generator",
"(",
"initial",
",",
"maximum",
",",
"multiplier",
"=",
"_DEFAULT_DELAY_MULTIPLIER",
")",
":",
"delay",
"=",
"initial",
"while",
"True",
":",
"# Introduce jitter by yielding a delay that is uniformly distributed",
"# to average out to the delay time.",
"yield",
"min",
"(",
"random",
".",
"uniform",
"(",
"0.0",
",",
"delay",
"*",
"2.0",
")",
",",
"maximum",
")",
"delay",
"=",
"delay",
"*",
"multiplier"
] |
Generates sleep intervals based on the exponential back-off algorithm.
This implements the `Truncated Exponential Back-off`_ algorithm.
.. _Truncated Exponential Back-off:
https://cloud.google.com/storage/docs/exponential-backoff
Args:
initial (float): The minimum about of time to delay. This must
be greater than 0.
maximum (float): The maximum about of time to delay.
multiplier (float): The multiplier applied to the delay.
Yields:
float: successive sleep intervals.
|
[
"Generates",
"sleep",
"intervals",
"based",
"on",
"the",
"exponential",
"back",
"-",
"off",
"algorithm",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/retry.py#L116-L138
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/retry.py
|
retry_target
|
def retry_target(target, predicate, sleep_generator, deadline, on_error=None):
"""Call a function and retry if it fails.
This is the lowest-level retry helper. Generally, you'll use the
higher-level retry helper :class:`Retry`.
Args:
target(Callable): The function to call and retry. This must be a
nullary function - apply arguments with `functools.partial`.
predicate (Callable[Exception]): A callable used to determine if an
exception raised by the target should be considered retryable.
It should return True to retry or False otherwise.
sleep_generator (Iterable[float]): An infinite iterator that determines
how long to sleep between retries.
deadline (float): How long to keep retrying the target.
on_error (Callable): A function to call while processing a retryable
exception. Any error raised by this function will *not* be
caught.
Returns:
Any: the return value of the target function.
Raises:
google.api_core.RetryError: If the deadline is exceeded while retrying.
ValueError: If the sleep generator stops yielding values.
Exception: If the target raises a method that isn't retryable.
"""
if deadline is not None:
deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta(
seconds=deadline
)
else:
deadline_datetime = None
last_exc = None
for sleep in sleep_generator:
try:
return target()
# pylint: disable=broad-except
# This function explicitly must deal with broad exceptions.
except Exception as exc:
if not predicate(exc):
raise
last_exc = exc
if on_error is not None:
on_error(exc)
now = datetime_helpers.utcnow()
if deadline_datetime is not None and deadline_datetime < now:
six.raise_from(
exceptions.RetryError(
"Deadline of {:.1f}s exceeded while calling {}".format(
deadline, target
),
last_exc,
),
last_exc,
)
_LOGGER.debug(
"Retrying due to {}, sleeping {:.1f}s ...".format(last_exc, sleep)
)
time.sleep(sleep)
raise ValueError("Sleep generator stopped yielding sleep values.")
|
python
|
def retry_target(target, predicate, sleep_generator, deadline, on_error=None):
"""Call a function and retry if it fails.
This is the lowest-level retry helper. Generally, you'll use the
higher-level retry helper :class:`Retry`.
Args:
target(Callable): The function to call and retry. This must be a
nullary function - apply arguments with `functools.partial`.
predicate (Callable[Exception]): A callable used to determine if an
exception raised by the target should be considered retryable.
It should return True to retry or False otherwise.
sleep_generator (Iterable[float]): An infinite iterator that determines
how long to sleep between retries.
deadline (float): How long to keep retrying the target.
on_error (Callable): A function to call while processing a retryable
exception. Any error raised by this function will *not* be
caught.
Returns:
Any: the return value of the target function.
Raises:
google.api_core.RetryError: If the deadline is exceeded while retrying.
ValueError: If the sleep generator stops yielding values.
Exception: If the target raises a method that isn't retryable.
"""
if deadline is not None:
deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta(
seconds=deadline
)
else:
deadline_datetime = None
last_exc = None
for sleep in sleep_generator:
try:
return target()
# pylint: disable=broad-except
# This function explicitly must deal with broad exceptions.
except Exception as exc:
if not predicate(exc):
raise
last_exc = exc
if on_error is not None:
on_error(exc)
now = datetime_helpers.utcnow()
if deadline_datetime is not None and deadline_datetime < now:
six.raise_from(
exceptions.RetryError(
"Deadline of {:.1f}s exceeded while calling {}".format(
deadline, target
),
last_exc,
),
last_exc,
)
_LOGGER.debug(
"Retrying due to {}, sleeping {:.1f}s ...".format(last_exc, sleep)
)
time.sleep(sleep)
raise ValueError("Sleep generator stopped yielding sleep values.")
|
[
"def",
"retry_target",
"(",
"target",
",",
"predicate",
",",
"sleep_generator",
",",
"deadline",
",",
"on_error",
"=",
"None",
")",
":",
"if",
"deadline",
"is",
"not",
"None",
":",
"deadline_datetime",
"=",
"datetime_helpers",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"deadline",
")",
"else",
":",
"deadline_datetime",
"=",
"None",
"last_exc",
"=",
"None",
"for",
"sleep",
"in",
"sleep_generator",
":",
"try",
":",
"return",
"target",
"(",
")",
"# pylint: disable=broad-except",
"# This function explicitly must deal with broad exceptions.",
"except",
"Exception",
"as",
"exc",
":",
"if",
"not",
"predicate",
"(",
"exc",
")",
":",
"raise",
"last_exc",
"=",
"exc",
"if",
"on_error",
"is",
"not",
"None",
":",
"on_error",
"(",
"exc",
")",
"now",
"=",
"datetime_helpers",
".",
"utcnow",
"(",
")",
"if",
"deadline_datetime",
"is",
"not",
"None",
"and",
"deadline_datetime",
"<",
"now",
":",
"six",
".",
"raise_from",
"(",
"exceptions",
".",
"RetryError",
"(",
"\"Deadline of {:.1f}s exceeded while calling {}\"",
".",
"format",
"(",
"deadline",
",",
"target",
")",
",",
"last_exc",
",",
")",
",",
"last_exc",
",",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Retrying due to {}, sleeping {:.1f}s ...\"",
".",
"format",
"(",
"last_exc",
",",
"sleep",
")",
")",
"time",
".",
"sleep",
"(",
"sleep",
")",
"raise",
"ValueError",
"(",
"\"Sleep generator stopped yielding sleep values.\"",
")"
] |
Call a function and retry if it fails.
This is the lowest-level retry helper. Generally, you'll use the
higher-level retry helper :class:`Retry`.
Args:
target(Callable): The function to call and retry. This must be a
nullary function - apply arguments with `functools.partial`.
predicate (Callable[Exception]): A callable used to determine if an
exception raised by the target should be considered retryable.
It should return True to retry or False otherwise.
sleep_generator (Iterable[float]): An infinite iterator that determines
how long to sleep between retries.
deadline (float): How long to keep retrying the target.
on_error (Callable): A function to call while processing a retryable
exception. Any error raised by this function will *not* be
caught.
Returns:
Any: the return value of the target function.
Raises:
google.api_core.RetryError: If the deadline is exceeded while retrying.
ValueError: If the sleep generator stops yielding values.
Exception: If the target raises a method that isn't retryable.
|
[
"Call",
"a",
"function",
"and",
"retry",
"if",
"it",
"fails",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/retry.py#L141-L207
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/bidi.py
|
BidiRpc.open
|
def open(self):
"""Opens the stream."""
if self.is_active:
raise ValueError("Can not open an already open stream.")
request_generator = _RequestQueueGenerator(
self._request_queue, initial_request=self._initial_request
)
call = self._start_rpc(iter(request_generator), metadata=self._rpc_metadata)
request_generator.call = call
# TODO: api_core should expose the future interface for wrapped
# callables as well.
if hasattr(call, "_wrapped"): # pragma: NO COVER
call._wrapped.add_done_callback(self._on_call_done)
else:
call.add_done_callback(self._on_call_done)
self._request_generator = request_generator
self.call = call
|
python
|
def open(self):
"""Opens the stream."""
if self.is_active:
raise ValueError("Can not open an already open stream.")
request_generator = _RequestQueueGenerator(
self._request_queue, initial_request=self._initial_request
)
call = self._start_rpc(iter(request_generator), metadata=self._rpc_metadata)
request_generator.call = call
# TODO: api_core should expose the future interface for wrapped
# callables as well.
if hasattr(call, "_wrapped"): # pragma: NO COVER
call._wrapped.add_done_callback(self._on_call_done)
else:
call.add_done_callback(self._on_call_done)
self._request_generator = request_generator
self.call = call
|
[
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_active",
":",
"raise",
"ValueError",
"(",
"\"Can not open an already open stream.\"",
")",
"request_generator",
"=",
"_RequestQueueGenerator",
"(",
"self",
".",
"_request_queue",
",",
"initial_request",
"=",
"self",
".",
"_initial_request",
")",
"call",
"=",
"self",
".",
"_start_rpc",
"(",
"iter",
"(",
"request_generator",
")",
",",
"metadata",
"=",
"self",
".",
"_rpc_metadata",
")",
"request_generator",
".",
"call",
"=",
"call",
"# TODO: api_core should expose the future interface for wrapped",
"# callables as well.",
"if",
"hasattr",
"(",
"call",
",",
"\"_wrapped\"",
")",
":",
"# pragma: NO COVER",
"call",
".",
"_wrapped",
".",
"add_done_callback",
"(",
"self",
".",
"_on_call_done",
")",
"else",
":",
"call",
".",
"add_done_callback",
"(",
"self",
".",
"_on_call_done",
")",
"self",
".",
"_request_generator",
"=",
"request_generator",
"self",
".",
"call",
"=",
"call"
] |
Opens the stream.
|
[
"Opens",
"the",
"stream",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/bidi.py#L202-L222
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/bidi.py
|
BidiRpc.close
|
def close(self):
"""Closes the stream."""
if self.call is None:
return
self._request_queue.put(None)
self.call.cancel()
self._request_generator = None
|
python
|
def close(self):
"""Closes the stream."""
if self.call is None:
return
self._request_queue.put(None)
self.call.cancel()
self._request_generator = None
|
[
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"call",
"is",
"None",
":",
"return",
"self",
".",
"_request_queue",
".",
"put",
"(",
"None",
")",
"self",
".",
"call",
".",
"cancel",
"(",
")",
"self",
".",
"_request_generator",
"=",
"None"
] |
Closes the stream.
|
[
"Closes",
"the",
"stream",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/bidi.py#L224-L231
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/bidi.py
|
BidiRpc.send
|
def send(self, request):
"""Queue a message to be sent on the stream.
Send is non-blocking.
If the underlying RPC has been closed, this will raise.
Args:
request (protobuf.Message): The request to send.
"""
if self.call is None:
raise ValueError("Can not send() on an RPC that has never been open()ed.")
# Don't use self.is_active(), as ResumableBidiRpc will overload it
# to mean something semantically different.
if self.call.is_active():
self._request_queue.put(request)
else:
# calling next should cause the call to raise.
next(self.call)
|
python
|
def send(self, request):
"""Queue a message to be sent on the stream.
Send is non-blocking.
If the underlying RPC has been closed, this will raise.
Args:
request (protobuf.Message): The request to send.
"""
if self.call is None:
raise ValueError("Can not send() on an RPC that has never been open()ed.")
# Don't use self.is_active(), as ResumableBidiRpc will overload it
# to mean something semantically different.
if self.call.is_active():
self._request_queue.put(request)
else:
# calling next should cause the call to raise.
next(self.call)
|
[
"def",
"send",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"call",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Can not send() on an RPC that has never been open()ed.\"",
")",
"# Don't use self.is_active(), as ResumableBidiRpc will overload it",
"# to mean something semantically different.",
"if",
"self",
".",
"call",
".",
"is_active",
"(",
")",
":",
"self",
".",
"_request_queue",
".",
"put",
"(",
"request",
")",
"else",
":",
"# calling next should cause the call to raise.",
"next",
"(",
"self",
".",
"call",
")"
] |
Queue a message to be sent on the stream.
Send is non-blocking.
If the underlying RPC has been closed, this will raise.
Args:
request (protobuf.Message): The request to send.
|
[
"Queue",
"a",
"message",
"to",
"be",
"sent",
"on",
"the",
"stream",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/bidi.py#L235-L254
|
train
|
googleapis/google-cloud-python
|
api_core/google/api_core/bidi.py
|
ResumableBidiRpc._recoverable
|
def _recoverable(self, method, *args, **kwargs):
"""Wraps a method to recover the stream and retry on error.
If a retryable error occurs while making the call, then the stream will
be re-opened and the method will be retried. This happens indefinitely
so long as the error is a retryable one. If an error occurs while
re-opening the stream, then this method will raise immediately and
trigger finalization of this object.
Args:
method (Callable[..., Any]): The method to call.
args: The args to pass to the method.
kwargs: The kwargs to pass to the method.
"""
while True:
try:
return method(*args, **kwargs)
except Exception as exc:
with self._operational_lock:
_LOGGER.debug("Call to retryable %r caused %s.", method, exc)
if not self._should_recover(exc):
self.close()
_LOGGER.debug("Not retrying %r due to %s.", method, exc)
self._finalize(exc)
raise exc
_LOGGER.debug("Re-opening stream from retryable %r.", method)
self._reopen()
|
python
|
def _recoverable(self, method, *args, **kwargs):
"""Wraps a method to recover the stream and retry on error.
If a retryable error occurs while making the call, then the stream will
be re-opened and the method will be retried. This happens indefinitely
so long as the error is a retryable one. If an error occurs while
re-opening the stream, then this method will raise immediately and
trigger finalization of this object.
Args:
method (Callable[..., Any]): The method to call.
args: The args to pass to the method.
kwargs: The kwargs to pass to the method.
"""
while True:
try:
return method(*args, **kwargs)
except Exception as exc:
with self._operational_lock:
_LOGGER.debug("Call to retryable %r caused %s.", method, exc)
if not self._should_recover(exc):
self.close()
_LOGGER.debug("Not retrying %r due to %s.", method, exc)
self._finalize(exc)
raise exc
_LOGGER.debug("Re-opening stream from retryable %r.", method)
self._reopen()
|
[
"def",
"_recoverable",
"(",
"self",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"try",
":",
"return",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"exc",
":",
"with",
"self",
".",
"_operational_lock",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Call to retryable %r caused %s.\"",
",",
"method",
",",
"exc",
")",
"if",
"not",
"self",
".",
"_should_recover",
"(",
"exc",
")",
":",
"self",
".",
"close",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Not retrying %r due to %s.\"",
",",
"method",
",",
"exc",
")",
"self",
".",
"_finalize",
"(",
"exc",
")",
"raise",
"exc",
"_LOGGER",
".",
"debug",
"(",
"\"Re-opening stream from retryable %r.\"",
",",
"method",
")",
"self",
".",
"_reopen",
"(",
")"
] |
Wraps a method to recover the stream and retry on error.
If a retryable error occurs while making the call, then the stream will
be re-opened and the method will be retried. This happens indefinitely
so long as the error is a retryable one. If an error occurs while
re-opening the stream, then this method will raise immediately and
trigger finalization of this object.
Args:
method (Callable[..., Any]): The method to call.
args: The args to pass to the method.
kwargs: The kwargs to pass to the method.
|
[
"Wraps",
"a",
"method",
"to",
"recover",
"the",
"stream",
"and",
"retry",
"on",
"error",
"."
] |
85e80125a59cb10f8cb105f25ecc099e4b940b50
|
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/bidi.py#L387-L416
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.