id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
28,100 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.rewrite | def rewrite(self, source, token=None, client=None):
"""Rewrite source blob into this one.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type source: :class:`Blob`
:param source: blob whose contents will be rewritten into this blob.
:type token: str
:param token: Optional. Token returned from an earlier, not-completed
call to rewrite the same source blob. If passed,
result will include updated status, total bytes written.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: tuple
:returns: ``(token, bytes_rewritten, total_bytes)``, where ``token``
is a rewrite token (``None`` if the rewrite is complete),
``bytes_rewritten`` is the number of bytes rewritten so far,
and ``total_bytes`` is the total number of bytes to be
rewritten.
"""
client = self._require_client(client)
headers = _get_encryption_headers(self._encryption_key)
headers.update(_get_encryption_headers(source._encryption_key, source=True))
query_params = self._query_params
if "generation" in query_params:
del query_params["generation"]
if token:
query_params["rewriteToken"] = token
if source.generation:
query_params["sourceGeneration"] = source.generation
if self.kms_key_name is not None:
query_params["destinationKmsKeyName"] = self.kms_key_name
api_response = client._connection.api_request(
method="POST",
path=source.path + "/rewriteTo" + self.path,
query_params=query_params,
data=self._properties,
headers=headers,
_target_object=self,
)
rewritten = int(api_response["totalBytesRewritten"])
size = int(api_response["objectSize"])
# The resource key is set if and only if the API response is
# completely done. Additionally, there is no rewrite token to return
# in this case.
if api_response["done"]:
self._set_properties(api_response["resource"])
return None, rewritten, size
return api_response["rewriteToken"], rewritten, size | python | def rewrite(self, source, token=None, client=None):
"""Rewrite source blob into this one.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type source: :class:`Blob`
:param source: blob whose contents will be rewritten into this blob.
:type token: str
:param token: Optional. Token returned from an earlier, not-completed
call to rewrite the same source blob. If passed,
result will include updated status, total bytes written.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: tuple
:returns: ``(token, bytes_rewritten, total_bytes)``, where ``token``
is a rewrite token (``None`` if the rewrite is complete),
``bytes_rewritten`` is the number of bytes rewritten so far,
and ``total_bytes`` is the total number of bytes to be
rewritten.
"""
client = self._require_client(client)
headers = _get_encryption_headers(self._encryption_key)
headers.update(_get_encryption_headers(source._encryption_key, source=True))
query_params = self._query_params
if "generation" in query_params:
del query_params["generation"]
if token:
query_params["rewriteToken"] = token
if source.generation:
query_params["sourceGeneration"] = source.generation
if self.kms_key_name is not None:
query_params["destinationKmsKeyName"] = self.kms_key_name
api_response = client._connection.api_request(
method="POST",
path=source.path + "/rewriteTo" + self.path,
query_params=query_params,
data=self._properties,
headers=headers,
_target_object=self,
)
rewritten = int(api_response["totalBytesRewritten"])
size = int(api_response["objectSize"])
# The resource key is set if and only if the API response is
# completely done. Additionally, there is no rewrite token to return
# in this case.
if api_response["done"]:
self._set_properties(api_response["resource"])
return None, rewritten, size
return api_response["rewriteToken"], rewritten, size | [
"def",
"rewrite",
"(",
"self",
",",
"source",
",",
"token",
"=",
"None",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"headers",
"=",
"_get_encryption_headers",
"(",
"self",
".",
"_encryption_key",
")",
"headers",
".",
"update",
"(",
"_get_encryption_headers",
"(",
"source",
".",
"_encryption_key",
",",
"source",
"=",
"True",
")",
")",
"query_params",
"=",
"self",
".",
"_query_params",
"if",
"\"generation\"",
"in",
"query_params",
":",
"del",
"query_params",
"[",
"\"generation\"",
"]",
"if",
"token",
":",
"query_params",
"[",
"\"rewriteToken\"",
"]",
"=",
"token",
"if",
"source",
".",
"generation",
":",
"query_params",
"[",
"\"sourceGeneration\"",
"]",
"=",
"source",
".",
"generation",
"if",
"self",
".",
"kms_key_name",
"is",
"not",
"None",
":",
"query_params",
"[",
"\"destinationKmsKeyName\"",
"]",
"=",
"self",
".",
"kms_key_name",
"api_response",
"=",
"client",
".",
"_connection",
".",
"api_request",
"(",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"source",
".",
"path",
"+",
"\"/rewriteTo\"",
"+",
"self",
".",
"path",
",",
"query_params",
"=",
"query_params",
",",
"data",
"=",
"self",
".",
"_properties",
",",
"headers",
"=",
"headers",
",",
"_target_object",
"=",
"self",
",",
")",
"rewritten",
"=",
"int",
"(",
"api_response",
"[",
"\"totalBytesRewritten\"",
"]",
")",
"size",
"=",
"int",
"(",
"api_response",
"[",
"\"objectSize\"",
"]",
")",
"# The resource key is set if and only if the API response is",
"# completely done. Additionally, there is no rewrite token to return",
"# in this case.",
"if",
"api_response",
"[",
"\"done\"",
"]",
":",
"self",
".",
"_set_properties",
"(",
"api_response",
"[",
"\"resource\"",
"]",
")",
"return",
"None",
",",
"rewritten",
",",
"size",
"return",
"api_response",
"[",
"\"rewriteToken\"",
"]",
",",
"rewritten",
",",
"size"
] | Rewrite source blob into this one.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type source: :class:`Blob`
:param source: blob whose contents will be rewritten into this blob.
:type token: str
:param token: Optional. Token returned from an earlier, not-completed
call to rewrite the same source blob. If passed,
result will include updated status, total bytes written.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: tuple
:returns: ``(token, bytes_rewritten, total_bytes)``, where ``token``
is a rewrite token (``None`` if the rewrite is complete),
``bytes_rewritten`` is the number of bytes rewritten so far,
and ``total_bytes`` is the total number of bytes to be
rewritten. | [
"Rewrite",
"source",
"blob",
"into",
"this",
"one",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1529-L1590 |
28,101 | googleapis/google-cloud-python | storage/google/cloud/storage/blob.py | Blob.update_storage_class | def update_storage_class(self, new_class, client=None):
"""Update blob's storage class via a rewrite-in-place. This helper will
wait for the rewrite to complete before returning, so it may take some
time for large files.
See
https://cloud.google.com/storage/docs/per-object-storage-class
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type new_class: str
:param new_class: new storage class for the object
:type client: :class:`~google.cloud.storage.client.Client`
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
"""
if new_class not in self._STORAGE_CLASSES:
raise ValueError("Invalid storage class: %s" % (new_class,))
# Update current blob's storage class prior to rewrite
self._patch_property("storageClass", new_class)
# Execute consecutive rewrite operations until operation is done
token, _, _ = self.rewrite(self)
while token is not None:
token, _, _ = self.rewrite(self, token=token) | python | def update_storage_class(self, new_class, client=None):
"""Update blob's storage class via a rewrite-in-place. This helper will
wait for the rewrite to complete before returning, so it may take some
time for large files.
See
https://cloud.google.com/storage/docs/per-object-storage-class
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type new_class: str
:param new_class: new storage class for the object
:type client: :class:`~google.cloud.storage.client.Client`
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
"""
if new_class not in self._STORAGE_CLASSES:
raise ValueError("Invalid storage class: %s" % (new_class,))
# Update current blob's storage class prior to rewrite
self._patch_property("storageClass", new_class)
# Execute consecutive rewrite operations until operation is done
token, _, _ = self.rewrite(self)
while token is not None:
token, _, _ = self.rewrite(self, token=token) | [
"def",
"update_storage_class",
"(",
"self",
",",
"new_class",
",",
"client",
"=",
"None",
")",
":",
"if",
"new_class",
"not",
"in",
"self",
".",
"_STORAGE_CLASSES",
":",
"raise",
"ValueError",
"(",
"\"Invalid storage class: %s\"",
"%",
"(",
"new_class",
",",
")",
")",
"# Update current blob's storage class prior to rewrite",
"self",
".",
"_patch_property",
"(",
"\"storageClass\"",
",",
"new_class",
")",
"# Execute consecutive rewrite operations until operation is done",
"token",
",",
"_",
",",
"_",
"=",
"self",
".",
"rewrite",
"(",
"self",
")",
"while",
"token",
"is",
"not",
"None",
":",
"token",
",",
"_",
",",
"_",
"=",
"self",
".",
"rewrite",
"(",
"self",
",",
"token",
"=",
"token",
")"
] | Update blob's storage class via a rewrite-in-place. This helper will
wait for the rewrite to complete before returning, so it may take some
time for large files.
See
https://cloud.google.com/storage/docs/per-object-storage-class
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type new_class: str
:param new_class: new storage class for the object
:type client: :class:`~google.cloud.storage.client.Client`
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket. | [
"Update",
"blob",
"s",
"storage",
"class",
"via",
"a",
"rewrite",
"-",
"in",
"-",
"place",
".",
"This",
"helper",
"will",
"wait",
"for",
"the",
"rewrite",
"to",
"complete",
"before",
"returning",
"so",
"it",
"may",
"take",
"some",
"time",
"for",
"large",
"files",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/blob.py#L1592-L1619 |
28,102 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | verify_path | def verify_path(path, is_collection):
"""Verifies that a ``path`` has the correct form.
Checks that all of the elements in ``path`` are strings.
Args:
path (Tuple[str, ...]): The components in a collection or
document path.
is_collection (bool): Indicates if the ``path`` represents
a document or a collection.
Raises:
ValueError: if
* the ``path`` is empty
* ``is_collection=True`` and there are an even number of elements
* ``is_collection=False`` and there are an odd number of elements
* an element is not a string
"""
num_elements = len(path)
if num_elements == 0:
raise ValueError("Document or collection path cannot be empty")
if is_collection:
if num_elements % 2 == 0:
raise ValueError("A collection must have an odd number of path elements")
else:
if num_elements % 2 == 1:
raise ValueError("A document must have an even number of path elements")
for element in path:
if not isinstance(element, six.string_types):
msg = BAD_PATH_TEMPLATE.format(element, type(element))
raise ValueError(msg) | python | def verify_path(path, is_collection):
"""Verifies that a ``path`` has the correct form.
Checks that all of the elements in ``path`` are strings.
Args:
path (Tuple[str, ...]): The components in a collection or
document path.
is_collection (bool): Indicates if the ``path`` represents
a document or a collection.
Raises:
ValueError: if
* the ``path`` is empty
* ``is_collection=True`` and there are an even number of elements
* ``is_collection=False`` and there are an odd number of elements
* an element is not a string
"""
num_elements = len(path)
if num_elements == 0:
raise ValueError("Document or collection path cannot be empty")
if is_collection:
if num_elements % 2 == 0:
raise ValueError("A collection must have an odd number of path elements")
else:
if num_elements % 2 == 1:
raise ValueError("A document must have an even number of path elements")
for element in path:
if not isinstance(element, six.string_types):
msg = BAD_PATH_TEMPLATE.format(element, type(element))
raise ValueError(msg) | [
"def",
"verify_path",
"(",
"path",
",",
"is_collection",
")",
":",
"num_elements",
"=",
"len",
"(",
"path",
")",
"if",
"num_elements",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Document or collection path cannot be empty\"",
")",
"if",
"is_collection",
":",
"if",
"num_elements",
"%",
"2",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"A collection must have an odd number of path elements\"",
")",
"else",
":",
"if",
"num_elements",
"%",
"2",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"\"A document must have an even number of path elements\"",
")",
"for",
"element",
"in",
"path",
":",
"if",
"not",
"isinstance",
"(",
"element",
",",
"six",
".",
"string_types",
")",
":",
"msg",
"=",
"BAD_PATH_TEMPLATE",
".",
"format",
"(",
"element",
",",
"type",
"(",
"element",
")",
")",
"raise",
"ValueError",
"(",
"msg",
")"
] | Verifies that a ``path`` has the correct form.
Checks that all of the elements in ``path`` are strings.
Args:
path (Tuple[str, ...]): The components in a collection or
document path.
is_collection (bool): Indicates if the ``path`` represents
a document or a collection.
Raises:
ValueError: if
* the ``path`` is empty
* ``is_collection=True`` and there are an even number of elements
* ``is_collection=False`` and there are an odd number of elements
* an element is not a string | [
"Verifies",
"that",
"a",
"path",
"has",
"the",
"correct",
"form",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L104-L137 |
28,103 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | encode_value | def encode_value(value):
"""Converts a native Python value into a Firestore protobuf ``Value``.
Args:
value (Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]): A native
Python value to convert to a protobuf field.
Returns:
~google.cloud.firestore_v1beta1.types.Value: A
value encoded as a Firestore protobuf.
Raises:
TypeError: If the ``value`` is not one of the accepted types.
"""
if value is None:
return document_pb2.Value(null_value=struct_pb2.NULL_VALUE)
# Must come before six.integer_types since ``bool`` is an integer subtype.
if isinstance(value, bool):
return document_pb2.Value(boolean_value=value)
if isinstance(value, six.integer_types):
return document_pb2.Value(integer_value=value)
if isinstance(value, float):
return document_pb2.Value(double_value=value)
if isinstance(value, DatetimeWithNanoseconds):
return document_pb2.Value(timestamp_value=value.timestamp_pb())
if isinstance(value, datetime.datetime):
return document_pb2.Value(timestamp_value=_datetime_to_pb_timestamp(value))
if isinstance(value, six.text_type):
return document_pb2.Value(string_value=value)
if isinstance(value, six.binary_type):
return document_pb2.Value(bytes_value=value)
# NOTE: We avoid doing an isinstance() check for a Document
# here to avoid import cycles.
document_path = getattr(value, "_document_path", None)
if document_path is not None:
return document_pb2.Value(reference_value=document_path)
if isinstance(value, GeoPoint):
return document_pb2.Value(geo_point_value=value.to_protobuf())
if isinstance(value, list):
value_list = [encode_value(element) for element in value]
value_pb = document_pb2.ArrayValue(values=value_list)
return document_pb2.Value(array_value=value_pb)
if isinstance(value, dict):
value_dict = encode_dict(value)
value_pb = document_pb2.MapValue(fields=value_dict)
return document_pb2.Value(map_value=value_pb)
raise TypeError(
"Cannot convert to a Firestore Value", value, "Invalid type", type(value)
) | python | def encode_value(value):
"""Converts a native Python value into a Firestore protobuf ``Value``.
Args:
value (Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]): A native
Python value to convert to a protobuf field.
Returns:
~google.cloud.firestore_v1beta1.types.Value: A
value encoded as a Firestore protobuf.
Raises:
TypeError: If the ``value`` is not one of the accepted types.
"""
if value is None:
return document_pb2.Value(null_value=struct_pb2.NULL_VALUE)
# Must come before six.integer_types since ``bool`` is an integer subtype.
if isinstance(value, bool):
return document_pb2.Value(boolean_value=value)
if isinstance(value, six.integer_types):
return document_pb2.Value(integer_value=value)
if isinstance(value, float):
return document_pb2.Value(double_value=value)
if isinstance(value, DatetimeWithNanoseconds):
return document_pb2.Value(timestamp_value=value.timestamp_pb())
if isinstance(value, datetime.datetime):
return document_pb2.Value(timestamp_value=_datetime_to_pb_timestamp(value))
if isinstance(value, six.text_type):
return document_pb2.Value(string_value=value)
if isinstance(value, six.binary_type):
return document_pb2.Value(bytes_value=value)
# NOTE: We avoid doing an isinstance() check for a Document
# here to avoid import cycles.
document_path = getattr(value, "_document_path", None)
if document_path is not None:
return document_pb2.Value(reference_value=document_path)
if isinstance(value, GeoPoint):
return document_pb2.Value(geo_point_value=value.to_protobuf())
if isinstance(value, list):
value_list = [encode_value(element) for element in value]
value_pb = document_pb2.ArrayValue(values=value_list)
return document_pb2.Value(array_value=value_pb)
if isinstance(value, dict):
value_dict = encode_dict(value)
value_pb = document_pb2.MapValue(fields=value_dict)
return document_pb2.Value(map_value=value_pb)
raise TypeError(
"Cannot convert to a Firestore Value", value, "Invalid type", type(value)
) | [
"def",
"encode_value",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"null_value",
"=",
"struct_pb2",
".",
"NULL_VALUE",
")",
"# Must come before six.integer_types since ``bool`` is an integer subtype.",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"boolean_value",
"=",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"integer_value",
"=",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"double_value",
"=",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"DatetimeWithNanoseconds",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"timestamp_value",
"=",
"value",
".",
"timestamp_pb",
"(",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"timestamp_value",
"=",
"_datetime_to_pb_timestamp",
"(",
"value",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"text_type",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"string_value",
"=",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"bytes_value",
"=",
"value",
")",
"# NOTE: We avoid doing an isinstance() check for a Document",
"# here to avoid import cycles.",
"document_path",
"=",
"getattr",
"(",
"value",
",",
"\"_document_path\"",
",",
"None",
")",
"if",
"document_path",
"is",
"not",
"None",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"reference_value",
"=",
"document_path",
")",
"if",
"isinstance",
"(",
"value",
",",
"GeoPoint",
")",
":",
"return",
"document_pb2",
".",
"Value",
"(",
"geo_point_value",
"=",
"value",
".",
"to_protobuf",
"(",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value_list",
"=",
"[",
"encode_value",
"(",
"element",
")",
"for",
"element",
"in",
"value",
"]",
"value_pb",
"=",
"document_pb2",
".",
"ArrayValue",
"(",
"values",
"=",
"value_list",
")",
"return",
"document_pb2",
".",
"Value",
"(",
"array_value",
"=",
"value_pb",
")",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"value_dict",
"=",
"encode_dict",
"(",
"value",
")",
"value_pb",
"=",
"document_pb2",
".",
"MapValue",
"(",
"fields",
"=",
"value_dict",
")",
"return",
"document_pb2",
".",
"Value",
"(",
"map_value",
"=",
"value_pb",
")",
"raise",
"TypeError",
"(",
"\"Cannot convert to a Firestore Value\"",
",",
"value",
",",
"\"Invalid type\"",
",",
"type",
"(",
"value",
")",
")"
] | Converts a native Python value into a Firestore protobuf ``Value``.
Args:
value (Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]): A native
Python value to convert to a protobuf field.
Returns:
~google.cloud.firestore_v1beta1.types.Value: A
value encoded as a Firestore protobuf.
Raises:
TypeError: If the ``value`` is not one of the accepted types. | [
"Converts",
"a",
"native",
"Python",
"value",
"into",
"a",
"Firestore",
"protobuf",
"Value",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L140-L201 |
28,104 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | encode_dict | def encode_dict(values_dict):
"""Encode a dictionary into protobuf ``Value``-s.
Args:
values_dict (dict): The dictionary to encode as protobuf fields.
Returns:
Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A
dictionary of string keys and ``Value`` protobufs as dictionary
values.
"""
return {key: encode_value(value) for key, value in six.iteritems(values_dict)} | python | def encode_dict(values_dict):
"""Encode a dictionary into protobuf ``Value``-s.
Args:
values_dict (dict): The dictionary to encode as protobuf fields.
Returns:
Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A
dictionary of string keys and ``Value`` protobufs as dictionary
values.
"""
return {key: encode_value(value) for key, value in six.iteritems(values_dict)} | [
"def",
"encode_dict",
"(",
"values_dict",
")",
":",
"return",
"{",
"key",
":",
"encode_value",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"values_dict",
")",
"}"
] | Encode a dictionary into protobuf ``Value``-s.
Args:
values_dict (dict): The dictionary to encode as protobuf fields.
Returns:
Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A
dictionary of string keys and ``Value`` protobufs as dictionary
values. | [
"Encode",
"a",
"dictionary",
"into",
"protobuf",
"Value",
"-",
"s",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L204-L215 |
28,105 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | reference_value_to_document | def reference_value_to_document(reference_value, client):
"""Convert a reference value string to a document.
Args:
reference_value (str): A document reference value.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
~.firestore_v1beta1.document.DocumentReference: The document
corresponding to ``reference_value``.
Raises:
ValueError: If the ``reference_value`` is not of the expected
format: ``projects/{project}/databases/{database}/documents/...``.
ValueError: If the ``reference_value`` does not come from the same
project / database combination as the ``client``.
"""
# The first 5 parts are
# projects, {project}, databases, {database}, documents
parts = reference_value.split(DOCUMENT_PATH_DELIMITER, 5)
if len(parts) != 6:
msg = BAD_REFERENCE_ERROR.format(reference_value)
raise ValueError(msg)
# The sixth part is `a/b/c/d` (i.e. the document path)
document = client.document(parts[-1])
if document._document_path != reference_value:
msg = WRONG_APP_REFERENCE.format(reference_value, client._database_string)
raise ValueError(msg)
return document | python | def reference_value_to_document(reference_value, client):
"""Convert a reference value string to a document.
Args:
reference_value (str): A document reference value.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
~.firestore_v1beta1.document.DocumentReference: The document
corresponding to ``reference_value``.
Raises:
ValueError: If the ``reference_value`` is not of the expected
format: ``projects/{project}/databases/{database}/documents/...``.
ValueError: If the ``reference_value`` does not come from the same
project / database combination as the ``client``.
"""
# The first 5 parts are
# projects, {project}, databases, {database}, documents
parts = reference_value.split(DOCUMENT_PATH_DELIMITER, 5)
if len(parts) != 6:
msg = BAD_REFERENCE_ERROR.format(reference_value)
raise ValueError(msg)
# The sixth part is `a/b/c/d` (i.e. the document path)
document = client.document(parts[-1])
if document._document_path != reference_value:
msg = WRONG_APP_REFERENCE.format(reference_value, client._database_string)
raise ValueError(msg)
return document | [
"def",
"reference_value_to_document",
"(",
"reference_value",
",",
"client",
")",
":",
"# The first 5 parts are",
"# projects, {project}, databases, {database}, documents",
"parts",
"=",
"reference_value",
".",
"split",
"(",
"DOCUMENT_PATH_DELIMITER",
",",
"5",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"6",
":",
"msg",
"=",
"BAD_REFERENCE_ERROR",
".",
"format",
"(",
"reference_value",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"# The sixth part is `a/b/c/d` (i.e. the document path)",
"document",
"=",
"client",
".",
"document",
"(",
"parts",
"[",
"-",
"1",
"]",
")",
"if",
"document",
".",
"_document_path",
"!=",
"reference_value",
":",
"msg",
"=",
"WRONG_APP_REFERENCE",
".",
"format",
"(",
"reference_value",
",",
"client",
".",
"_database_string",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"return",
"document"
] | Convert a reference value string to a document.
Args:
reference_value (str): A document reference value.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
~.firestore_v1beta1.document.DocumentReference: The document
corresponding to ``reference_value``.
Raises:
ValueError: If the ``reference_value`` is not of the expected
format: ``projects/{project}/databases/{database}/documents/...``.
ValueError: If the ``reference_value`` does not come from the same
project / database combination as the ``client``. | [
"Convert",
"a",
"reference",
"value",
"string",
"to",
"a",
"document",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L218-L249 |
28,106 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | decode_value | def decode_value(value, client):
"""Converts a Firestore protobuf ``Value`` to a native Python value.
Args:
value (google.cloud.firestore_v1beta1.types.Value): A
Firestore protobuf to be decoded / parsed / converted.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]: A native
Python value converted from the ``value``.
Raises:
NotImplementedError: If the ``value_type`` is ``reference_value``.
ValueError: If the ``value_type`` is unknown.
"""
value_type = value.WhichOneof("value_type")
if value_type == "null_value":
return None
elif value_type == "boolean_value":
return value.boolean_value
elif value_type == "integer_value":
return value.integer_value
elif value_type == "double_value":
return value.double_value
elif value_type == "timestamp_value":
return DatetimeWithNanoseconds.from_timestamp_pb(value.timestamp_value)
elif value_type == "string_value":
return value.string_value
elif value_type == "bytes_value":
return value.bytes_value
elif value_type == "reference_value":
return reference_value_to_document(value.reference_value, client)
elif value_type == "geo_point_value":
return GeoPoint(value.geo_point_value.latitude, value.geo_point_value.longitude)
elif value_type == "array_value":
return [decode_value(element, client) for element in value.array_value.values]
elif value_type == "map_value":
return decode_dict(value.map_value.fields, client)
else:
raise ValueError("Unknown ``value_type``", value_type) | python | def decode_value(value, client):
"""Converts a Firestore protobuf ``Value`` to a native Python value.
Args:
value (google.cloud.firestore_v1beta1.types.Value): A
Firestore protobuf to be decoded / parsed / converted.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]: A native
Python value converted from the ``value``.
Raises:
NotImplementedError: If the ``value_type`` is ``reference_value``.
ValueError: If the ``value_type`` is unknown.
"""
value_type = value.WhichOneof("value_type")
if value_type == "null_value":
return None
elif value_type == "boolean_value":
return value.boolean_value
elif value_type == "integer_value":
return value.integer_value
elif value_type == "double_value":
return value.double_value
elif value_type == "timestamp_value":
return DatetimeWithNanoseconds.from_timestamp_pb(value.timestamp_value)
elif value_type == "string_value":
return value.string_value
elif value_type == "bytes_value":
return value.bytes_value
elif value_type == "reference_value":
return reference_value_to_document(value.reference_value, client)
elif value_type == "geo_point_value":
return GeoPoint(value.geo_point_value.latitude, value.geo_point_value.longitude)
elif value_type == "array_value":
return [decode_value(element, client) for element in value.array_value.values]
elif value_type == "map_value":
return decode_dict(value.map_value.fields, client)
else:
raise ValueError("Unknown ``value_type``", value_type) | [
"def",
"decode_value",
"(",
"value",
",",
"client",
")",
":",
"value_type",
"=",
"value",
".",
"WhichOneof",
"(",
"\"value_type\"",
")",
"if",
"value_type",
"==",
"\"null_value\"",
":",
"return",
"None",
"elif",
"value_type",
"==",
"\"boolean_value\"",
":",
"return",
"value",
".",
"boolean_value",
"elif",
"value_type",
"==",
"\"integer_value\"",
":",
"return",
"value",
".",
"integer_value",
"elif",
"value_type",
"==",
"\"double_value\"",
":",
"return",
"value",
".",
"double_value",
"elif",
"value_type",
"==",
"\"timestamp_value\"",
":",
"return",
"DatetimeWithNanoseconds",
".",
"from_timestamp_pb",
"(",
"value",
".",
"timestamp_value",
")",
"elif",
"value_type",
"==",
"\"string_value\"",
":",
"return",
"value",
".",
"string_value",
"elif",
"value_type",
"==",
"\"bytes_value\"",
":",
"return",
"value",
".",
"bytes_value",
"elif",
"value_type",
"==",
"\"reference_value\"",
":",
"return",
"reference_value_to_document",
"(",
"value",
".",
"reference_value",
",",
"client",
")",
"elif",
"value_type",
"==",
"\"geo_point_value\"",
":",
"return",
"GeoPoint",
"(",
"value",
".",
"geo_point_value",
".",
"latitude",
",",
"value",
".",
"geo_point_value",
".",
"longitude",
")",
"elif",
"value_type",
"==",
"\"array_value\"",
":",
"return",
"[",
"decode_value",
"(",
"element",
",",
"client",
")",
"for",
"element",
"in",
"value",
".",
"array_value",
".",
"values",
"]",
"elif",
"value_type",
"==",
"\"map_value\"",
":",
"return",
"decode_dict",
"(",
"value",
".",
"map_value",
".",
"fields",
",",
"client",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown ``value_type``\"",
",",
"value_type",
")"
] | Converts a Firestore protobuf ``Value`` to a native Python value.
Args:
value (google.cloud.firestore_v1beta1.types.Value): A
Firestore protobuf to be decoded / parsed / converted.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]: A native
Python value converted from the ``value``.
Raises:
NotImplementedError: If the ``value_type`` is ``reference_value``.
ValueError: If the ``value_type`` is unknown. | [
"Converts",
"a",
"Firestore",
"protobuf",
"Value",
"to",
"a",
"native",
"Python",
"value",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L252-L295 |
28,107 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | decode_dict | def decode_dict(value_fields, client):
"""Converts a protobuf map of Firestore ``Value``-s.
Args:
value_fields (google.protobuf.pyext._message.MessageMapContainer): A
protobuf map of Firestore ``Value``-s.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Dict[str, Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]]: A dictionary
of native Python values converted from the ``value_fields``.
"""
return {
key: decode_value(value, client) for key, value in six.iteritems(value_fields)
} | python | def decode_dict(value_fields, client):
"""Converts a protobuf map of Firestore ``Value``-s.
Args:
value_fields (google.protobuf.pyext._message.MessageMapContainer): A
protobuf map of Firestore ``Value``-s.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Dict[str, Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]]: A dictionary
of native Python values converted from the ``value_fields``.
"""
return {
key: decode_value(value, client) for key, value in six.iteritems(value_fields)
} | [
"def",
"decode_dict",
"(",
"value_fields",
",",
"client",
")",
":",
"return",
"{",
"key",
":",
"decode_value",
"(",
"value",
",",
"client",
")",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"value_fields",
")",
"}"
] | Converts a protobuf map of Firestore ``Value``-s.
Args:
value_fields (google.protobuf.pyext._message.MessageMapContainer): A
protobuf map of Firestore ``Value``-s.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
Dict[str, Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]]: A dictionary
of native Python values converted from the ``value_fields``. | [
"Converts",
"a",
"protobuf",
"map",
"of",
"Firestore",
"Value",
"-",
"s",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L298-L314 |
28,108 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | get_doc_id | def get_doc_id(document_pb, expected_prefix):
"""Parse a document ID from a document protobuf.
Args:
document_pb (google.cloud.proto.firestore.v1beta1.\
document_pb2.Document): A protobuf for a document that
was created in a ``CreateDocument`` RPC.
expected_prefix (str): The expected collection prefix for the
fully-qualified document name.
Returns:
str: The document ID from the protobuf.
Raises:
ValueError: If the name does not begin with the prefix.
"""
prefix, document_id = document_pb.name.rsplit(DOCUMENT_PATH_DELIMITER, 1)
if prefix != expected_prefix:
raise ValueError(
"Unexpected document name",
document_pb.name,
"Expected to begin with",
expected_prefix,
)
return document_id | python | def get_doc_id(document_pb, expected_prefix):
"""Parse a document ID from a document protobuf.
Args:
document_pb (google.cloud.proto.firestore.v1beta1.\
document_pb2.Document): A protobuf for a document that
was created in a ``CreateDocument`` RPC.
expected_prefix (str): The expected collection prefix for the
fully-qualified document name.
Returns:
str: The document ID from the protobuf.
Raises:
ValueError: If the name does not begin with the prefix.
"""
prefix, document_id = document_pb.name.rsplit(DOCUMENT_PATH_DELIMITER, 1)
if prefix != expected_prefix:
raise ValueError(
"Unexpected document name",
document_pb.name,
"Expected to begin with",
expected_prefix,
)
return document_id | [
"def",
"get_doc_id",
"(",
"document_pb",
",",
"expected_prefix",
")",
":",
"prefix",
",",
"document_id",
"=",
"document_pb",
".",
"name",
".",
"rsplit",
"(",
"DOCUMENT_PATH_DELIMITER",
",",
"1",
")",
"if",
"prefix",
"!=",
"expected_prefix",
":",
"raise",
"ValueError",
"(",
"\"Unexpected document name\"",
",",
"document_pb",
".",
"name",
",",
"\"Expected to begin with\"",
",",
"expected_prefix",
",",
")",
"return",
"document_id"
] | Parse a document ID from a document protobuf.
Args:
document_pb (google.cloud.proto.firestore.v1beta1.\
document_pb2.Document): A protobuf for a document that
was created in a ``CreateDocument`` RPC.
expected_prefix (str): The expected collection prefix for the
fully-qualified document name.
Returns:
str: The document ID from the protobuf.
Raises:
ValueError: If the name does not begin with the prefix. | [
"Parse",
"a",
"document",
"ID",
"from",
"a",
"document",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L317-L342 |
28,109 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | extract_fields | def extract_fields(document_data, prefix_path, expand_dots=False):
"""Do depth-first walk of tree, yielding field_path, value"""
if not document_data:
yield prefix_path, _EmptyDict
else:
for key, value in sorted(six.iteritems(document_data)):
if expand_dots:
sub_key = FieldPath.from_string(key)
else:
sub_key = FieldPath(key)
field_path = FieldPath(*(prefix_path.parts + sub_key.parts))
if isinstance(value, dict):
for s_path, s_value in extract_fields(value, field_path):
yield s_path, s_value
else:
yield field_path, value | python | def extract_fields(document_data, prefix_path, expand_dots=False):
"""Do depth-first walk of tree, yielding field_path, value"""
if not document_data:
yield prefix_path, _EmptyDict
else:
for key, value in sorted(six.iteritems(document_data)):
if expand_dots:
sub_key = FieldPath.from_string(key)
else:
sub_key = FieldPath(key)
field_path = FieldPath(*(prefix_path.parts + sub_key.parts))
if isinstance(value, dict):
for s_path, s_value in extract_fields(value, field_path):
yield s_path, s_value
else:
yield field_path, value | [
"def",
"extract_fields",
"(",
"document_data",
",",
"prefix_path",
",",
"expand_dots",
"=",
"False",
")",
":",
"if",
"not",
"document_data",
":",
"yield",
"prefix_path",
",",
"_EmptyDict",
"else",
":",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"six",
".",
"iteritems",
"(",
"document_data",
")",
")",
":",
"if",
"expand_dots",
":",
"sub_key",
"=",
"FieldPath",
".",
"from_string",
"(",
"key",
")",
"else",
":",
"sub_key",
"=",
"FieldPath",
"(",
"key",
")",
"field_path",
"=",
"FieldPath",
"(",
"*",
"(",
"prefix_path",
".",
"parts",
"+",
"sub_key",
".",
"parts",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"for",
"s_path",
",",
"s_value",
"in",
"extract_fields",
"(",
"value",
",",
"field_path",
")",
":",
"yield",
"s_path",
",",
"s_value",
"else",
":",
"yield",
"field_path",
",",
"value"
] | Do depth-first walk of tree, yielding field_path, value | [
"Do",
"depth",
"-",
"first",
"walk",
"of",
"tree",
"yielding",
"field_path",
"value"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L348-L366 |
28,110 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | set_field_value | def set_field_value(document_data, field_path, value):
"""Set a value into a document for a field_path"""
current = document_data
for element in field_path.parts[:-1]:
current = current.setdefault(element, {})
if value is _EmptyDict:
value = {}
current[field_path.parts[-1]] = value | python | def set_field_value(document_data, field_path, value):
"""Set a value into a document for a field_path"""
current = document_data
for element in field_path.parts[:-1]:
current = current.setdefault(element, {})
if value is _EmptyDict:
value = {}
current[field_path.parts[-1]] = value | [
"def",
"set_field_value",
"(",
"document_data",
",",
"field_path",
",",
"value",
")",
":",
"current",
"=",
"document_data",
"for",
"element",
"in",
"field_path",
".",
"parts",
"[",
":",
"-",
"1",
"]",
":",
"current",
"=",
"current",
".",
"setdefault",
"(",
"element",
",",
"{",
"}",
")",
"if",
"value",
"is",
"_EmptyDict",
":",
"value",
"=",
"{",
"}",
"current",
"[",
"field_path",
".",
"parts",
"[",
"-",
"1",
"]",
"]",
"=",
"value"
] | Set a value into a document for a field_path | [
"Set",
"a",
"value",
"into",
"a",
"document",
"for",
"a",
"field_path"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L369-L376 |
28,111 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | get_transaction_id | def get_transaction_id(transaction, read_operation=True):
"""Get the transaction ID from a ``Transaction`` object.
Args:
transaction (Optional[~.firestore_v1beta1.transaction.\
Transaction]): An existing transaction that this query will
run in.
read_operation (Optional[bool]): Indicates if the transaction ID
will be used in a read operation. Defaults to :data:`True`.
Returns:
Optional[bytes]: The ID of the transaction, or :data:`None` if the
``transaction`` is :data:`None`.
Raises:
ValueError: If the ``transaction`` is not in progress (only if
``transaction`` is not :data:`None`).
ReadAfterWriteError: If the ``transaction`` has writes stored on
it and ``read_operation`` is :data:`True`.
"""
if transaction is None:
return None
else:
if not transaction.in_progress:
raise ValueError(INACTIVE_TXN)
if read_operation and len(transaction._write_pbs) > 0:
raise ReadAfterWriteError(READ_AFTER_WRITE_ERROR)
return transaction.id | python | def get_transaction_id(transaction, read_operation=True):
"""Get the transaction ID from a ``Transaction`` object.
Args:
transaction (Optional[~.firestore_v1beta1.transaction.\
Transaction]): An existing transaction that this query will
run in.
read_operation (Optional[bool]): Indicates if the transaction ID
will be used in a read operation. Defaults to :data:`True`.
Returns:
Optional[bytes]: The ID of the transaction, or :data:`None` if the
``transaction`` is :data:`None`.
Raises:
ValueError: If the ``transaction`` is not in progress (only if
``transaction`` is not :data:`None`).
ReadAfterWriteError: If the ``transaction`` has writes stored on
it and ``read_operation`` is :data:`True`.
"""
if transaction is None:
return None
else:
if not transaction.in_progress:
raise ValueError(INACTIVE_TXN)
if read_operation and len(transaction._write_pbs) > 0:
raise ReadAfterWriteError(READ_AFTER_WRITE_ERROR)
return transaction.id | [
"def",
"get_transaction_id",
"(",
"transaction",
",",
"read_operation",
"=",
"True",
")",
":",
"if",
"transaction",
"is",
"None",
":",
"return",
"None",
"else",
":",
"if",
"not",
"transaction",
".",
"in_progress",
":",
"raise",
"ValueError",
"(",
"INACTIVE_TXN",
")",
"if",
"read_operation",
"and",
"len",
"(",
"transaction",
".",
"_write_pbs",
")",
">",
"0",
":",
"raise",
"ReadAfterWriteError",
"(",
"READ_AFTER_WRITE_ERROR",
")",
"return",
"transaction",
".",
"id"
] | Get the transaction ID from a ``Transaction`` object.
Args:
transaction (Optional[~.firestore_v1beta1.transaction.\
Transaction]): An existing transaction that this query will
run in.
read_operation (Optional[bool]): Indicates if the transaction ID
will be used in a read operation. Defaults to :data:`True`.
Returns:
Optional[bytes]: The ID of the transaction, or :data:`None` if the
``transaction`` is :data:`None`.
Raises:
ValueError: If the ``transaction`` is not in progress (only if
``transaction`` is not :data:`None`).
ReadAfterWriteError: If the ``transaction`` has writes stored on
it and ``read_operation`` is :data:`True`. | [
"Get",
"the",
"transaction",
"ID",
"from",
"a",
"Transaction",
"object",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L864-L891 |
28,112 | googleapis/google-cloud-python | monitoring/google/cloud/monitoring_v3/gapic/uptime_check_service_client.py | UptimeCheckServiceClient.uptime_check_config_path | def uptime_check_config_path(cls, project, uptime_check_config):
"""Return a fully-qualified uptime_check_config string."""
return google.api_core.path_template.expand(
"projects/{project}/uptimeCheckConfigs/{uptime_check_config}",
project=project,
uptime_check_config=uptime_check_config,
) | python | def uptime_check_config_path(cls, project, uptime_check_config):
"""Return a fully-qualified uptime_check_config string."""
return google.api_core.path_template.expand(
"projects/{project}/uptimeCheckConfigs/{uptime_check_config}",
project=project,
uptime_check_config=uptime_check_config,
) | [
"def",
"uptime_check_config_path",
"(",
"cls",
",",
"project",
",",
"uptime_check_config",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/uptimeCheckConfigs/{uptime_check_config}\"",
",",
"project",
"=",
"project",
",",
"uptime_check_config",
"=",
"uptime_check_config",
",",
")"
] | Return a fully-qualified uptime_check_config string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"uptime_check_config",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/gapic/uptime_check_service_client.py#L110-L116 |
28,113 | googleapis/google-cloud-python | monitoring/google/cloud/monitoring_v3/gapic/uptime_check_service_client.py | UptimeCheckServiceClient.create_uptime_check_config | def create_uptime_check_config(
self,
parent,
uptime_check_config,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a new uptime check configuration.
Example:
>>> from google.cloud import monitoring_v3
>>>
>>> client = monitoring_v3.UptimeCheckServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `uptime_check_config`:
>>> uptime_check_config = {}
>>>
>>> response = client.create_uptime_check_config(parent, uptime_check_config)
Args:
parent (str): The project in which to create the uptime check. The format is
``projects/[PROJECT_ID]``.
uptime_check_config (Union[dict, ~google.cloud.monitoring_v3.types.UptimeCheckConfig]): The new uptime check configuration.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.monitoring_v3.types.UptimeCheckConfig`
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.monitoring_v3.types.UptimeCheckConfig` 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.
"""
if metadata is None:
metadata = []
metadata = list(metadata)
# Wrap the transport method to add retry and timeout logic.
if "create_uptime_check_config" not in self._inner_api_calls:
self._inner_api_calls[
"create_uptime_check_config"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_uptime_check_config,
default_retry=self._method_configs["CreateUptimeCheckConfig"].retry,
default_timeout=self._method_configs["CreateUptimeCheckConfig"].timeout,
client_info=self._client_info,
)
request = uptime_service_pb2.CreateUptimeCheckConfigRequest(
parent=parent, uptime_check_config=uptime_check_config
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["create_uptime_check_config"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def create_uptime_check_config(
self,
parent,
uptime_check_config,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a new uptime check configuration.
Example:
>>> from google.cloud import monitoring_v3
>>>
>>> client = monitoring_v3.UptimeCheckServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `uptime_check_config`:
>>> uptime_check_config = {}
>>>
>>> response = client.create_uptime_check_config(parent, uptime_check_config)
Args:
parent (str): The project in which to create the uptime check. The format is
``projects/[PROJECT_ID]``.
uptime_check_config (Union[dict, ~google.cloud.monitoring_v3.types.UptimeCheckConfig]): The new uptime check configuration.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.monitoring_v3.types.UptimeCheckConfig`
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.monitoring_v3.types.UptimeCheckConfig` 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.
"""
if metadata is None:
metadata = []
metadata = list(metadata)
# Wrap the transport method to add retry and timeout logic.
if "create_uptime_check_config" not in self._inner_api_calls:
self._inner_api_calls[
"create_uptime_check_config"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_uptime_check_config,
default_retry=self._method_configs["CreateUptimeCheckConfig"].retry,
default_timeout=self._method_configs["CreateUptimeCheckConfig"].timeout,
client_info=self._client_info,
)
request = uptime_service_pb2.CreateUptimeCheckConfigRequest(
parent=parent, uptime_check_config=uptime_check_config
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("parent", parent)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["create_uptime_check_config"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"create_uptime_check_config",
"(",
"self",
",",
"parent",
",",
"uptime_check_config",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"create_uptime_check_config\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"create_uptime_check_config\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_uptime_check_config",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateUptimeCheckConfig\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateUptimeCheckConfig\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"uptime_service_pb2",
".",
"CreateUptimeCheckConfigRequest",
"(",
"parent",
"=",
"parent",
",",
"uptime_check_config",
"=",
"uptime_check_config",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"parent\"",
",",
"parent",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"create_uptime_check_config\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Creates a new uptime check configuration.
Example:
>>> from google.cloud import monitoring_v3
>>>
>>> client = monitoring_v3.UptimeCheckServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `uptime_check_config`:
>>> uptime_check_config = {}
>>>
>>> response = client.create_uptime_check_config(parent, uptime_check_config)
Args:
parent (str): The project in which to create the uptime check. The format is
``projects/[PROJECT_ID]``.
uptime_check_config (Union[dict, ~google.cloud.monitoring_v3.types.UptimeCheckConfig]): The new uptime check configuration.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.monitoring_v3.types.UptimeCheckConfig`
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.monitoring_v3.types.UptimeCheckConfig` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Creates",
"a",
"new",
"uptime",
"check",
"configuration",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/gapic/uptime_check_service_client.py#L398-L479 |
28,114 | googleapis/google-cloud-python | api_core/google/api_core/iam.py | Policy.owners | def owners(self):
"""Legacy access to owner role.
DEPRECATED: use ``policy["roles/owners"]`` instead."""
result = set()
for role in self._OWNER_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) | python | def owners(self):
"""Legacy access to owner role.
DEPRECATED: use ``policy["roles/owners"]`` instead."""
result = set()
for role in self._OWNER_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) | [
"def",
"owners",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"role",
"in",
"self",
".",
"_OWNER_ROLES",
":",
"for",
"member",
"in",
"self",
".",
"_bindings",
".",
"get",
"(",
"role",
",",
"(",
")",
")",
":",
"result",
".",
"add",
"(",
"member",
")",
"return",
"frozenset",
"(",
"result",
")"
] | Legacy access to owner role.
DEPRECATED: use ``policy["roles/owners"]`` instead. | [
"Legacy",
"access",
"to",
"owner",
"role",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/iam.py#L99-L107 |
28,115 | googleapis/google-cloud-python | api_core/google/api_core/iam.py | Policy.owners | def owners(self, value):
"""Update owners.
DEPRECATED: use ``policy["roles/owners"] = value`` instead."""
warnings.warn(
_ASSIGNMENT_DEPRECATED_MSG.format("owners", OWNER_ROLE), DeprecationWarning
)
self[OWNER_ROLE] = value | python | def owners(self, value):
"""Update owners.
DEPRECATED: use ``policy["roles/owners"] = value`` instead."""
warnings.warn(
_ASSIGNMENT_DEPRECATED_MSG.format("owners", OWNER_ROLE), DeprecationWarning
)
self[OWNER_ROLE] = value | [
"def",
"owners",
"(",
"self",
",",
"value",
")",
":",
"warnings",
".",
"warn",
"(",
"_ASSIGNMENT_DEPRECATED_MSG",
".",
"format",
"(",
"\"owners\"",
",",
"OWNER_ROLE",
")",
",",
"DeprecationWarning",
")",
"self",
"[",
"OWNER_ROLE",
"]",
"=",
"value"
] | Update owners.
DEPRECATED: use ``policy["roles/owners"] = value`` instead. | [
"Update",
"owners",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/iam.py#L110-L117 |
28,116 | googleapis/google-cloud-python | api_core/google/api_core/iam.py | Policy.editors | def editors(self):
"""Legacy access to editor role.
DEPRECATED: use ``policy["roles/editors"]`` instead."""
result = set()
for role in self._EDITOR_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) | python | def editors(self):
"""Legacy access to editor role.
DEPRECATED: use ``policy["roles/editors"]`` instead."""
result = set()
for role in self._EDITOR_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) | [
"def",
"editors",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"role",
"in",
"self",
".",
"_EDITOR_ROLES",
":",
"for",
"member",
"in",
"self",
".",
"_bindings",
".",
"get",
"(",
"role",
",",
"(",
")",
")",
":",
"result",
".",
"add",
"(",
"member",
")",
"return",
"frozenset",
"(",
"result",
")"
] | Legacy access to editor role.
DEPRECATED: use ``policy["roles/editors"]`` instead. | [
"Legacy",
"access",
"to",
"editor",
"role",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/iam.py#L120-L128 |
28,117 | googleapis/google-cloud-python | api_core/google/api_core/iam.py | Policy.editors | def editors(self, value):
"""Update editors.
DEPRECATED: use ``policy["roles/editors"] = value`` instead."""
warnings.warn(
_ASSIGNMENT_DEPRECATED_MSG.format("editors", EDITOR_ROLE),
DeprecationWarning,
)
self[EDITOR_ROLE] = value | python | def editors(self, value):
"""Update editors.
DEPRECATED: use ``policy["roles/editors"] = value`` instead."""
warnings.warn(
_ASSIGNMENT_DEPRECATED_MSG.format("editors", EDITOR_ROLE),
DeprecationWarning,
)
self[EDITOR_ROLE] = value | [
"def",
"editors",
"(",
"self",
",",
"value",
")",
":",
"warnings",
".",
"warn",
"(",
"_ASSIGNMENT_DEPRECATED_MSG",
".",
"format",
"(",
"\"editors\"",
",",
"EDITOR_ROLE",
")",
",",
"DeprecationWarning",
",",
")",
"self",
"[",
"EDITOR_ROLE",
"]",
"=",
"value"
] | Update editors.
DEPRECATED: use ``policy["roles/editors"] = value`` instead. | [
"Update",
"editors",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/iam.py#L131-L139 |
28,118 | googleapis/google-cloud-python | api_core/google/api_core/iam.py | Policy.viewers | def viewers(self):
"""Legacy access to viewer role.
DEPRECATED: use ``policy["roles/viewers"]`` instead
"""
result = set()
for role in self._VIEWER_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) | python | def viewers(self):
"""Legacy access to viewer role.
DEPRECATED: use ``policy["roles/viewers"]`` instead
"""
result = set()
for role in self._VIEWER_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) | [
"def",
"viewers",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"role",
"in",
"self",
".",
"_VIEWER_ROLES",
":",
"for",
"member",
"in",
"self",
".",
"_bindings",
".",
"get",
"(",
"role",
",",
"(",
")",
")",
":",
"result",
".",
"add",
"(",
"member",
")",
"return",
"frozenset",
"(",
"result",
")"
] | Legacy access to viewer role.
DEPRECATED: use ``policy["roles/viewers"]`` instead | [
"Legacy",
"access",
"to",
"viewer",
"role",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/iam.py#L142-L151 |
28,119 | googleapis/google-cloud-python | api_core/google/api_core/iam.py | Policy.viewers | def viewers(self, value):
"""Update viewers.
DEPRECATED: use ``policy["roles/viewers"] = value`` instead.
"""
warnings.warn(
_ASSIGNMENT_DEPRECATED_MSG.format("viewers", VIEWER_ROLE),
DeprecationWarning,
)
self[VIEWER_ROLE] = value | python | def viewers(self, value):
"""Update viewers.
DEPRECATED: use ``policy["roles/viewers"] = value`` instead.
"""
warnings.warn(
_ASSIGNMENT_DEPRECATED_MSG.format("viewers", VIEWER_ROLE),
DeprecationWarning,
)
self[VIEWER_ROLE] = value | [
"def",
"viewers",
"(",
"self",
",",
"value",
")",
":",
"warnings",
".",
"warn",
"(",
"_ASSIGNMENT_DEPRECATED_MSG",
".",
"format",
"(",
"\"viewers\"",
",",
"VIEWER_ROLE",
")",
",",
"DeprecationWarning",
",",
")",
"self",
"[",
"VIEWER_ROLE",
"]",
"=",
"value"
] | Update viewers.
DEPRECATED: use ``policy["roles/viewers"] = value`` instead. | [
"Update",
"viewers",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/iam.py#L154-L163 |
28,120 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | _reference_info | def _reference_info(references):
"""Get information about document references.
Helper for :meth:`~.firestore_v1beta1.client.Client.get_all`.
Args:
references (List[.DocumentReference, ...]): Iterable of document
references.
Returns:
Tuple[List[str, ...], Dict[str, .DocumentReference]]: A two-tuple of
* fully-qualified documents paths for each reference in ``references``
* a mapping from the paths to the original reference. (If multiple
``references`` contains multiple references to the same document,
that key will be overwritten in the result.)
"""
document_paths = []
reference_map = {}
for reference in references:
doc_path = reference._document_path
document_paths.append(doc_path)
reference_map[doc_path] = reference
return document_paths, reference_map | python | def _reference_info(references):
"""Get information about document references.
Helper for :meth:`~.firestore_v1beta1.client.Client.get_all`.
Args:
references (List[.DocumentReference, ...]): Iterable of document
references.
Returns:
Tuple[List[str, ...], Dict[str, .DocumentReference]]: A two-tuple of
* fully-qualified documents paths for each reference in ``references``
* a mapping from the paths to the original reference. (If multiple
``references`` contains multiple references to the same document,
that key will be overwritten in the result.)
"""
document_paths = []
reference_map = {}
for reference in references:
doc_path = reference._document_path
document_paths.append(doc_path)
reference_map[doc_path] = reference
return document_paths, reference_map | [
"def",
"_reference_info",
"(",
"references",
")",
":",
"document_paths",
"=",
"[",
"]",
"reference_map",
"=",
"{",
"}",
"for",
"reference",
"in",
"references",
":",
"doc_path",
"=",
"reference",
".",
"_document_path",
"document_paths",
".",
"append",
"(",
"doc_path",
")",
"reference_map",
"[",
"doc_path",
"]",
"=",
"reference",
"return",
"document_paths",
",",
"reference_map"
] | Get information about document references.
Helper for :meth:`~.firestore_v1beta1.client.Client.get_all`.
Args:
references (List[.DocumentReference, ...]): Iterable of document
references.
Returns:
Tuple[List[str, ...], Dict[str, .DocumentReference]]: A two-tuple of
* fully-qualified documents paths for each reference in ``references``
* a mapping from the paths to the original reference. (If multiple
``references`` contains multiple references to the same document,
that key will be overwritten in the result.) | [
"Get",
"information",
"about",
"document",
"references",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L385-L409 |
28,121 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | _get_reference | def _get_reference(document_path, reference_map):
"""Get a document reference from a dictionary.
This just wraps a simple dictionary look-up with a helpful error that is
specific to :meth:`~.firestore.client.Client.get_all`, the
**public** caller of this function.
Args:
document_path (str): A fully-qualified document path.
reference_map (Dict[str, .DocumentReference]): A mapping (produced
by :func:`_reference_info`) of fully-qualified document paths to
document references.
Returns:
.DocumentReference: The matching reference.
Raises:
ValueError: If ``document_path`` has not been encountered.
"""
try:
return reference_map[document_path]
except KeyError:
msg = _BAD_DOC_TEMPLATE.format(document_path)
raise ValueError(msg) | python | def _get_reference(document_path, reference_map):
"""Get a document reference from a dictionary.
This just wraps a simple dictionary look-up with a helpful error that is
specific to :meth:`~.firestore.client.Client.get_all`, the
**public** caller of this function.
Args:
document_path (str): A fully-qualified document path.
reference_map (Dict[str, .DocumentReference]): A mapping (produced
by :func:`_reference_info`) of fully-qualified document paths to
document references.
Returns:
.DocumentReference: The matching reference.
Raises:
ValueError: If ``document_path`` has not been encountered.
"""
try:
return reference_map[document_path]
except KeyError:
msg = _BAD_DOC_TEMPLATE.format(document_path)
raise ValueError(msg) | [
"def",
"_get_reference",
"(",
"document_path",
",",
"reference_map",
")",
":",
"try",
":",
"return",
"reference_map",
"[",
"document_path",
"]",
"except",
"KeyError",
":",
"msg",
"=",
"_BAD_DOC_TEMPLATE",
".",
"format",
"(",
"document_path",
")",
"raise",
"ValueError",
"(",
"msg",
")"
] | Get a document reference from a dictionary.
This just wraps a simple dictionary look-up with a helpful error that is
specific to :meth:`~.firestore.client.Client.get_all`, the
**public** caller of this function.
Args:
document_path (str): A fully-qualified document path.
reference_map (Dict[str, .DocumentReference]): A mapping (produced
by :func:`_reference_info`) of fully-qualified document paths to
document references.
Returns:
.DocumentReference: The matching reference.
Raises:
ValueError: If ``document_path`` has not been encountered. | [
"Get",
"a",
"document",
"reference",
"from",
"a",
"dictionary",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L412-L435 |
28,122 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | _parse_batch_get | def _parse_batch_get(get_doc_response, reference_map, client):
"""Parse a `BatchGetDocumentsResponse` protobuf.
Args:
get_doc_response (~google.cloud.proto.firestore.v1beta1.\
firestore_pb2.BatchGetDocumentsResponse): A single response (from
a stream) containing the "get" response for a document.
reference_map (Dict[str, .DocumentReference]): A mapping (produced
by :func:`_reference_info`) of fully-qualified document paths to
document references.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
[.DocumentSnapshot]: The retrieved snapshot.
Raises:
ValueError: If the response has a ``result`` field (a oneof) other
than ``found`` or ``missing``.
"""
result_type = get_doc_response.WhichOneof("result")
if result_type == "found":
reference = _get_reference(get_doc_response.found.name, reference_map)
data = _helpers.decode_dict(get_doc_response.found.fields, client)
snapshot = DocumentSnapshot(
reference,
data,
exists=True,
read_time=get_doc_response.read_time,
create_time=get_doc_response.found.create_time,
update_time=get_doc_response.found.update_time,
)
elif result_type == "missing":
snapshot = DocumentSnapshot(
None,
None,
exists=False,
read_time=get_doc_response.read_time,
create_time=None,
update_time=None,
)
else:
raise ValueError(
"`BatchGetDocumentsResponse.result` (a oneof) had a field other "
"than `found` or `missing` set, or was unset"
)
return snapshot | python | def _parse_batch_get(get_doc_response, reference_map, client):
"""Parse a `BatchGetDocumentsResponse` protobuf.
Args:
get_doc_response (~google.cloud.proto.firestore.v1beta1.\
firestore_pb2.BatchGetDocumentsResponse): A single response (from
a stream) containing the "get" response for a document.
reference_map (Dict[str, .DocumentReference]): A mapping (produced
by :func:`_reference_info`) of fully-qualified document paths to
document references.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
[.DocumentSnapshot]: The retrieved snapshot.
Raises:
ValueError: If the response has a ``result`` field (a oneof) other
than ``found`` or ``missing``.
"""
result_type = get_doc_response.WhichOneof("result")
if result_type == "found":
reference = _get_reference(get_doc_response.found.name, reference_map)
data = _helpers.decode_dict(get_doc_response.found.fields, client)
snapshot = DocumentSnapshot(
reference,
data,
exists=True,
read_time=get_doc_response.read_time,
create_time=get_doc_response.found.create_time,
update_time=get_doc_response.found.update_time,
)
elif result_type == "missing":
snapshot = DocumentSnapshot(
None,
None,
exists=False,
read_time=get_doc_response.read_time,
create_time=None,
update_time=None,
)
else:
raise ValueError(
"`BatchGetDocumentsResponse.result` (a oneof) had a field other "
"than `found` or `missing` set, or was unset"
)
return snapshot | [
"def",
"_parse_batch_get",
"(",
"get_doc_response",
",",
"reference_map",
",",
"client",
")",
":",
"result_type",
"=",
"get_doc_response",
".",
"WhichOneof",
"(",
"\"result\"",
")",
"if",
"result_type",
"==",
"\"found\"",
":",
"reference",
"=",
"_get_reference",
"(",
"get_doc_response",
".",
"found",
".",
"name",
",",
"reference_map",
")",
"data",
"=",
"_helpers",
".",
"decode_dict",
"(",
"get_doc_response",
".",
"found",
".",
"fields",
",",
"client",
")",
"snapshot",
"=",
"DocumentSnapshot",
"(",
"reference",
",",
"data",
",",
"exists",
"=",
"True",
",",
"read_time",
"=",
"get_doc_response",
".",
"read_time",
",",
"create_time",
"=",
"get_doc_response",
".",
"found",
".",
"create_time",
",",
"update_time",
"=",
"get_doc_response",
".",
"found",
".",
"update_time",
",",
")",
"elif",
"result_type",
"==",
"\"missing\"",
":",
"snapshot",
"=",
"DocumentSnapshot",
"(",
"None",
",",
"None",
",",
"exists",
"=",
"False",
",",
"read_time",
"=",
"get_doc_response",
".",
"read_time",
",",
"create_time",
"=",
"None",
",",
"update_time",
"=",
"None",
",",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"`BatchGetDocumentsResponse.result` (a oneof) had a field other \"",
"\"than `found` or `missing` set, or was unset\"",
")",
"return",
"snapshot"
] | Parse a `BatchGetDocumentsResponse` protobuf.
Args:
get_doc_response (~google.cloud.proto.firestore.v1beta1.\
firestore_pb2.BatchGetDocumentsResponse): A single response (from
a stream) containing the "get" response for a document.
reference_map (Dict[str, .DocumentReference]): A mapping (produced
by :func:`_reference_info`) of fully-qualified document paths to
document references.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns:
[.DocumentSnapshot]: The retrieved snapshot.
Raises:
ValueError: If the response has a ``result`` field (a oneof) other
than ``found`` or ``missing``. | [
"Parse",
"a",
"BatchGetDocumentsResponse",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L438-L484 |
28,123 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | Client._firestore_api | def _firestore_api(self):
"""Lazy-loading getter GAPIC Firestore API.
Returns:
~.gapic.firestore.v1beta1.firestore_client.FirestoreClient: The
GAPIC client with the credentials of the current client.
"""
if self._firestore_api_internal is None:
self._firestore_api_internal = firestore_client.FirestoreClient(
credentials=self._credentials
)
return self._firestore_api_internal | python | def _firestore_api(self):
"""Lazy-loading getter GAPIC Firestore API.
Returns:
~.gapic.firestore.v1beta1.firestore_client.FirestoreClient: The
GAPIC client with the credentials of the current client.
"""
if self._firestore_api_internal is None:
self._firestore_api_internal = firestore_client.FirestoreClient(
credentials=self._credentials
)
return self._firestore_api_internal | [
"def",
"_firestore_api",
"(",
"self",
")",
":",
"if",
"self",
".",
"_firestore_api_internal",
"is",
"None",
":",
"self",
".",
"_firestore_api_internal",
"=",
"firestore_client",
".",
"FirestoreClient",
"(",
"credentials",
"=",
"self",
".",
"_credentials",
")",
"return",
"self",
".",
"_firestore_api_internal"
] | Lazy-loading getter GAPIC Firestore API.
Returns:
~.gapic.firestore.v1beta1.firestore_client.FirestoreClient: The
GAPIC client with the credentials of the current client. | [
"Lazy",
"-",
"loading",
"getter",
"GAPIC",
"Firestore",
"API",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L91-L103 |
28,124 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | Client._database_string | def _database_string(self):
"""The database string corresponding to this client's project.
This value is lazy-loaded and cached.
Will be of the form
``projects/{project_id}/databases/{database_id}``
but ``database_id == '(default)'`` for the time being.
Returns:
str: The fully-qualified database string for the current
project. (The default database is also in this string.)
"""
if self._database_string_internal is None:
# NOTE: database_root_path() is a classmethod, so we don't use
# self._firestore_api (it isn't necessary).
db_str = firestore_client.FirestoreClient.database_root_path(
self.project, self._database
)
self._database_string_internal = db_str
return self._database_string_internal | python | def _database_string(self):
"""The database string corresponding to this client's project.
This value is lazy-loaded and cached.
Will be of the form
``projects/{project_id}/databases/{database_id}``
but ``database_id == '(default)'`` for the time being.
Returns:
str: The fully-qualified database string for the current
project. (The default database is also in this string.)
"""
if self._database_string_internal is None:
# NOTE: database_root_path() is a classmethod, so we don't use
# self._firestore_api (it isn't necessary).
db_str = firestore_client.FirestoreClient.database_root_path(
self.project, self._database
)
self._database_string_internal = db_str
return self._database_string_internal | [
"def",
"_database_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"_database_string_internal",
"is",
"None",
":",
"# NOTE: database_root_path() is a classmethod, so we don't use",
"# self._firestore_api (it isn't necessary).",
"db_str",
"=",
"firestore_client",
".",
"FirestoreClient",
".",
"database_root_path",
"(",
"self",
".",
"project",
",",
"self",
".",
"_database",
")",
"self",
".",
"_database_string_internal",
"=",
"db_str",
"return",
"self",
".",
"_database_string_internal"
] | The database string corresponding to this client's project.
This value is lazy-loaded and cached.
Will be of the form
``projects/{project_id}/databases/{database_id}``
but ``database_id == '(default)'`` for the time being.
Returns:
str: The fully-qualified database string for the current
project. (The default database is also in this string.) | [
"The",
"database",
"string",
"corresponding",
"to",
"this",
"client",
"s",
"project",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L106-L129 |
28,125 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | Client._rpc_metadata | def _rpc_metadata(self):
"""The RPC metadata for this client's associated database.
Returns:
Sequence[Tuple(str, str)]: RPC metadata with resource prefix
for the database associated with this client.
"""
if self._rpc_metadata_internal is None:
self._rpc_metadata_internal = _helpers.metadata_with_prefix(
self._database_string
)
return self._rpc_metadata_internal | python | def _rpc_metadata(self):
"""The RPC metadata for this client's associated database.
Returns:
Sequence[Tuple(str, str)]: RPC metadata with resource prefix
for the database associated with this client.
"""
if self._rpc_metadata_internal is None:
self._rpc_metadata_internal = _helpers.metadata_with_prefix(
self._database_string
)
return self._rpc_metadata_internal | [
"def",
"_rpc_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_rpc_metadata_internal",
"is",
"None",
":",
"self",
".",
"_rpc_metadata_internal",
"=",
"_helpers",
".",
"metadata_with_prefix",
"(",
"self",
".",
"_database_string",
")",
"return",
"self",
".",
"_rpc_metadata_internal"
] | The RPC metadata for this client's associated database.
Returns:
Sequence[Tuple(str, str)]: RPC metadata with resource prefix
for the database associated with this client. | [
"The",
"RPC",
"metadata",
"for",
"this",
"client",
"s",
"associated",
"database",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L132-L144 |
28,126 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | Client.collection | def collection(self, *collection_path):
"""Get a reference to a collection.
For a top-level collection:
.. code-block:: python
>>> client.collection('top')
For a sub-collection:
.. code-block:: python
>>> client.collection('mydocs/doc/subcol')
>>> # is the same as
>>> client.collection('mydocs', 'doc', 'subcol')
Sub-collections can be nested deeper in a similar fashion.
Args:
collection_path (Tuple[str, ...]): Can either be
* A single ``/``-delimited path to a collection
* A tuple of collection path segments
Returns:
~.firestore_v1beta1.collection.CollectionReference: A reference
to a collection in the Firestore database.
"""
if len(collection_path) == 1:
path = collection_path[0].split(_helpers.DOCUMENT_PATH_DELIMITER)
else:
path = collection_path
return CollectionReference(*path, client=self) | python | def collection(self, *collection_path):
"""Get a reference to a collection.
For a top-level collection:
.. code-block:: python
>>> client.collection('top')
For a sub-collection:
.. code-block:: python
>>> client.collection('mydocs/doc/subcol')
>>> # is the same as
>>> client.collection('mydocs', 'doc', 'subcol')
Sub-collections can be nested deeper in a similar fashion.
Args:
collection_path (Tuple[str, ...]): Can either be
* A single ``/``-delimited path to a collection
* A tuple of collection path segments
Returns:
~.firestore_v1beta1.collection.CollectionReference: A reference
to a collection in the Firestore database.
"""
if len(collection_path) == 1:
path = collection_path[0].split(_helpers.DOCUMENT_PATH_DELIMITER)
else:
path = collection_path
return CollectionReference(*path, client=self) | [
"def",
"collection",
"(",
"self",
",",
"*",
"collection_path",
")",
":",
"if",
"len",
"(",
"collection_path",
")",
"==",
"1",
":",
"path",
"=",
"collection_path",
"[",
"0",
"]",
".",
"split",
"(",
"_helpers",
".",
"DOCUMENT_PATH_DELIMITER",
")",
"else",
":",
"path",
"=",
"collection_path",
"return",
"CollectionReference",
"(",
"*",
"path",
",",
"client",
"=",
"self",
")"
] | Get a reference to a collection.
For a top-level collection:
.. code-block:: python
>>> client.collection('top')
For a sub-collection:
.. code-block:: python
>>> client.collection('mydocs/doc/subcol')
>>> # is the same as
>>> client.collection('mydocs', 'doc', 'subcol')
Sub-collections can be nested deeper in a similar fashion.
Args:
collection_path (Tuple[str, ...]): Can either be
* A single ``/``-delimited path to a collection
* A tuple of collection path segments
Returns:
~.firestore_v1beta1.collection.CollectionReference: A reference
to a collection in the Firestore database. | [
"Get",
"a",
"reference",
"to",
"a",
"collection",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L146-L180 |
28,127 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | Client.document | def document(self, *document_path):
"""Get a reference to a document in a collection.
For a top-level document:
.. code-block:: python
>>> client.document('collek/shun')
>>> # is the same as
>>> client.document('collek', 'shun')
For a document in a sub-collection:
.. code-block:: python
>>> client.document('mydocs/doc/subcol/child')
>>> # is the same as
>>> client.document('mydocs', 'doc', 'subcol', 'child')
Documents in sub-collections can be nested deeper in a similar fashion.
Args:
document_path (Tuple[str, ...]): Can either be
* A single ``/``-delimited path to a document
* A tuple of document path segments
Returns:
~.firestore_v1beta1.document.DocumentReference: A reference
to a document in a collection.
"""
if len(document_path) == 1:
path = document_path[0].split(_helpers.DOCUMENT_PATH_DELIMITER)
else:
path = document_path
return DocumentReference(*path, client=self) | python | def document(self, *document_path):
"""Get a reference to a document in a collection.
For a top-level document:
.. code-block:: python
>>> client.document('collek/shun')
>>> # is the same as
>>> client.document('collek', 'shun')
For a document in a sub-collection:
.. code-block:: python
>>> client.document('mydocs/doc/subcol/child')
>>> # is the same as
>>> client.document('mydocs', 'doc', 'subcol', 'child')
Documents in sub-collections can be nested deeper in a similar fashion.
Args:
document_path (Tuple[str, ...]): Can either be
* A single ``/``-delimited path to a document
* A tuple of document path segments
Returns:
~.firestore_v1beta1.document.DocumentReference: A reference
to a document in a collection.
"""
if len(document_path) == 1:
path = document_path[0].split(_helpers.DOCUMENT_PATH_DELIMITER)
else:
path = document_path
return DocumentReference(*path, client=self) | [
"def",
"document",
"(",
"self",
",",
"*",
"document_path",
")",
":",
"if",
"len",
"(",
"document_path",
")",
"==",
"1",
":",
"path",
"=",
"document_path",
"[",
"0",
"]",
".",
"split",
"(",
"_helpers",
".",
"DOCUMENT_PATH_DELIMITER",
")",
"else",
":",
"path",
"=",
"document_path",
"return",
"DocumentReference",
"(",
"*",
"path",
",",
"client",
"=",
"self",
")"
] | Get a reference to a document in a collection.
For a top-level document:
.. code-block:: python
>>> client.document('collek/shun')
>>> # is the same as
>>> client.document('collek', 'shun')
For a document in a sub-collection:
.. code-block:: python
>>> client.document('mydocs/doc/subcol/child')
>>> # is the same as
>>> client.document('mydocs', 'doc', 'subcol', 'child')
Documents in sub-collections can be nested deeper in a similar fashion.
Args:
document_path (Tuple[str, ...]): Can either be
* A single ``/``-delimited path to a document
* A tuple of document path segments
Returns:
~.firestore_v1beta1.document.DocumentReference: A reference
to a document in a collection. | [
"Get",
"a",
"reference",
"to",
"a",
"document",
"in",
"a",
"collection",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L182-L218 |
28,128 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | Client.write_option | def write_option(**kwargs):
"""Create a write option for write operations.
Write operations include :meth:`~.DocumentReference.set`,
:meth:`~.DocumentReference.update` and
:meth:`~.DocumentReference.delete`.
One of the following keyword arguments must be provided:
* ``last_update_time`` (:class:`google.protobuf.timestamp_pb2.\
Timestamp`): A timestamp. When set, the target document must
exist and have been last updated at that time. Protobuf
``update_time`` timestamps are typically returned from methods
that perform write operations as part of a "write result"
protobuf or directly.
* ``exists`` (:class:`bool`): Indicates if the document being modified
should already exist.
Providing no argument would make the option have no effect (so
it is not allowed). Providing multiple would be an apparent
contradiction, since ``last_update_time`` assumes that the
document **was** updated (it can't have been updated if it
doesn't exist) and ``exists`` indicate that it is unknown if the
document exists or not.
Args:
kwargs (Dict[str, Any]): The keyword arguments described above.
Raises:
TypeError: If anything other than exactly one argument is
provided by the caller.
"""
if len(kwargs) != 1:
raise TypeError(_BAD_OPTION_ERR)
name, value = kwargs.popitem()
if name == "last_update_time":
return _helpers.LastUpdateOption(value)
elif name == "exists":
return _helpers.ExistsOption(value)
else:
extra = "{!r} was provided".format(name)
raise TypeError(_BAD_OPTION_ERR, extra) | python | def write_option(**kwargs):
"""Create a write option for write operations.
Write operations include :meth:`~.DocumentReference.set`,
:meth:`~.DocumentReference.update` and
:meth:`~.DocumentReference.delete`.
One of the following keyword arguments must be provided:
* ``last_update_time`` (:class:`google.protobuf.timestamp_pb2.\
Timestamp`): A timestamp. When set, the target document must
exist and have been last updated at that time. Protobuf
``update_time`` timestamps are typically returned from methods
that perform write operations as part of a "write result"
protobuf or directly.
* ``exists`` (:class:`bool`): Indicates if the document being modified
should already exist.
Providing no argument would make the option have no effect (so
it is not allowed). Providing multiple would be an apparent
contradiction, since ``last_update_time`` assumes that the
document **was** updated (it can't have been updated if it
doesn't exist) and ``exists`` indicate that it is unknown if the
document exists or not.
Args:
kwargs (Dict[str, Any]): The keyword arguments described above.
Raises:
TypeError: If anything other than exactly one argument is
provided by the caller.
"""
if len(kwargs) != 1:
raise TypeError(_BAD_OPTION_ERR)
name, value = kwargs.popitem()
if name == "last_update_time":
return _helpers.LastUpdateOption(value)
elif name == "exists":
return _helpers.ExistsOption(value)
else:
extra = "{!r} was provided".format(name)
raise TypeError(_BAD_OPTION_ERR, extra) | [
"def",
"write_option",
"(",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
"!=",
"1",
":",
"raise",
"TypeError",
"(",
"_BAD_OPTION_ERR",
")",
"name",
",",
"value",
"=",
"kwargs",
".",
"popitem",
"(",
")",
"if",
"name",
"==",
"\"last_update_time\"",
":",
"return",
"_helpers",
".",
"LastUpdateOption",
"(",
"value",
")",
"elif",
"name",
"==",
"\"exists\"",
":",
"return",
"_helpers",
".",
"ExistsOption",
"(",
"value",
")",
"else",
":",
"extra",
"=",
"\"{!r} was provided\"",
".",
"format",
"(",
"name",
")",
"raise",
"TypeError",
"(",
"_BAD_OPTION_ERR",
",",
"extra",
")"
] | Create a write option for write operations.
Write operations include :meth:`~.DocumentReference.set`,
:meth:`~.DocumentReference.update` and
:meth:`~.DocumentReference.delete`.
One of the following keyword arguments must be provided:
* ``last_update_time`` (:class:`google.protobuf.timestamp_pb2.\
Timestamp`): A timestamp. When set, the target document must
exist and have been last updated at that time. Protobuf
``update_time`` timestamps are typically returned from methods
that perform write operations as part of a "write result"
protobuf or directly.
* ``exists`` (:class:`bool`): Indicates if the document being modified
should already exist.
Providing no argument would make the option have no effect (so
it is not allowed). Providing multiple would be an apparent
contradiction, since ``last_update_time`` assumes that the
document **was** updated (it can't have been updated if it
doesn't exist) and ``exists`` indicate that it is unknown if the
document exists or not.
Args:
kwargs (Dict[str, Any]): The keyword arguments described above.
Raises:
TypeError: If anything other than exactly one argument is
provided by the caller. | [
"Create",
"a",
"write",
"option",
"for",
"write",
"operations",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L250-L292 |
28,129 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | Client.get_all | def get_all(self, references, field_paths=None, transaction=None):
"""Retrieve a batch of documents.
.. note::
Documents returned by this method are not guaranteed to be
returned in the same order that they are given in ``references``.
.. note::
If multiple ``references`` refer to the same document, the server
will only return one result.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
If a ``transaction`` is used and it already has write operations
added, this method cannot be used (i.e. read-after-write is not
allowed).
Args:
references (List[.DocumentReference, ...]): Iterable of document
references to be retrieved.
field_paths (Optional[Iterable[str, ...]]): An iterable of field
paths (``.``-delimited list of field names) to use as a
projection of document fields in the returned results. If
no value is provided, all fields will be returned.
transaction (Optional[~.firestore_v1beta1.transaction.\
Transaction]): An existing transaction that these
``references`` will be retrieved in.
Yields:
.DocumentSnapshot: The next document snapshot that fulfills the
query, or :data:`None` if the document does not exist.
"""
document_paths, reference_map = _reference_info(references)
mask = _get_doc_mask(field_paths)
response_iterator = self._firestore_api.batch_get_documents(
self._database_string,
document_paths,
mask,
transaction=_helpers.get_transaction_id(transaction),
metadata=self._rpc_metadata,
)
for get_doc_response in response_iterator:
yield _parse_batch_get(get_doc_response, reference_map, self) | python | def get_all(self, references, field_paths=None, transaction=None):
"""Retrieve a batch of documents.
.. note::
Documents returned by this method are not guaranteed to be
returned in the same order that they are given in ``references``.
.. note::
If multiple ``references`` refer to the same document, the server
will only return one result.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
If a ``transaction`` is used and it already has write operations
added, this method cannot be used (i.e. read-after-write is not
allowed).
Args:
references (List[.DocumentReference, ...]): Iterable of document
references to be retrieved.
field_paths (Optional[Iterable[str, ...]]): An iterable of field
paths (``.``-delimited list of field names) to use as a
projection of document fields in the returned results. If
no value is provided, all fields will be returned.
transaction (Optional[~.firestore_v1beta1.transaction.\
Transaction]): An existing transaction that these
``references`` will be retrieved in.
Yields:
.DocumentSnapshot: The next document snapshot that fulfills the
query, or :data:`None` if the document does not exist.
"""
document_paths, reference_map = _reference_info(references)
mask = _get_doc_mask(field_paths)
response_iterator = self._firestore_api.batch_get_documents(
self._database_string,
document_paths,
mask,
transaction=_helpers.get_transaction_id(transaction),
metadata=self._rpc_metadata,
)
for get_doc_response in response_iterator:
yield _parse_batch_get(get_doc_response, reference_map, self) | [
"def",
"get_all",
"(",
"self",
",",
"references",
",",
"field_paths",
"=",
"None",
",",
"transaction",
"=",
"None",
")",
":",
"document_paths",
",",
"reference_map",
"=",
"_reference_info",
"(",
"references",
")",
"mask",
"=",
"_get_doc_mask",
"(",
"field_paths",
")",
"response_iterator",
"=",
"self",
".",
"_firestore_api",
".",
"batch_get_documents",
"(",
"self",
".",
"_database_string",
",",
"document_paths",
",",
"mask",
",",
"transaction",
"=",
"_helpers",
".",
"get_transaction_id",
"(",
"transaction",
")",
",",
"metadata",
"=",
"self",
".",
"_rpc_metadata",
",",
")",
"for",
"get_doc_response",
"in",
"response_iterator",
":",
"yield",
"_parse_batch_get",
"(",
"get_doc_response",
",",
"reference_map",
",",
"self",
")"
] | Retrieve a batch of documents.
.. note::
Documents returned by this method are not guaranteed to be
returned in the same order that they are given in ``references``.
.. note::
If multiple ``references`` refer to the same document, the server
will only return one result.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
If a ``transaction`` is used and it already has write operations
added, this method cannot be used (i.e. read-after-write is not
allowed).
Args:
references (List[.DocumentReference, ...]): Iterable of document
references to be retrieved.
field_paths (Optional[Iterable[str, ...]]): An iterable of field
paths (``.``-delimited list of field names) to use as a
projection of document fields in the returned results. If
no value is provided, all fields will be returned.
transaction (Optional[~.firestore_v1beta1.transaction.\
Transaction]): An existing transaction that these
``references`` will be retrieved in.
Yields:
.DocumentSnapshot: The next document snapshot that fulfills the
query, or :data:`None` if the document does not exist. | [
"Retrieve",
"a",
"batch",
"of",
"documents",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L294-L340 |
28,130 | googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | Client.collections | def collections(self):
"""List top-level collections of the client's database.
Returns:
Sequence[~.firestore_v1beta1.collection.CollectionReference]:
iterator of subcollections of the current document.
"""
iterator = self._firestore_api.list_collection_ids(
self._database_string, metadata=self._rpc_metadata
)
iterator.client = self
iterator.item_to_value = _item_to_collection_ref
return iterator | python | def collections(self):
"""List top-level collections of the client's database.
Returns:
Sequence[~.firestore_v1beta1.collection.CollectionReference]:
iterator of subcollections of the current document.
"""
iterator = self._firestore_api.list_collection_ids(
self._database_string, metadata=self._rpc_metadata
)
iterator.client = self
iterator.item_to_value = _item_to_collection_ref
return iterator | [
"def",
"collections",
"(",
"self",
")",
":",
"iterator",
"=",
"self",
".",
"_firestore_api",
".",
"list_collection_ids",
"(",
"self",
".",
"_database_string",
",",
"metadata",
"=",
"self",
".",
"_rpc_metadata",
")",
"iterator",
".",
"client",
"=",
"self",
"iterator",
".",
"item_to_value",
"=",
"_item_to_collection_ref",
"return",
"iterator"
] | List top-level collections of the client's database.
Returns:
Sequence[~.firestore_v1beta1.collection.CollectionReference]:
iterator of subcollections of the current document. | [
"List",
"top",
"-",
"level",
"collections",
"of",
"the",
"client",
"s",
"database",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L342-L354 |
28,131 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/transaction.py | Transaction.begin | def begin(self):
"""Begin a transaction on the database.
:rtype: bytes
:returns: the ID for the newly-begun transaction.
:raises ValueError:
if the transaction is already begun, committed, or rolled back.
"""
if self._transaction_id is not None:
raise ValueError("Transaction already begun")
if self.committed is not None:
raise ValueError("Transaction already committed")
if self._rolled_back:
raise ValueError("Transaction is already rolled back")
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
txn_options = TransactionOptions(read_write=TransactionOptions.ReadWrite())
response = api.begin_transaction(
self._session.name, txn_options, metadata=metadata
)
self._transaction_id = response.id
return self._transaction_id | python | def begin(self):
"""Begin a transaction on the database.
:rtype: bytes
:returns: the ID for the newly-begun transaction.
:raises ValueError:
if the transaction is already begun, committed, or rolled back.
"""
if self._transaction_id is not None:
raise ValueError("Transaction already begun")
if self.committed is not None:
raise ValueError("Transaction already committed")
if self._rolled_back:
raise ValueError("Transaction is already rolled back")
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
txn_options = TransactionOptions(read_write=TransactionOptions.ReadWrite())
response = api.begin_transaction(
self._session.name, txn_options, metadata=metadata
)
self._transaction_id = response.id
return self._transaction_id | [
"def",
"begin",
"(",
"self",
")",
":",
"if",
"self",
".",
"_transaction_id",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Transaction already begun\"",
")",
"if",
"self",
".",
"committed",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Transaction already committed\"",
")",
"if",
"self",
".",
"_rolled_back",
":",
"raise",
"ValueError",
"(",
"\"Transaction is already rolled back\"",
")",
"database",
"=",
"self",
".",
"_session",
".",
"_database",
"api",
"=",
"database",
".",
"spanner_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"database",
".",
"name",
")",
"txn_options",
"=",
"TransactionOptions",
"(",
"read_write",
"=",
"TransactionOptions",
".",
"ReadWrite",
"(",
")",
")",
"response",
"=",
"api",
".",
"begin_transaction",
"(",
"self",
".",
"_session",
".",
"name",
",",
"txn_options",
",",
"metadata",
"=",
"metadata",
")",
"self",
".",
"_transaction_id",
"=",
"response",
".",
"id",
"return",
"self",
".",
"_transaction_id"
] | Begin a transaction on the database.
:rtype: bytes
:returns: the ID for the newly-begun transaction.
:raises ValueError:
if the transaction is already begun, committed, or rolled back. | [
"Begin",
"a",
"transaction",
"on",
"the",
"database",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/transaction.py#L74-L99 |
28,132 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/transaction.py | Transaction.rollback | def rollback(self):
"""Roll back a transaction on the database."""
self._check_state()
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
api.rollback(self._session.name, self._transaction_id, metadata=metadata)
self._rolled_back = True
del self._session._transaction | python | def rollback(self):
"""Roll back a transaction on the database."""
self._check_state()
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
api.rollback(self._session.name, self._transaction_id, metadata=metadata)
self._rolled_back = True
del self._session._transaction | [
"def",
"rollback",
"(",
"self",
")",
":",
"self",
".",
"_check_state",
"(",
")",
"database",
"=",
"self",
".",
"_session",
".",
"_database",
"api",
"=",
"database",
".",
"spanner_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"database",
".",
"name",
")",
"api",
".",
"rollback",
"(",
"self",
".",
"_session",
".",
"name",
",",
"self",
".",
"_transaction_id",
",",
"metadata",
"=",
"metadata",
")",
"self",
".",
"_rolled_back",
"=",
"True",
"del",
"self",
".",
"_session",
".",
"_transaction"
] | Roll back a transaction on the database. | [
"Roll",
"back",
"a",
"transaction",
"on",
"the",
"database",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/transaction.py#L101-L109 |
28,133 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/transaction.py | Transaction.execute_update | def execute_update(self, dml, params=None, param_types=None, query_mode=None):
"""Perform an ``ExecuteSql`` API request with DML.
:type dml: str
:param dml: SQL 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.
:type query_mode:
:class:`google.cloud.spanner_v1.proto.ExecuteSqlRequest.QueryMode`
:param query_mode: Mode governing return of results / query plan. See
https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode1
:rtype: int
:returns: Count of rows affected by the DML statement.
"""
params_pb = self._make_params_pb(params, param_types)
database = self._session._database
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
api = database.spanner_api
response = api.execute_sql(
self._session.name,
dml,
transaction=transaction,
params=params_pb,
param_types=param_types,
query_mode=query_mode,
seqno=self._execute_sql_count,
metadata=metadata,
)
self._execute_sql_count += 1
return response.stats.row_count_exact | python | def execute_update(self, dml, params=None, param_types=None, query_mode=None):
"""Perform an ``ExecuteSql`` API request with DML.
:type dml: str
:param dml: SQL 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.
:type query_mode:
:class:`google.cloud.spanner_v1.proto.ExecuteSqlRequest.QueryMode`
:param query_mode: Mode governing return of results / query plan. See
https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode1
:rtype: int
:returns: Count of rows affected by the DML statement.
"""
params_pb = self._make_params_pb(params, param_types)
database = self._session._database
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
api = database.spanner_api
response = api.execute_sql(
self._session.name,
dml,
transaction=transaction,
params=params_pb,
param_types=param_types,
query_mode=query_mode,
seqno=self._execute_sql_count,
metadata=metadata,
)
self._execute_sql_count += 1
return response.stats.row_count_exact | [
"def",
"execute_update",
"(",
"self",
",",
"dml",
",",
"params",
"=",
"None",
",",
"param_types",
"=",
"None",
",",
"query_mode",
"=",
"None",
")",
":",
"params_pb",
"=",
"self",
".",
"_make_params_pb",
"(",
"params",
",",
"param_types",
")",
"database",
"=",
"self",
".",
"_session",
".",
"_database",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"database",
".",
"name",
")",
"transaction",
"=",
"self",
".",
"_make_txn_selector",
"(",
")",
"api",
"=",
"database",
".",
"spanner_api",
"response",
"=",
"api",
".",
"execute_sql",
"(",
"self",
".",
"_session",
".",
"name",
",",
"dml",
",",
"transaction",
"=",
"transaction",
",",
"params",
"=",
"params_pb",
",",
"param_types",
"=",
"param_types",
",",
"query_mode",
"=",
"query_mode",
",",
"seqno",
"=",
"self",
".",
"_execute_sql_count",
",",
"metadata",
"=",
"metadata",
",",
")",
"self",
".",
"_execute_sql_count",
"+=",
"1",
"return",
"response",
".",
"stats",
".",
"row_count_exact"
] | Perform an ``ExecuteSql`` API request with DML.
:type dml: str
:param dml: SQL 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.
:type query_mode:
:class:`google.cloud.spanner_v1.proto.ExecuteSqlRequest.QueryMode`
:param query_mode: Mode governing return of results / query plan. See
https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode1
:rtype: int
:returns: Count of rows affected by the DML statement. | [
"Perform",
"an",
"ExecuteSql",
"API",
"request",
"with",
"DML",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/transaction.py#L165-L206 |
28,134 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/transaction.py | Transaction.batch_update | def batch_update(self, statements):
"""Perform a batch of DML statements via an ``ExecuteBatchDml`` request.
:type statements:
Sequence[Union[ str, Tuple[str, Dict[str, Any], Dict[str, Union[dict, .types.Type]]]]]
:param statements:
List of DML statements, with optional params / param types.
If passed, 'params' is a dict mapping names to the values
for parameter replacement. Keys must match the names used in the
corresponding DML statement. If 'params' is passed, 'param_types'
must also be passed, as a dict mapping names to the type of
value passed in 'params'.
:rtype:
Tuple(status, Sequence[int])
:returns:
Status code, plus counts of rows affected by each completed DML
statement. Note that if the staus code is not ``OK``, the
statement triggering the error will not have an entry in the
list, nor will any statements following that one.
"""
parsed = []
for statement in statements:
if isinstance(statement, str):
parsed.append({"sql": statement})
else:
dml, params, param_types = statement
params_pb = self._make_params_pb(params, param_types)
parsed.append(
{"sql": dml, "params": params_pb, "param_types": param_types}
)
database = self._session._database
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
api = database.spanner_api
response = api.execute_batch_dml(
session=self._session.name,
transaction=transaction,
statements=parsed,
seqno=self._execute_sql_count,
metadata=metadata,
)
self._execute_sql_count += 1
row_counts = [
result_set.stats.row_count_exact for result_set in response.result_sets
]
return response.status, row_counts | python | def batch_update(self, statements):
"""Perform a batch of DML statements via an ``ExecuteBatchDml`` request.
:type statements:
Sequence[Union[ str, Tuple[str, Dict[str, Any], Dict[str, Union[dict, .types.Type]]]]]
:param statements:
List of DML statements, with optional params / param types.
If passed, 'params' is a dict mapping names to the values
for parameter replacement. Keys must match the names used in the
corresponding DML statement. If 'params' is passed, 'param_types'
must also be passed, as a dict mapping names to the type of
value passed in 'params'.
:rtype:
Tuple(status, Sequence[int])
:returns:
Status code, plus counts of rows affected by each completed DML
statement. Note that if the staus code is not ``OK``, the
statement triggering the error will not have an entry in the
list, nor will any statements following that one.
"""
parsed = []
for statement in statements:
if isinstance(statement, str):
parsed.append({"sql": statement})
else:
dml, params, param_types = statement
params_pb = self._make_params_pb(params, param_types)
parsed.append(
{"sql": dml, "params": params_pb, "param_types": param_types}
)
database = self._session._database
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
api = database.spanner_api
response = api.execute_batch_dml(
session=self._session.name,
transaction=transaction,
statements=parsed,
seqno=self._execute_sql_count,
metadata=metadata,
)
self._execute_sql_count += 1
row_counts = [
result_set.stats.row_count_exact for result_set in response.result_sets
]
return response.status, row_counts | [
"def",
"batch_update",
"(",
"self",
",",
"statements",
")",
":",
"parsed",
"=",
"[",
"]",
"for",
"statement",
"in",
"statements",
":",
"if",
"isinstance",
"(",
"statement",
",",
"str",
")",
":",
"parsed",
".",
"append",
"(",
"{",
"\"sql\"",
":",
"statement",
"}",
")",
"else",
":",
"dml",
",",
"params",
",",
"param_types",
"=",
"statement",
"params_pb",
"=",
"self",
".",
"_make_params_pb",
"(",
"params",
",",
"param_types",
")",
"parsed",
".",
"append",
"(",
"{",
"\"sql\"",
":",
"dml",
",",
"\"params\"",
":",
"params_pb",
",",
"\"param_types\"",
":",
"param_types",
"}",
")",
"database",
"=",
"self",
".",
"_session",
".",
"_database",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"database",
".",
"name",
")",
"transaction",
"=",
"self",
".",
"_make_txn_selector",
"(",
")",
"api",
"=",
"database",
".",
"spanner_api",
"response",
"=",
"api",
".",
"execute_batch_dml",
"(",
"session",
"=",
"self",
".",
"_session",
".",
"name",
",",
"transaction",
"=",
"transaction",
",",
"statements",
"=",
"parsed",
",",
"seqno",
"=",
"self",
".",
"_execute_sql_count",
",",
"metadata",
"=",
"metadata",
",",
")",
"self",
".",
"_execute_sql_count",
"+=",
"1",
"row_counts",
"=",
"[",
"result_set",
".",
"stats",
".",
"row_count_exact",
"for",
"result_set",
"in",
"response",
".",
"result_sets",
"]",
"return",
"response",
".",
"status",
",",
"row_counts"
] | Perform a batch of DML statements via an ``ExecuteBatchDml`` request.
:type statements:
Sequence[Union[ str, Tuple[str, Dict[str, Any], Dict[str, Union[dict, .types.Type]]]]]
:param statements:
List of DML statements, with optional params / param types.
If passed, 'params' is a dict mapping names to the values
for parameter replacement. Keys must match the names used in the
corresponding DML statement. If 'params' is passed, 'param_types'
must also be passed, as a dict mapping names to the type of
value passed in 'params'.
:rtype:
Tuple(status, Sequence[int])
:returns:
Status code, plus counts of rows affected by each completed DML
statement. Note that if the staus code is not ``OK``, the
statement triggering the error will not have an entry in the
list, nor will any statements following that one. | [
"Perform",
"a",
"batch",
"of",
"DML",
"statements",
"via",
"an",
"ExecuteBatchDml",
"request",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/transaction.py#L208-L258 |
28,135 | googleapis/google-cloud-python | dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py | DlpServiceClient.organization_deidentify_template_path | def organization_deidentify_template_path(cls, organization, deidentify_template):
"""Return a fully-qualified organization_deidentify_template string."""
return google.api_core.path_template.expand(
"organizations/{organization}/deidentifyTemplates/{deidentify_template}",
organization=organization,
deidentify_template=deidentify_template,
) | python | def organization_deidentify_template_path(cls, organization, deidentify_template):
"""Return a fully-qualified organization_deidentify_template string."""
return google.api_core.path_template.expand(
"organizations/{organization}/deidentifyTemplates/{deidentify_template}",
organization=organization,
deidentify_template=deidentify_template,
) | [
"def",
"organization_deidentify_template_path",
"(",
"cls",
",",
"organization",
",",
"deidentify_template",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"organizations/{organization}/deidentifyTemplates/{deidentify_template}\"",
",",
"organization",
"=",
"organization",
",",
"deidentify_template",
"=",
"deidentify_template",
",",
")"
] | Return a fully-qualified organization_deidentify_template string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"organization_deidentify_template",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py#L92-L98 |
28,136 | googleapis/google-cloud-python | dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py | DlpServiceClient.project_deidentify_template_path | def project_deidentify_template_path(cls, project, deidentify_template):
"""Return a fully-qualified project_deidentify_template string."""
return google.api_core.path_template.expand(
"projects/{project}/deidentifyTemplates/{deidentify_template}",
project=project,
deidentify_template=deidentify_template,
) | python | def project_deidentify_template_path(cls, project, deidentify_template):
"""Return a fully-qualified project_deidentify_template string."""
return google.api_core.path_template.expand(
"projects/{project}/deidentifyTemplates/{deidentify_template}",
project=project,
deidentify_template=deidentify_template,
) | [
"def",
"project_deidentify_template_path",
"(",
"cls",
",",
"project",
",",
"deidentify_template",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/deidentifyTemplates/{deidentify_template}\"",
",",
"project",
"=",
"project",
",",
"deidentify_template",
"=",
"deidentify_template",
",",
")"
] | Return a fully-qualified project_deidentify_template string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"project_deidentify_template",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py#L101-L107 |
28,137 | googleapis/google-cloud-python | dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py | DlpServiceClient.organization_inspect_template_path | def organization_inspect_template_path(cls, organization, inspect_template):
"""Return a fully-qualified organization_inspect_template string."""
return google.api_core.path_template.expand(
"organizations/{organization}/inspectTemplates/{inspect_template}",
organization=organization,
inspect_template=inspect_template,
) | python | def organization_inspect_template_path(cls, organization, inspect_template):
"""Return a fully-qualified organization_inspect_template string."""
return google.api_core.path_template.expand(
"organizations/{organization}/inspectTemplates/{inspect_template}",
organization=organization,
inspect_template=inspect_template,
) | [
"def",
"organization_inspect_template_path",
"(",
"cls",
",",
"organization",
",",
"inspect_template",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"organizations/{organization}/inspectTemplates/{inspect_template}\"",
",",
"organization",
"=",
"organization",
",",
"inspect_template",
"=",
"inspect_template",
",",
")"
] | Return a fully-qualified organization_inspect_template string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"organization_inspect_template",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py#L110-L116 |
28,138 | googleapis/google-cloud-python | dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py | DlpServiceClient.project_inspect_template_path | def project_inspect_template_path(cls, project, inspect_template):
"""Return a fully-qualified project_inspect_template string."""
return google.api_core.path_template.expand(
"projects/{project}/inspectTemplates/{inspect_template}",
project=project,
inspect_template=inspect_template,
) | python | def project_inspect_template_path(cls, project, inspect_template):
"""Return a fully-qualified project_inspect_template string."""
return google.api_core.path_template.expand(
"projects/{project}/inspectTemplates/{inspect_template}",
project=project,
inspect_template=inspect_template,
) | [
"def",
"project_inspect_template_path",
"(",
"cls",
",",
"project",
",",
"inspect_template",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/inspectTemplates/{inspect_template}\"",
",",
"project",
"=",
"project",
",",
"inspect_template",
"=",
"inspect_template",
",",
")"
] | Return a fully-qualified project_inspect_template string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"project_inspect_template",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py#L119-L125 |
28,139 | googleapis/google-cloud-python | dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py | DlpServiceClient.project_job_trigger_path | def project_job_trigger_path(cls, project, job_trigger):
"""Return a fully-qualified project_job_trigger string."""
return google.api_core.path_template.expand(
"projects/{project}/jobTriggers/{job_trigger}",
project=project,
job_trigger=job_trigger,
) | python | def project_job_trigger_path(cls, project, job_trigger):
"""Return a fully-qualified project_job_trigger string."""
return google.api_core.path_template.expand(
"projects/{project}/jobTriggers/{job_trigger}",
project=project,
job_trigger=job_trigger,
) | [
"def",
"project_job_trigger_path",
"(",
"cls",
",",
"project",
",",
"job_trigger",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/jobTriggers/{job_trigger}\"",
",",
"project",
"=",
"project",
",",
"job_trigger",
"=",
"job_trigger",
",",
")"
] | Return a fully-qualified project_job_trigger string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"project_job_trigger",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py#L128-L134 |
28,140 | googleapis/google-cloud-python | dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py | DlpServiceClient.dlp_job_path | def dlp_job_path(cls, project, dlp_job):
"""Return a fully-qualified dlp_job string."""
return google.api_core.path_template.expand(
"projects/{project}/dlpJobs/{dlp_job}", project=project, dlp_job=dlp_job
) | python | def dlp_job_path(cls, project, dlp_job):
"""Return a fully-qualified dlp_job string."""
return google.api_core.path_template.expand(
"projects/{project}/dlpJobs/{dlp_job}", project=project, dlp_job=dlp_job
) | [
"def",
"dlp_job_path",
"(",
"cls",
",",
"project",
",",
"dlp_job",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/dlpJobs/{dlp_job}\"",
",",
"project",
"=",
"project",
",",
"dlp_job",
"=",
"dlp_job",
")"
] | Return a fully-qualified dlp_job string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"dlp_job",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py#L144-L148 |
28,141 | googleapis/google-cloud-python | dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py | DlpServiceClient.organization_stored_info_type_path | def organization_stored_info_type_path(cls, organization, stored_info_type):
"""Return a fully-qualified organization_stored_info_type string."""
return google.api_core.path_template.expand(
"organizations/{organization}/storedInfoTypes/{stored_info_type}",
organization=organization,
stored_info_type=stored_info_type,
) | python | def organization_stored_info_type_path(cls, organization, stored_info_type):
"""Return a fully-qualified organization_stored_info_type string."""
return google.api_core.path_template.expand(
"organizations/{organization}/storedInfoTypes/{stored_info_type}",
organization=organization,
stored_info_type=stored_info_type,
) | [
"def",
"organization_stored_info_type_path",
"(",
"cls",
",",
"organization",
",",
"stored_info_type",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"organizations/{organization}/storedInfoTypes/{stored_info_type}\"",
",",
"organization",
"=",
"organization",
",",
"stored_info_type",
"=",
"stored_info_type",
",",
")"
] | Return a fully-qualified organization_stored_info_type string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"organization_stored_info_type",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py#L151-L157 |
28,142 | googleapis/google-cloud-python | dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py | DlpServiceClient.project_stored_info_type_path | def project_stored_info_type_path(cls, project, stored_info_type):
"""Return a fully-qualified project_stored_info_type string."""
return google.api_core.path_template.expand(
"projects/{project}/storedInfoTypes/{stored_info_type}",
project=project,
stored_info_type=stored_info_type,
) | python | def project_stored_info_type_path(cls, project, stored_info_type):
"""Return a fully-qualified project_stored_info_type string."""
return google.api_core.path_template.expand(
"projects/{project}/storedInfoTypes/{stored_info_type}",
project=project,
stored_info_type=stored_info_type,
) | [
"def",
"project_stored_info_type_path",
"(",
"cls",
",",
"project",
",",
"stored_info_type",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/storedInfoTypes/{stored_info_type}\"",
",",
"project",
"=",
"project",
",",
"stored_info_type",
"=",
"stored_info_type",
",",
")"
] | Return a fully-qualified project_stored_info_type string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"project_stored_info_type",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dlp/google/cloud/dlp_v2/gapic/dlp_service_client.py#L160-L166 |
28,143 | googleapis/google-cloud-python | trace/google/cloud/trace/client.py | Client.trace_api | def trace_api(self):
"""
Helper for trace-related API calls.
See
https://cloud.google.com/trace/docs/reference/v2/rpc/google.devtools.
cloudtrace.v2
"""
if self._trace_api is None:
self._trace_api = make_trace_api(self)
return self._trace_api | python | def trace_api(self):
"""
Helper for trace-related API calls.
See
https://cloud.google.com/trace/docs/reference/v2/rpc/google.devtools.
cloudtrace.v2
"""
if self._trace_api is None:
self._trace_api = make_trace_api(self)
return self._trace_api | [
"def",
"trace_api",
"(",
"self",
")",
":",
"if",
"self",
".",
"_trace_api",
"is",
"None",
":",
"self",
".",
"_trace_api",
"=",
"make_trace_api",
"(",
"self",
")",
"return",
"self",
".",
"_trace_api"
] | Helper for trace-related API calls.
See
https://cloud.google.com/trace/docs/reference/v2/rpc/google.devtools.
cloudtrace.v2 | [
"Helper",
"for",
"trace",
"-",
"related",
"API",
"calls",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/trace/google/cloud/trace/client.py#L46-L56 |
28,144 | googleapis/google-cloud-python | error_reporting/google/cloud/error_reporting/_logging.py | _ErrorReportingLoggingAPI.report_error_event | def report_error_event(self, error_report):
"""Report error payload.
:type error_report: dict
:param: error_report:
dict payload of the error report formatted according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
This object should be built using
:meth:~`google.cloud.error_reporting.client._build_error_report`
"""
logger = self.logging_client.logger("errors")
logger.log_struct(error_report) | python | def report_error_event(self, error_report):
"""Report error payload.
:type error_report: dict
:param: error_report:
dict payload of the error report formatted according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
This object should be built using
:meth:~`google.cloud.error_reporting.client._build_error_report`
"""
logger = self.logging_client.logger("errors")
logger.log_struct(error_report) | [
"def",
"report_error_event",
"(",
"self",
",",
"error_report",
")",
":",
"logger",
"=",
"self",
".",
"logging_client",
".",
"logger",
"(",
"\"errors\"",
")",
"logger",
".",
"log_struct",
"(",
"error_report",
")"
] | Report error payload.
:type error_report: dict
:param: error_report:
dict payload of the error report formatted according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
This object should be built using
:meth:~`google.cloud.error_reporting.client._build_error_report` | [
"Report",
"error",
"payload",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/error_reporting/_logging.py#L55-L66 |
28,145 | googleapis/google-cloud-python | api_core/google/api_core/gapic_v1/routing_header.py | to_routing_header | def to_routing_header(params):
"""Returns a routing header string for the given request parameters.
Args:
params (Mapping[str, Any]): A dictionary containing the request
parameters used for routing.
Returns:
str: The routing header string.
"""
if sys.version_info[0] < 3:
# Python 2 does not have the "safe" parameter for urlencode.
return urlencode(params).replace("%2F", "/")
return urlencode(
params,
# Per Google API policy (go/api-url-encoding), / is not encoded.
safe="/",
) | python | def to_routing_header(params):
"""Returns a routing header string for the given request parameters.
Args:
params (Mapping[str, Any]): A dictionary containing the request
parameters used for routing.
Returns:
str: The routing header string.
"""
if sys.version_info[0] < 3:
# Python 2 does not have the "safe" parameter for urlencode.
return urlencode(params).replace("%2F", "/")
return urlencode(
params,
# Per Google API policy (go/api-url-encoding), / is not encoded.
safe="/",
) | [
"def",
"to_routing_header",
"(",
"params",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"# Python 2 does not have the \"safe\" parameter for urlencode.",
"return",
"urlencode",
"(",
"params",
")",
".",
"replace",
"(",
"\"%2F\"",
",",
"\"/\"",
")",
"return",
"urlencode",
"(",
"params",
",",
"# Per Google API policy (go/api-url-encoding), / is not encoded.",
"safe",
"=",
"\"/\"",
",",
")"
] | Returns a routing header string for the given request parameters.
Args:
params (Mapping[str, Any]): A dictionary containing the request
parameters used for routing.
Returns:
str: The routing header string. | [
"Returns",
"a",
"routing",
"header",
"string",
"for",
"the",
"given",
"request",
"parameters",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/gapic_v1/routing_header.py#L30-L47 |
28,146 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/param_types.py | StructField | def StructField(name, field_type): # pylint: disable=invalid-name
"""Construct a field description protobuf.
:type name: str
:param name: the name of the field
:type field_type: :class:`type_pb2.Type`
:param field_type: the type of the field
:rtype: :class:`type_pb2.StructType.Field`
:returns: the appropriate struct-field-type protobuf
"""
return type_pb2.StructType.Field(name=name, type=field_type) | python | def StructField(name, field_type): # pylint: disable=invalid-name
"""Construct a field description protobuf.
:type name: str
:param name: the name of the field
:type field_type: :class:`type_pb2.Type`
:param field_type: the type of the field
:rtype: :class:`type_pb2.StructType.Field`
:returns: the appropriate struct-field-type protobuf
"""
return type_pb2.StructType.Field(name=name, type=field_type) | [
"def",
"StructField",
"(",
"name",
",",
"field_type",
")",
":",
"# pylint: disable=invalid-name",
"return",
"type_pb2",
".",
"StructType",
".",
"Field",
"(",
"name",
"=",
"name",
",",
"type",
"=",
"field_type",
")"
] | Construct a field description protobuf.
:type name: str
:param name: the name of the field
:type field_type: :class:`type_pb2.Type`
:param field_type: the type of the field
:rtype: :class:`type_pb2.StructType.Field`
:returns: the appropriate struct-field-type protobuf | [
"Construct",
"a",
"field",
"description",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/param_types.py#L42-L54 |
28,147 | googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/param_types.py | Struct | def Struct(fields): # pylint: disable=invalid-name
"""Construct a struct parameter type description protobuf.
:type fields: list of :class:`type_pb2.StructType.Field`
:param fields: the fields of the struct
:rtype: :class:`type_pb2.Type`
:returns: the appropriate struct-type protobuf
"""
return type_pb2.Type(
code=type_pb2.STRUCT, struct_type=type_pb2.StructType(fields=fields)
) | python | def Struct(fields): # pylint: disable=invalid-name
"""Construct a struct parameter type description protobuf.
:type fields: list of :class:`type_pb2.StructType.Field`
:param fields: the fields of the struct
:rtype: :class:`type_pb2.Type`
:returns: the appropriate struct-type protobuf
"""
return type_pb2.Type(
code=type_pb2.STRUCT, struct_type=type_pb2.StructType(fields=fields)
) | [
"def",
"Struct",
"(",
"fields",
")",
":",
"# pylint: disable=invalid-name",
"return",
"type_pb2",
".",
"Type",
"(",
"code",
"=",
"type_pb2",
".",
"STRUCT",
",",
"struct_type",
"=",
"type_pb2",
".",
"StructType",
"(",
"fields",
"=",
"fields",
")",
")"
] | Construct a struct parameter type description protobuf.
:type fields: list of :class:`type_pb2.StructType.Field`
:param fields: the fields of the struct
:rtype: :class:`type_pb2.Type`
:returns: the appropriate struct-type protobuf | [
"Construct",
"a",
"struct",
"parameter",
"type",
"description",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/param_types.py#L57-L68 |
28,148 | googleapis/google-cloud-python | speech/google/cloud/speech_v1/helpers.py | SpeechHelpers.streaming_recognize | def streaming_recognize(
self,
config,
requests,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
):
"""Perform bi-directional speech recognition.
This method allows you to receive results while sending audio;
it is only available via. gRPC (not REST).
.. warning::
This method is EXPERIMENTAL. Its interface might change in the
future.
Example:
>>> from google.cloud.speech_v1 import enums
>>> from google.cloud.speech_v1 import SpeechClient
>>> from google.cloud.speech_v1 import types
>>> client = SpeechClient()
>>> config = types.StreamingRecognitionConfig(
... config=types.RecognitionConfig(
... encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
... ),
... )
>>> request = types.StreamingRecognizeRequest(audio_content=b'...')
>>> requests = [request]
>>> for element in client.streaming_recognize(config, requests):
... # process element
... pass
Args:
config (:class:`~.types.StreamingRecognitionConfig`): The
configuration to use for the stream.
requests (Iterable[:class:`~.types.StreamingRecognizeRequest`]):
The input objects.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
Returns:
Iterable[:class:`~.types.StreamingRecognizeResponse`]
Raises:
:exc:`google.gax.errors.GaxError` if the RPC is aborted.
:exc:`ValueError` if the parameters are invalid.
"""
return super(SpeechHelpers, self).streaming_recognize(
self._streaming_request_iterable(config, requests),
retry=retry,
timeout=timeout,
) | python | def streaming_recognize(
self,
config,
requests,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
):
"""Perform bi-directional speech recognition.
This method allows you to receive results while sending audio;
it is only available via. gRPC (not REST).
.. warning::
This method is EXPERIMENTAL. Its interface might change in the
future.
Example:
>>> from google.cloud.speech_v1 import enums
>>> from google.cloud.speech_v1 import SpeechClient
>>> from google.cloud.speech_v1 import types
>>> client = SpeechClient()
>>> config = types.StreamingRecognitionConfig(
... config=types.RecognitionConfig(
... encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
... ),
... )
>>> request = types.StreamingRecognizeRequest(audio_content=b'...')
>>> requests = [request]
>>> for element in client.streaming_recognize(config, requests):
... # process element
... pass
Args:
config (:class:`~.types.StreamingRecognitionConfig`): The
configuration to use for the stream.
requests (Iterable[:class:`~.types.StreamingRecognizeRequest`]):
The input objects.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
Returns:
Iterable[:class:`~.types.StreamingRecognizeResponse`]
Raises:
:exc:`google.gax.errors.GaxError` if the RPC is aborted.
:exc:`ValueError` if the parameters are invalid.
"""
return super(SpeechHelpers, self).streaming_recognize(
self._streaming_request_iterable(config, requests),
retry=retry,
timeout=timeout,
) | [
"def",
"streaming_recognize",
"(",
"self",
",",
"config",
",",
"requests",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
")",
":",
"return",
"super",
"(",
"SpeechHelpers",
",",
"self",
")",
".",
"streaming_recognize",
"(",
"self",
".",
"_streaming_request_iterable",
"(",
"config",
",",
"requests",
")",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
")"
] | Perform bi-directional speech recognition.
This method allows you to receive results while sending audio;
it is only available via. gRPC (not REST).
.. warning::
This method is EXPERIMENTAL. Its interface might change in the
future.
Example:
>>> from google.cloud.speech_v1 import enums
>>> from google.cloud.speech_v1 import SpeechClient
>>> from google.cloud.speech_v1 import types
>>> client = SpeechClient()
>>> config = types.StreamingRecognitionConfig(
... config=types.RecognitionConfig(
... encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
... ),
... )
>>> request = types.StreamingRecognizeRequest(audio_content=b'...')
>>> requests = [request]
>>> for element in client.streaming_recognize(config, requests):
... # process element
... pass
Args:
config (:class:`~.types.StreamingRecognitionConfig`): The
configuration to use for the stream.
requests (Iterable[:class:`~.types.StreamingRecognizeRequest`]):
The input objects.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
Returns:
Iterable[:class:`~.types.StreamingRecognizeResponse`]
Raises:
:exc:`google.gax.errors.GaxError` if the RPC is aborted.
:exc:`ValueError` if the parameters are invalid. | [
"Perform",
"bi",
"-",
"directional",
"speech",
"recognition",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/speech/google/cloud/speech_v1/helpers.py#L28-L84 |
28,149 | googleapis/google-cloud-python | speech/google/cloud/speech_v1/helpers.py | SpeechHelpers._streaming_request_iterable | def _streaming_request_iterable(self, config, requests):
"""A generator that yields the config followed by the requests.
Args:
config (~.speech_v1.types.StreamingRecognitionConfig): The
configuration to use for the stream.
requests (Iterable[~.speech_v1.types.StreamingRecognizeRequest]):
The input objects.
Returns:
Iterable[~.speech_v1.types.StreamingRecognizeRequest]): The
correctly formatted input for
:meth:`~.speech_v1.SpeechClient.streaming_recognize`.
"""
yield self.types.StreamingRecognizeRequest(streaming_config=config)
for request in requests:
yield request | python | def _streaming_request_iterable(self, config, requests):
"""A generator that yields the config followed by the requests.
Args:
config (~.speech_v1.types.StreamingRecognitionConfig): The
configuration to use for the stream.
requests (Iterable[~.speech_v1.types.StreamingRecognizeRequest]):
The input objects.
Returns:
Iterable[~.speech_v1.types.StreamingRecognizeRequest]): The
correctly formatted input for
:meth:`~.speech_v1.SpeechClient.streaming_recognize`.
"""
yield self.types.StreamingRecognizeRequest(streaming_config=config)
for request in requests:
yield request | [
"def",
"_streaming_request_iterable",
"(",
"self",
",",
"config",
",",
"requests",
")",
":",
"yield",
"self",
".",
"types",
".",
"StreamingRecognizeRequest",
"(",
"streaming_config",
"=",
"config",
")",
"for",
"request",
"in",
"requests",
":",
"yield",
"request"
] | A generator that yields the config followed by the requests.
Args:
config (~.speech_v1.types.StreamingRecognitionConfig): The
configuration to use for the stream.
requests (Iterable[~.speech_v1.types.StreamingRecognizeRequest]):
The input objects.
Returns:
Iterable[~.speech_v1.types.StreamingRecognizeRequest]): The
correctly formatted input for
:meth:`~.speech_v1.SpeechClient.streaming_recognize`. | [
"A",
"generator",
"that",
"yields",
"the",
"config",
"followed",
"by",
"the",
"requests",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/speech/google/cloud/speech_v1/helpers.py#L86-L102 |
28,150 | googleapis/google-cloud-python | bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py | DataTransferServiceClient.project_data_source_path | def project_data_source_path(cls, project, data_source):
"""Return a fully-qualified project_data_source string."""
return google.api_core.path_template.expand(
"projects/{project}/dataSources/{data_source}",
project=project,
data_source=data_source,
) | python | def project_data_source_path(cls, project, data_source):
"""Return a fully-qualified project_data_source string."""
return google.api_core.path_template.expand(
"projects/{project}/dataSources/{data_source}",
project=project,
data_source=data_source,
) | [
"def",
"project_data_source_path",
"(",
"cls",
",",
"project",
",",
"data_source",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/dataSources/{data_source}\"",
",",
"project",
"=",
"project",
",",
"data_source",
"=",
"data_source",
",",
")"
] | Return a fully-qualified project_data_source string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"project_data_source",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py#L88-L94 |
28,151 | googleapis/google-cloud-python | bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py | DataTransferServiceClient.project_transfer_config_path | def project_transfer_config_path(cls, project, transfer_config):
"""Return a fully-qualified project_transfer_config string."""
return google.api_core.path_template.expand(
"projects/{project}/transferConfigs/{transfer_config}",
project=project,
transfer_config=transfer_config,
) | python | def project_transfer_config_path(cls, project, transfer_config):
"""Return a fully-qualified project_transfer_config string."""
return google.api_core.path_template.expand(
"projects/{project}/transferConfigs/{transfer_config}",
project=project,
transfer_config=transfer_config,
) | [
"def",
"project_transfer_config_path",
"(",
"cls",
",",
"project",
",",
"transfer_config",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/transferConfigs/{transfer_config}\"",
",",
"project",
"=",
"project",
",",
"transfer_config",
"=",
"transfer_config",
",",
")"
] | Return a fully-qualified project_transfer_config string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"project_transfer_config",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py#L104-L110 |
28,152 | googleapis/google-cloud-python | bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py | DataTransferServiceClient.project_run_path | def project_run_path(cls, project, transfer_config, run):
"""Return a fully-qualified project_run string."""
return google.api_core.path_template.expand(
"projects/{project}/transferConfigs/{transfer_config}/runs/{run}",
project=project,
transfer_config=transfer_config,
run=run,
) | python | def project_run_path(cls, project, transfer_config, run):
"""Return a fully-qualified project_run string."""
return google.api_core.path_template.expand(
"projects/{project}/transferConfigs/{transfer_config}/runs/{run}",
project=project,
transfer_config=transfer_config,
run=run,
) | [
"def",
"project_run_path",
"(",
"cls",
",",
"project",
",",
"transfer_config",
",",
"run",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/transferConfigs/{transfer_config}/runs/{run}\"",
",",
"project",
"=",
"project",
",",
"transfer_config",
"=",
"transfer_config",
",",
"run",
"=",
"run",
",",
")"
] | Return a fully-qualified project_run string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"project_run",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py#L113-L120 |
28,153 | googleapis/google-cloud-python | bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py | DataTransferServiceClient.create_transfer_config | def create_transfer_config(
self,
parent,
transfer_config,
authorization_code=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a new data transfer configuration.
Example:
>>> from google.cloud import bigquery_datatransfer_v1
>>>
>>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `transfer_config`:
>>> transfer_config = {}
>>>
>>> response = client.create_transfer_config(parent, transfer_config)
Args:
parent (str): The BigQuery project id where the transfer configuration should be
created. Must be in the format
/projects/{project\_id}/locations/{location\_id} If specified location
and location of the destination bigquery dataset do not match - the
request will fail.
transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig`
authorization_code (str): Optional OAuth2 authorization code to use with this transfer
configuration. This is required if new credentials are needed, as
indicated by ``CheckValidCreds``. In order to obtain
authorization\_code, please make a request to
https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=<data\_source\_scopes>&redirect\_uri=<redirect\_uri>
- client\_id should be OAuth client\_id of BigQuery DTS API for the
given data source returned by ListDataSources method.
- data\_source\_scopes are the scopes returned by ListDataSources
method.
- redirect\_uri is an optional parameter. If not specified, then
authorization code is posted to the opener of authorization flow
window. Otherwise it will be sent to the redirect uri. A special
value of urn:ietf:wg:oauth:2.0:oob means that authorization code
should be returned in the title bar of the browser, with the page
text prompting the user to copy the code and paste it in the
application.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` 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_transfer_config" not in self._inner_api_calls:
self._inner_api_calls[
"create_transfer_config"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_transfer_config,
default_retry=self._method_configs["CreateTransferConfig"].retry,
default_timeout=self._method_configs["CreateTransferConfig"].timeout,
client_info=self._client_info,
)
request = datatransfer_pb2.CreateTransferConfigRequest(
parent=parent,
transfer_config=transfer_config,
authorization_code=authorization_code,
)
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_transfer_config"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def create_transfer_config(
self,
parent,
transfer_config,
authorization_code=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a new data transfer configuration.
Example:
>>> from google.cloud import bigquery_datatransfer_v1
>>>
>>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `transfer_config`:
>>> transfer_config = {}
>>>
>>> response = client.create_transfer_config(parent, transfer_config)
Args:
parent (str): The BigQuery project id where the transfer configuration should be
created. Must be in the format
/projects/{project\_id}/locations/{location\_id} If specified location
and location of the destination bigquery dataset do not match - the
request will fail.
transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig`
authorization_code (str): Optional OAuth2 authorization code to use with this transfer
configuration. This is required if new credentials are needed, as
indicated by ``CheckValidCreds``. In order to obtain
authorization\_code, please make a request to
https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=<data\_source\_scopes>&redirect\_uri=<redirect\_uri>
- client\_id should be OAuth client\_id of BigQuery DTS API for the
given data source returned by ListDataSources method.
- data\_source\_scopes are the scopes returned by ListDataSources
method.
- redirect\_uri is an optional parameter. If not specified, then
authorization code is posted to the opener of authorization flow
window. Otherwise it will be sent to the redirect uri. A special
value of urn:ietf:wg:oauth:2.0:oob means that authorization code
should be returned in the title bar of the browser, with the page
text prompting the user to copy the code and paste it in the
application.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` 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_transfer_config" not in self._inner_api_calls:
self._inner_api_calls[
"create_transfer_config"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_transfer_config,
default_retry=self._method_configs["CreateTransferConfig"].retry,
default_timeout=self._method_configs["CreateTransferConfig"].timeout,
client_info=self._client_info,
)
request = datatransfer_pb2.CreateTransferConfigRequest(
parent=parent,
transfer_config=transfer_config,
authorization_code=authorization_code,
)
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_transfer_config"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"create_transfer_config",
"(",
"self",
",",
"parent",
",",
"transfer_config",
",",
"authorization_code",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"create_transfer_config\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"create_transfer_config\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_transfer_config",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateTransferConfig\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateTransferConfig\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"datatransfer_pb2",
".",
"CreateTransferConfigRequest",
"(",
"parent",
"=",
"parent",
",",
"transfer_config",
"=",
"transfer_config",
",",
"authorization_code",
"=",
"authorization_code",
",",
")",
"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_transfer_config\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Creates a new data transfer configuration.
Example:
>>> from google.cloud import bigquery_datatransfer_v1
>>>
>>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `transfer_config`:
>>> transfer_config = {}
>>>
>>> response = client.create_transfer_config(parent, transfer_config)
Args:
parent (str): The BigQuery project id where the transfer configuration should be
created. Must be in the format
/projects/{project\_id}/locations/{location\_id} If specified location
and location of the destination bigquery dataset do not match - the
request will fail.
transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig`
authorization_code (str): Optional OAuth2 authorization code to use with this transfer
configuration. This is required if new credentials are needed, as
indicated by ``CheckValidCreds``. In order to obtain
authorization\_code, please make a request to
https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=<data\_source\_scopes>&redirect\_uri=<redirect\_uri>
- client\_id should be OAuth client\_id of BigQuery DTS API for the
given data source returned by ListDataSources method.
- data\_source\_scopes are the scopes returned by ListDataSources
method.
- redirect\_uri is an optional parameter. If not specified, then
authorization code is posted to the opener of authorization flow
window. Otherwise it will be sent to the redirect uri. A special
value of urn:ietf:wg:oauth:2.0:oob means that authorization code
should be returned in the title bar of the browser, with the page
text prompting the user to copy the code and paste it in the
application.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Creates",
"a",
"new",
"data",
"transfer",
"configuration",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py#L397-L498 |
28,154 | googleapis/google-cloud-python | bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py | DataTransferServiceClient.update_transfer_config | def update_transfer_config(
self,
transfer_config,
update_mask,
authorization_code=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates a data transfer configuration.
All fields must be set, even if they are not updated.
Example:
>>> from google.cloud import bigquery_datatransfer_v1
>>>
>>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
>>>
>>> # TODO: Initialize `transfer_config`:
>>> transfer_config = {}
>>>
>>> # TODO: Initialize `update_mask`:
>>> update_mask = {}
>>>
>>> response = client.update_transfer_config(transfer_config, update_mask)
Args:
transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig`
update_mask (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.FieldMask]): Required list of fields to be updated in this request.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_datatransfer_v1.types.FieldMask`
authorization_code (str): Optional OAuth2 authorization code to use with this transfer
configuration. If it is provided, the transfer configuration will be
associated with the authorizing user. In order to obtain
authorization\_code, please make a request to
https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=<data\_source\_scopes>&redirect\_uri=<redirect\_uri>
- client\_id should be OAuth client\_id of BigQuery DTS API for the
given data source returned by ListDataSources method.
- data\_source\_scopes are the scopes returned by ListDataSources
method.
- redirect\_uri is an optional parameter. If not specified, then
authorization code is posted to the opener of authorization flow
window. Otherwise it will be sent to the redirect uri. A special
value of urn:ietf:wg:oauth:2.0:oob means that authorization code
should be returned in the title bar of the browser, with the page
text prompting the user to copy the code and paste it in the
application.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "update_transfer_config" not in self._inner_api_calls:
self._inner_api_calls[
"update_transfer_config"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_transfer_config,
default_retry=self._method_configs["UpdateTransferConfig"].retry,
default_timeout=self._method_configs["UpdateTransferConfig"].timeout,
client_info=self._client_info,
)
request = datatransfer_pb2.UpdateTransferConfigRequest(
transfer_config=transfer_config,
update_mask=update_mask,
authorization_code=authorization_code,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("transfer_config.name", transfer_config.name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["update_transfer_config"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def update_transfer_config(
self,
transfer_config,
update_mask,
authorization_code=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates a data transfer configuration.
All fields must be set, even if they are not updated.
Example:
>>> from google.cloud import bigquery_datatransfer_v1
>>>
>>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
>>>
>>> # TODO: Initialize `transfer_config`:
>>> transfer_config = {}
>>>
>>> # TODO: Initialize `update_mask`:
>>> update_mask = {}
>>>
>>> response = client.update_transfer_config(transfer_config, update_mask)
Args:
transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig`
update_mask (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.FieldMask]): Required list of fields to be updated in this request.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_datatransfer_v1.types.FieldMask`
authorization_code (str): Optional OAuth2 authorization code to use with this transfer
configuration. If it is provided, the transfer configuration will be
associated with the authorizing user. In order to obtain
authorization\_code, please make a request to
https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=<data\_source\_scopes>&redirect\_uri=<redirect\_uri>
- client\_id should be OAuth client\_id of BigQuery DTS API for the
given data source returned by ListDataSources method.
- data\_source\_scopes are the scopes returned by ListDataSources
method.
- redirect\_uri is an optional parameter. If not specified, then
authorization code is posted to the opener of authorization flow
window. Otherwise it will be sent to the redirect uri. A special
value of urn:ietf:wg:oauth:2.0:oob means that authorization code
should be returned in the title bar of the browser, with the page
text prompting the user to copy the code and paste it in the
application.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "update_transfer_config" not in self._inner_api_calls:
self._inner_api_calls[
"update_transfer_config"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_transfer_config,
default_retry=self._method_configs["UpdateTransferConfig"].retry,
default_timeout=self._method_configs["UpdateTransferConfig"].timeout,
client_info=self._client_info,
)
request = datatransfer_pb2.UpdateTransferConfigRequest(
transfer_config=transfer_config,
update_mask=update_mask,
authorization_code=authorization_code,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("transfer_config.name", transfer_config.name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["update_transfer_config"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"update_transfer_config",
"(",
"self",
",",
"transfer_config",
",",
"update_mask",
",",
"authorization_code",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"update_transfer_config\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"update_transfer_config\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"update_transfer_config",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"UpdateTransferConfig\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"UpdateTransferConfig\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"datatransfer_pb2",
".",
"UpdateTransferConfigRequest",
"(",
"transfer_config",
"=",
"transfer_config",
",",
"update_mask",
"=",
"update_mask",
",",
"authorization_code",
"=",
"authorization_code",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"transfer_config.name\"",
",",
"transfer_config",
".",
"name",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"update_transfer_config\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Updates a data transfer configuration.
All fields must be set, even if they are not updated.
Example:
>>> from google.cloud import bigquery_datatransfer_v1
>>>
>>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
>>>
>>> # TODO: Initialize `transfer_config`:
>>> transfer_config = {}
>>>
>>> # TODO: Initialize `update_mask`:
>>> update_mask = {}
>>>
>>> response = client.update_transfer_config(transfer_config, update_mask)
Args:
transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig`
update_mask (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.FieldMask]): Required list of fields to be updated in this request.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.bigquery_datatransfer_v1.types.FieldMask`
authorization_code (str): Optional OAuth2 authorization code to use with this transfer
configuration. If it is provided, the transfer configuration will be
associated with the authorizing user. In order to obtain
authorization\_code, please make a request to
https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=<data\_source\_scopes>&redirect\_uri=<redirect\_uri>
- client\_id should be OAuth client\_id of BigQuery DTS API for the
given data source returned by ListDataSources method.
- data\_source\_scopes are the scopes returned by ListDataSources
method.
- redirect\_uri is an optional parameter. If not specified, then
authorization code is posted to the opener of authorization flow
window. Otherwise it will be sent to the redirect uri. A special
value of urn:ietf:wg:oauth:2.0:oob means that authorization code
should be returned in the title bar of the browser, with the page
text prompting the user to copy the code and paste it in the
application.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Updates",
"a",
"data",
"transfer",
"configuration",
".",
"All",
"fields",
"must",
"be",
"set",
"even",
"if",
"they",
"are",
"not",
"updated",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py#L500-L602 |
28,155 | googleapis/google-cloud-python | webrisk/google/cloud/webrisk_v1beta1/gapic/web_risk_service_v1_beta1_client.py | WebRiskServiceV1Beta1Client.compute_threat_list_diff | def compute_threat_list_diff(
self,
threat_type,
constraints,
version_token=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets the most recent threat list diffs.
Example:
>>> from google.cloud import webrisk_v1beta1
>>> from google.cloud.webrisk_v1beta1 import enums
>>>
>>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client()
>>>
>>> # TODO: Initialize `threat_type`:
>>> threat_type = enums.ThreatType.THREAT_TYPE_UNSPECIFIED
>>>
>>> # TODO: Initialize `constraints`:
>>> constraints = {}
>>>
>>> response = client.compute_threat_list_diff(threat_type, constraints)
Args:
threat_type (~google.cloud.webrisk_v1beta1.types.ThreatType): Required. The ThreatList to update.
constraints (Union[dict, ~google.cloud.webrisk_v1beta1.types.Constraints]): The constraints associated with this request.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.webrisk_v1beta1.types.Constraints`
version_token (bytes): The current version token of the client for the requested list (the
client version that was received from the last successful diff).
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.webrisk_v1beta1.types.ComputeThreatListDiffResponse` 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 "compute_threat_list_diff" not in self._inner_api_calls:
self._inner_api_calls[
"compute_threat_list_diff"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.compute_threat_list_diff,
default_retry=self._method_configs["ComputeThreatListDiff"].retry,
default_timeout=self._method_configs["ComputeThreatListDiff"].timeout,
client_info=self._client_info,
)
request = webrisk_pb2.ComputeThreatListDiffRequest(
threat_type=threat_type,
constraints=constraints,
version_token=version_token,
)
return self._inner_api_calls["compute_threat_list_diff"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def compute_threat_list_diff(
self,
threat_type,
constraints,
version_token=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets the most recent threat list diffs.
Example:
>>> from google.cloud import webrisk_v1beta1
>>> from google.cloud.webrisk_v1beta1 import enums
>>>
>>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client()
>>>
>>> # TODO: Initialize `threat_type`:
>>> threat_type = enums.ThreatType.THREAT_TYPE_UNSPECIFIED
>>>
>>> # TODO: Initialize `constraints`:
>>> constraints = {}
>>>
>>> response = client.compute_threat_list_diff(threat_type, constraints)
Args:
threat_type (~google.cloud.webrisk_v1beta1.types.ThreatType): Required. The ThreatList to update.
constraints (Union[dict, ~google.cloud.webrisk_v1beta1.types.Constraints]): The constraints associated with this request.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.webrisk_v1beta1.types.Constraints`
version_token (bytes): The current version token of the client for the requested list (the
client version that was received from the last successful diff).
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.webrisk_v1beta1.types.ComputeThreatListDiffResponse` 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 "compute_threat_list_diff" not in self._inner_api_calls:
self._inner_api_calls[
"compute_threat_list_diff"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.compute_threat_list_diff,
default_retry=self._method_configs["ComputeThreatListDiff"].retry,
default_timeout=self._method_configs["ComputeThreatListDiff"].timeout,
client_info=self._client_info,
)
request = webrisk_pb2.ComputeThreatListDiffRequest(
threat_type=threat_type,
constraints=constraints,
version_token=version_token,
)
return self._inner_api_calls["compute_threat_list_diff"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"compute_threat_list_diff",
"(",
"self",
",",
"threat_type",
",",
"constraints",
",",
"version_token",
"=",
"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",
"\"compute_threat_list_diff\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"compute_threat_list_diff\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"compute_threat_list_diff",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"ComputeThreatListDiff\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"ComputeThreatListDiff\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"webrisk_pb2",
".",
"ComputeThreatListDiffRequest",
"(",
"threat_type",
"=",
"threat_type",
",",
"constraints",
"=",
"constraints",
",",
"version_token",
"=",
"version_token",
",",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"compute_threat_list_diff\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Gets the most recent threat list diffs.
Example:
>>> from google.cloud import webrisk_v1beta1
>>> from google.cloud.webrisk_v1beta1 import enums
>>>
>>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client()
>>>
>>> # TODO: Initialize `threat_type`:
>>> threat_type = enums.ThreatType.THREAT_TYPE_UNSPECIFIED
>>>
>>> # TODO: Initialize `constraints`:
>>> constraints = {}
>>>
>>> response = client.compute_threat_list_diff(threat_type, constraints)
Args:
threat_type (~google.cloud.webrisk_v1beta1.types.ThreatType): Required. The ThreatList to update.
constraints (Union[dict, ~google.cloud.webrisk_v1beta1.types.Constraints]): The constraints associated with this request.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.webrisk_v1beta1.types.Constraints`
version_token (bytes): The current version token of the client for the requested list (the
client version that was received from the last successful diff).
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.webrisk_v1beta1.types.ComputeThreatListDiffResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Gets",
"the",
"most",
"recent",
"threat",
"list",
"diffs",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/webrisk/google/cloud/webrisk_v1beta1/gapic/web_risk_service_v1_beta1_client.py#L171-L242 |
28,156 | googleapis/google-cloud-python | webrisk/google/cloud/webrisk_v1beta1/gapic/web_risk_service_v1_beta1_client.py | WebRiskServiceV1Beta1Client.search_uris | def search_uris(
self,
uri,
threat_types,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
This method is used to check whether a URI is on a given threatList.
Example:
>>> from google.cloud import webrisk_v1beta1
>>> from google.cloud.webrisk_v1beta1 import enums
>>>
>>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client()
>>>
>>> # TODO: Initialize `uri`:
>>> uri = ''
>>>
>>> # TODO: Initialize `threat_types`:
>>> threat_types = []
>>>
>>> response = client.search_uris(uri, threat_types)
Args:
uri (str): The URI to be checked for matches.
threat_types (list[~google.cloud.webrisk_v1beta1.types.ThreatType]): Required. The ThreatLists to search in.
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.webrisk_v1beta1.types.SearchUrisResponse` 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 "search_uris" not in self._inner_api_calls:
self._inner_api_calls[
"search_uris"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.search_uris,
default_retry=self._method_configs["SearchUris"].retry,
default_timeout=self._method_configs["SearchUris"].timeout,
client_info=self._client_info,
)
request = webrisk_pb2.SearchUrisRequest(uri=uri, threat_types=threat_types)
return self._inner_api_calls["search_uris"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def search_uris(
self,
uri,
threat_types,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
This method is used to check whether a URI is on a given threatList.
Example:
>>> from google.cloud import webrisk_v1beta1
>>> from google.cloud.webrisk_v1beta1 import enums
>>>
>>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client()
>>>
>>> # TODO: Initialize `uri`:
>>> uri = ''
>>>
>>> # TODO: Initialize `threat_types`:
>>> threat_types = []
>>>
>>> response = client.search_uris(uri, threat_types)
Args:
uri (str): The URI to be checked for matches.
threat_types (list[~google.cloud.webrisk_v1beta1.types.ThreatType]): Required. The ThreatLists to search in.
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.webrisk_v1beta1.types.SearchUrisResponse` 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 "search_uris" not in self._inner_api_calls:
self._inner_api_calls[
"search_uris"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.search_uris,
default_retry=self._method_configs["SearchUris"].retry,
default_timeout=self._method_configs["SearchUris"].timeout,
client_info=self._client_info,
)
request = webrisk_pb2.SearchUrisRequest(uri=uri, threat_types=threat_types)
return self._inner_api_calls["search_uris"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"search_uris",
"(",
"self",
",",
"uri",
",",
"threat_types",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"search_uris\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"search_uris\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"search_uris",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"SearchUris\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"SearchUris\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"webrisk_pb2",
".",
"SearchUrisRequest",
"(",
"uri",
"=",
"uri",
",",
"threat_types",
"=",
"threat_types",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"search_uris\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | This method is used to check whether a URI is on a given threatList.
Example:
>>> from google.cloud import webrisk_v1beta1
>>> from google.cloud.webrisk_v1beta1 import enums
>>>
>>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client()
>>>
>>> # TODO: Initialize `uri`:
>>> uri = ''
>>>
>>> # TODO: Initialize `threat_types`:
>>> threat_types = []
>>>
>>> response = client.search_uris(uri, threat_types)
Args:
uri (str): The URI to be checked for matches.
threat_types (list[~google.cloud.webrisk_v1beta1.types.ThreatType]): Required. The ThreatLists to search in.
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.webrisk_v1beta1.types.SearchUrisResponse` 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. | [
"This",
"method",
"is",
"used",
"to",
"check",
"whether",
"a",
"URI",
"is",
"on",
"a",
"given",
"threatList",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/webrisk/google/cloud/webrisk_v1beta1/gapic/web_risk_service_v1_beta1_client.py#L244-L305 |
28,157 | googleapis/google-cloud-python | webrisk/google/cloud/webrisk_v1beta1/gapic/web_risk_service_v1_beta1_client.py | WebRiskServiceV1Beta1Client.search_hashes | def search_hashes(
self,
hash_prefix=None,
threat_types=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets the full hashes that match the requested hash prefix.
This is used after a hash prefix is looked up in a threatList
and there is a match. The client side threatList only holds partial hashes
so the client must query this method to determine if there is a full
hash match of a threat.
Example:
>>> from google.cloud import webrisk_v1beta1
>>>
>>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client()
>>>
>>> response = client.search_hashes()
Args:
hash_prefix (bytes): A hash prefix, consisting of the most significant 4-32 bytes of a SHA256
hash. For JSON requests, this field is base64-encoded.
threat_types (list[~google.cloud.webrisk_v1beta1.types.ThreatType]): Required. The ThreatLists to search in.
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.webrisk_v1beta1.types.SearchHashesResponse` 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 "search_hashes" not in self._inner_api_calls:
self._inner_api_calls[
"search_hashes"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.search_hashes,
default_retry=self._method_configs["SearchHashes"].retry,
default_timeout=self._method_configs["SearchHashes"].timeout,
client_info=self._client_info,
)
request = webrisk_pb2.SearchHashesRequest(
hash_prefix=hash_prefix, threat_types=threat_types
)
return self._inner_api_calls["search_hashes"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def search_hashes(
self,
hash_prefix=None,
threat_types=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets the full hashes that match the requested hash prefix.
This is used after a hash prefix is looked up in a threatList
and there is a match. The client side threatList only holds partial hashes
so the client must query this method to determine if there is a full
hash match of a threat.
Example:
>>> from google.cloud import webrisk_v1beta1
>>>
>>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client()
>>>
>>> response = client.search_hashes()
Args:
hash_prefix (bytes): A hash prefix, consisting of the most significant 4-32 bytes of a SHA256
hash. For JSON requests, this field is base64-encoded.
threat_types (list[~google.cloud.webrisk_v1beta1.types.ThreatType]): Required. The ThreatLists to search in.
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.webrisk_v1beta1.types.SearchHashesResponse` 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 "search_hashes" not in self._inner_api_calls:
self._inner_api_calls[
"search_hashes"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.search_hashes,
default_retry=self._method_configs["SearchHashes"].retry,
default_timeout=self._method_configs["SearchHashes"].timeout,
client_info=self._client_info,
)
request = webrisk_pb2.SearchHashesRequest(
hash_prefix=hash_prefix, threat_types=threat_types
)
return self._inner_api_calls["search_hashes"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"search_hashes",
"(",
"self",
",",
"hash_prefix",
"=",
"None",
",",
"threat_types",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"search_hashes\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"search_hashes\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"search_hashes",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"SearchHashes\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"SearchHashes\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"webrisk_pb2",
".",
"SearchHashesRequest",
"(",
"hash_prefix",
"=",
"hash_prefix",
",",
"threat_types",
"=",
"threat_types",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"search_hashes\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Gets the full hashes that match the requested hash prefix.
This is used after a hash prefix is looked up in a threatList
and there is a match. The client side threatList only holds partial hashes
so the client must query this method to determine if there is a full
hash match of a threat.
Example:
>>> from google.cloud import webrisk_v1beta1
>>>
>>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client()
>>>
>>> response = client.search_hashes()
Args:
hash_prefix (bytes): A hash prefix, consisting of the most significant 4-32 bytes of a SHA256
hash. For JSON requests, this field is base64-encoded.
threat_types (list[~google.cloud.webrisk_v1beta1.types.ThreatType]): Required. The ThreatLists to search in.
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.webrisk_v1beta1.types.SearchHashesResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Gets",
"the",
"full",
"hashes",
"that",
"match",
"the",
"requested",
"hash",
"prefix",
".",
"This",
"is",
"used",
"after",
"a",
"hash",
"prefix",
"is",
"looked",
"up",
"in",
"a",
"threatList",
"and",
"there",
"is",
"a",
"match",
".",
"The",
"client",
"side",
"threatList",
"only",
"holds",
"partial",
"hashes",
"so",
"the",
"client",
"must",
"query",
"this",
"method",
"to",
"determine",
"if",
"there",
"is",
"a",
"full",
"hash",
"match",
"of",
"a",
"threat",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/webrisk/google/cloud/webrisk_v1beta1/gapic/web_risk_service_v1_beta1_client.py#L307-L368 |
28,158 | googleapis/google-cloud-python | securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py | SecurityCenterClient.asset_path | def asset_path(cls, organization, asset):
"""Return a fully-qualified asset string."""
return google.api_core.path_template.expand(
"organizations/{organization}/assets/{asset}",
organization=organization,
asset=asset,
) | python | def asset_path(cls, organization, asset):
"""Return a fully-qualified asset string."""
return google.api_core.path_template.expand(
"organizations/{organization}/assets/{asset}",
organization=organization,
asset=asset,
) | [
"def",
"asset_path",
"(",
"cls",
",",
"organization",
",",
"asset",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"organizations/{organization}/assets/{asset}\"",
",",
"organization",
"=",
"organization",
",",
"asset",
"=",
"asset",
",",
")"
] | Return a fully-qualified asset string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"asset",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py#L104-L110 |
28,159 | googleapis/google-cloud-python | securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py | SecurityCenterClient.asset_security_marks_path | def asset_security_marks_path(cls, organization, asset):
"""Return a fully-qualified asset_security_marks string."""
return google.api_core.path_template.expand(
"organizations/{organization}/assets/{asset}/securityMarks",
organization=organization,
asset=asset,
) | python | def asset_security_marks_path(cls, organization, asset):
"""Return a fully-qualified asset_security_marks string."""
return google.api_core.path_template.expand(
"organizations/{organization}/assets/{asset}/securityMarks",
organization=organization,
asset=asset,
) | [
"def",
"asset_security_marks_path",
"(",
"cls",
",",
"organization",
",",
"asset",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"organizations/{organization}/assets/{asset}/securityMarks\"",
",",
"organization",
"=",
"organization",
",",
"asset",
"=",
"asset",
",",
")"
] | Return a fully-qualified asset_security_marks string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"asset_security_marks",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py#L113-L119 |
28,160 | googleapis/google-cloud-python | securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py | SecurityCenterClient.source_path | def source_path(cls, organization, source):
"""Return a fully-qualified source string."""
return google.api_core.path_template.expand(
"organizations/{organization}/sources/{source}",
organization=organization,
source=source,
) | python | def source_path(cls, organization, source):
"""Return a fully-qualified source string."""
return google.api_core.path_template.expand(
"organizations/{organization}/sources/{source}",
organization=organization,
source=source,
) | [
"def",
"source_path",
"(",
"cls",
",",
"organization",
",",
"source",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"organizations/{organization}/sources/{source}\"",
",",
"organization",
"=",
"organization",
",",
"source",
"=",
"source",
",",
")"
] | Return a fully-qualified source string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"source",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py#L122-L128 |
28,161 | googleapis/google-cloud-python | securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py | SecurityCenterClient.create_source | def create_source(
self,
parent,
source,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a source.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> parent = client.organization_path('[ORGANIZATION]')
>>>
>>> # TODO: Initialize `source`:
>>> source = {}
>>>
>>> response = client.create_source(parent, source)
Args:
parent (str): Resource name of the new source's parent. Its format should be
"organizations/[organization\_id]".
source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): The Source being created, only the display\_name and description will be
used. All other fields will be ignored.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.Source`
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.securitycenter_v1.types.Source` 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_source" not in self._inner_api_calls:
self._inner_api_calls[
"create_source"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_source,
default_retry=self._method_configs["CreateSource"].retry,
default_timeout=self._method_configs["CreateSource"].timeout,
client_info=self._client_info,
)
request = securitycenter_service_pb2.CreateSourceRequest(
parent=parent, source=source
)
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_source"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def create_source(
self,
parent,
source,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a source.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> parent = client.organization_path('[ORGANIZATION]')
>>>
>>> # TODO: Initialize `source`:
>>> source = {}
>>>
>>> response = client.create_source(parent, source)
Args:
parent (str): Resource name of the new source's parent. Its format should be
"organizations/[organization\_id]".
source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): The Source being created, only the display\_name and description will be
used. All other fields will be ignored.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.Source`
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.securitycenter_v1.types.Source` 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_source" not in self._inner_api_calls:
self._inner_api_calls[
"create_source"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_source,
default_retry=self._method_configs["CreateSource"].retry,
default_timeout=self._method_configs["CreateSource"].timeout,
client_info=self._client_info,
)
request = securitycenter_service_pb2.CreateSourceRequest(
parent=parent, source=source
)
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_source"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"create_source",
"(",
"self",
",",
"parent",
",",
"source",
",",
"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_source\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"create_source\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_source",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateSource\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateSource\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"securitycenter_service_pb2",
".",
"CreateSourceRequest",
"(",
"parent",
"=",
"parent",
",",
"source",
"=",
"source",
")",
"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_source\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Creates a source.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> parent = client.organization_path('[ORGANIZATION]')
>>>
>>> # TODO: Initialize `source`:
>>> source = {}
>>>
>>> response = client.create_source(parent, source)
Args:
parent (str): Resource name of the new source's parent. Its format should be
"organizations/[organization\_id]".
source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): The Source being created, only the display\_name and description will be
used. All other fields will be ignored.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.Source`
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.securitycenter_v1.types.Source` 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",
"source",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py#L256-L335 |
28,162 | googleapis/google-cloud-python | securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py | SecurityCenterClient.create_finding | def create_finding(
self,
parent,
finding_id,
finding,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a finding. The corresponding source must exist for finding creation
to succeed.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]')
>>>
>>> # TODO: Initialize `finding_id`:
>>> finding_id = ''
>>>
>>> # TODO: Initialize `finding`:
>>> finding = {}
>>>
>>> response = client.create_finding(parent, finding_id, finding)
Args:
parent (str): Resource name of the new finding's parent. Its format should be
"organizations/[organization\_id]/sources/[source\_id]".
finding_id (str): Unique identifier provided by the client within the parent scope.
It must be alphanumeric and less than or equal to 32 characters and
greater than 0 characters in length.
finding (Union[dict, ~google.cloud.securitycenter_v1.types.Finding]): The Finding being created. The name and security\_marks will be ignored
as they are both output only fields on this resource.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.Finding`
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.securitycenter_v1.types.Finding` 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_finding" not in self._inner_api_calls:
self._inner_api_calls[
"create_finding"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_finding,
default_retry=self._method_configs["CreateFinding"].retry,
default_timeout=self._method_configs["CreateFinding"].timeout,
client_info=self._client_info,
)
request = securitycenter_service_pb2.CreateFindingRequest(
parent=parent, finding_id=finding_id, finding=finding
)
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_finding"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def create_finding(
self,
parent,
finding_id,
finding,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a finding. The corresponding source must exist for finding creation
to succeed.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]')
>>>
>>> # TODO: Initialize `finding_id`:
>>> finding_id = ''
>>>
>>> # TODO: Initialize `finding`:
>>> finding = {}
>>>
>>> response = client.create_finding(parent, finding_id, finding)
Args:
parent (str): Resource name of the new finding's parent. Its format should be
"organizations/[organization\_id]/sources/[source\_id]".
finding_id (str): Unique identifier provided by the client within the parent scope.
It must be alphanumeric and less than or equal to 32 characters and
greater than 0 characters in length.
finding (Union[dict, ~google.cloud.securitycenter_v1.types.Finding]): The Finding being created. The name and security\_marks will be ignored
as they are both output only fields on this resource.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.Finding`
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.securitycenter_v1.types.Finding` 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_finding" not in self._inner_api_calls:
self._inner_api_calls[
"create_finding"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_finding,
default_retry=self._method_configs["CreateFinding"].retry,
default_timeout=self._method_configs["CreateFinding"].timeout,
client_info=self._client_info,
)
request = securitycenter_service_pb2.CreateFindingRequest(
parent=parent, finding_id=finding_id, finding=finding
)
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_finding"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"create_finding",
"(",
"self",
",",
"parent",
",",
"finding_id",
",",
"finding",
",",
"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_finding\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"create_finding\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_finding",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateFinding\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateFinding\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"securitycenter_service_pb2",
".",
"CreateFindingRequest",
"(",
"parent",
"=",
"parent",
",",
"finding_id",
"=",
"finding_id",
",",
"finding",
"=",
"finding",
")",
"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_finding\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Creates a finding. The corresponding source must exist for finding creation
to succeed.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]')
>>>
>>> # TODO: Initialize `finding_id`:
>>> finding_id = ''
>>>
>>> # TODO: Initialize `finding`:
>>> finding = {}
>>>
>>> response = client.create_finding(parent, finding_id, finding)
Args:
parent (str): Resource name of the new finding's parent. Its format should be
"organizations/[organization\_id]/sources/[source\_id]".
finding_id (str): Unique identifier provided by the client within the parent scope.
It must be alphanumeric and less than or equal to 32 characters and
greater than 0 characters in length.
finding (Union[dict, ~google.cloud.securitycenter_v1.types.Finding]): The Finding being created. The name and security\_marks will be ignored
as they are both output only fields on this resource.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.Finding`
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.securitycenter_v1.types.Finding` 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",
"finding",
".",
"The",
"corresponding",
"source",
"must",
"exist",
"for",
"finding",
"creation",
"to",
"succeed",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py#L337-L424 |
28,163 | googleapis/google-cloud-python | securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py | SecurityCenterClient.run_asset_discovery | def run_asset_discovery(
self,
parent,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Runs asset discovery. The discovery is tracked with a long-running
operation.
This API can only be called with limited frequency for an organization.
If it is called too frequently the caller will receive a
TOO\_MANY\_REQUESTS error.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> parent = client.organization_path('[ORGANIZATION]')
>>>
>>> response = client.run_asset_discovery(parent)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Name of the organization to run asset discovery for. Its format is
"organizations/[organization\_id]".
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.securitycenter_v1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "run_asset_discovery" not in self._inner_api_calls:
self._inner_api_calls[
"run_asset_discovery"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.run_asset_discovery,
default_retry=self._method_configs["RunAssetDiscovery"].retry,
default_timeout=self._method_configs["RunAssetDiscovery"].timeout,
client_info=self._client_info,
)
request = securitycenter_service_pb2.RunAssetDiscoveryRequest(parent=parent)
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["run_asset_discovery"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
empty_pb2.Empty,
metadata_type=empty_pb2.Empty,
) | python | def run_asset_discovery(
self,
parent,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Runs asset discovery. The discovery is tracked with a long-running
operation.
This API can only be called with limited frequency for an organization.
If it is called too frequently the caller will receive a
TOO\_MANY\_REQUESTS error.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> parent = client.organization_path('[ORGANIZATION]')
>>>
>>> response = client.run_asset_discovery(parent)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Name of the organization to run asset discovery for. Its format is
"organizations/[organization\_id]".
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.securitycenter_v1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "run_asset_discovery" not in self._inner_api_calls:
self._inner_api_calls[
"run_asset_discovery"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.run_asset_discovery,
default_retry=self._method_configs["RunAssetDiscovery"].retry,
default_timeout=self._method_configs["RunAssetDiscovery"].timeout,
client_info=self._client_info,
)
request = securitycenter_service_pb2.RunAssetDiscoveryRequest(parent=parent)
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["run_asset_discovery"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
empty_pb2.Empty,
metadata_type=empty_pb2.Empty,
) | [
"def",
"run_asset_discovery",
"(",
"self",
",",
"parent",
",",
"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",
"\"run_asset_discovery\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"run_asset_discovery\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"run_asset_discovery",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"RunAssetDiscovery\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"RunAssetDiscovery\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"securitycenter_service_pb2",
".",
"RunAssetDiscoveryRequest",
"(",
"parent",
"=",
"parent",
")",
"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",
"[",
"\"run_asset_discovery\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")",
"return",
"google",
".",
"api_core",
".",
"operation",
".",
"from_gapic",
"(",
"operation",
",",
"self",
".",
"transport",
".",
"_operations_client",
",",
"empty_pb2",
".",
"Empty",
",",
"metadata_type",
"=",
"empty_pb2",
".",
"Empty",
",",
")"
] | Runs asset discovery. The discovery is tracked with a long-running
operation.
This API can only be called with limited frequency for an organization.
If it is called too frequently the caller will receive a
TOO\_MANY\_REQUESTS error.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> parent = client.organization_path('[ORGANIZATION]')
>>>
>>> response = client.run_asset_discovery(parent)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Name of the organization to run asset discovery for. Its format is
"organizations/[organization\_id]".
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.securitycenter_v1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Runs",
"asset",
"discovery",
".",
"The",
"discovery",
"is",
"tracked",
"with",
"a",
"long",
"-",
"running",
"operation",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py#L1565-L1653 |
28,164 | googleapis/google-cloud-python | securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py | SecurityCenterClient.update_security_marks | def update_security_marks(
self,
security_marks,
update_mask=None,
start_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates security marks.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> # TODO: Initialize `security_marks`:
>>> security_marks = {}
>>>
>>> response = client.update_security_marks(security_marks)
Args:
security_marks (Union[dict, ~google.cloud.securitycenter_v1.types.SecurityMarks]): The security marks resource to update.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.SecurityMarks`
update_mask (Union[dict, ~google.cloud.securitycenter_v1.types.FieldMask]): The FieldMask to use when updating the security marks resource.
The field mask must not contain duplicate fields. If empty or set to
"marks", all marks will be replaced. Individual marks can be updated
using "marks.<mark\_key>".
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.FieldMask`
start_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): The time at which the updated SecurityMarks take effect.
If not set uses current server time. Updates will be applied to the
SecurityMarks that are active immediately preceding this time.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.Timestamp`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.securitycenter_v1.types.SecurityMarks` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "update_security_marks" not in self._inner_api_calls:
self._inner_api_calls[
"update_security_marks"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_security_marks,
default_retry=self._method_configs["UpdateSecurityMarks"].retry,
default_timeout=self._method_configs["UpdateSecurityMarks"].timeout,
client_info=self._client_info,
)
request = securitycenter_service_pb2.UpdateSecurityMarksRequest(
security_marks=security_marks,
update_mask=update_mask,
start_time=start_time,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("security_marks.name", security_marks.name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["update_security_marks"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def update_security_marks(
self,
security_marks,
update_mask=None,
start_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates security marks.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> # TODO: Initialize `security_marks`:
>>> security_marks = {}
>>>
>>> response = client.update_security_marks(security_marks)
Args:
security_marks (Union[dict, ~google.cloud.securitycenter_v1.types.SecurityMarks]): The security marks resource to update.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.SecurityMarks`
update_mask (Union[dict, ~google.cloud.securitycenter_v1.types.FieldMask]): The FieldMask to use when updating the security marks resource.
The field mask must not contain duplicate fields. If empty or set to
"marks", all marks will be replaced. Individual marks can be updated
using "marks.<mark\_key>".
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.FieldMask`
start_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): The time at which the updated SecurityMarks take effect.
If not set uses current server time. Updates will be applied to the
SecurityMarks that are active immediately preceding this time.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.Timestamp`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.securitycenter_v1.types.SecurityMarks` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "update_security_marks" not in self._inner_api_calls:
self._inner_api_calls[
"update_security_marks"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_security_marks,
default_retry=self._method_configs["UpdateSecurityMarks"].retry,
default_timeout=self._method_configs["UpdateSecurityMarks"].timeout,
client_info=self._client_info,
)
request = securitycenter_service_pb2.UpdateSecurityMarksRequest(
security_marks=security_marks,
update_mask=update_mask,
start_time=start_time,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("security_marks.name", security_marks.name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["update_security_marks"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"update_security_marks",
"(",
"self",
",",
"security_marks",
",",
"update_mask",
"=",
"None",
",",
"start_time",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"update_security_marks\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"update_security_marks\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"update_security_marks",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"UpdateSecurityMarks\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"UpdateSecurityMarks\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"securitycenter_service_pb2",
".",
"UpdateSecurityMarksRequest",
"(",
"security_marks",
"=",
"security_marks",
",",
"update_mask",
"=",
"update_mask",
",",
"start_time",
"=",
"start_time",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"security_marks.name\"",
",",
"security_marks",
".",
"name",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"update_security_marks\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Updates security marks.
Example:
>>> from google.cloud import securitycenter_v1
>>>
>>> client = securitycenter_v1.SecurityCenterClient()
>>>
>>> # TODO: Initialize `security_marks`:
>>> security_marks = {}
>>>
>>> response = client.update_security_marks(security_marks)
Args:
security_marks (Union[dict, ~google.cloud.securitycenter_v1.types.SecurityMarks]): The security marks resource to update.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.SecurityMarks`
update_mask (Union[dict, ~google.cloud.securitycenter_v1.types.FieldMask]): The FieldMask to use when updating the security marks resource.
The field mask must not contain duplicate fields. If empty or set to
"marks", all marks will be replaced. Individual marks can be updated
using "marks.<mark\_key>".
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.FieldMask`
start_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): The time at which the updated SecurityMarks take effect.
If not set uses current server time. Updates will be applied to the
SecurityMarks that are active immediately preceding this time.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1.types.Timestamp`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.securitycenter_v1.types.SecurityMarks` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Updates",
"security",
"marks",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py#L2165-L2256 |
28,165 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row_set.py | RowSet.add_row_range_from_keys | def add_row_range_from_keys(
self, start_key=None, end_key=None, start_inclusive=True, end_inclusive=False
):
"""Add row range to row_ranges list from the row keys
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_range_from_keys]
:end-before: [END bigtable_row_range_from_keys]
:type start_key: bytes
:param start_key: (Optional) Start key of the row range. If left empty,
will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) End key of the row range. If left empty,
will be interpreted as the empty string and range will
be unbounded on the high end.
:type start_inclusive: bool
:param start_inclusive: (Optional) Whether the ``start_key`` should be
considered inclusive. The default is True (inclusive).
:type end_inclusive: bool
:param end_inclusive: (Optional) Whether the ``end_key`` should be
considered inclusive. The default is False (exclusive).
"""
row_range = RowRange(start_key, end_key, start_inclusive, end_inclusive)
self.row_ranges.append(row_range) | python | def add_row_range_from_keys(
self, start_key=None, end_key=None, start_inclusive=True, end_inclusive=False
):
"""Add row range to row_ranges list from the row keys
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_range_from_keys]
:end-before: [END bigtable_row_range_from_keys]
:type start_key: bytes
:param start_key: (Optional) Start key of the row range. If left empty,
will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) End key of the row range. If left empty,
will be interpreted as the empty string and range will
be unbounded on the high end.
:type start_inclusive: bool
:param start_inclusive: (Optional) Whether the ``start_key`` should be
considered inclusive. The default is True (inclusive).
:type end_inclusive: bool
:param end_inclusive: (Optional) Whether the ``end_key`` should be
considered inclusive. The default is False (exclusive).
"""
row_range = RowRange(start_key, end_key, start_inclusive, end_inclusive)
self.row_ranges.append(row_range) | [
"def",
"add_row_range_from_keys",
"(",
"self",
",",
"start_key",
"=",
"None",
",",
"end_key",
"=",
"None",
",",
"start_inclusive",
"=",
"True",
",",
"end_inclusive",
"=",
"False",
")",
":",
"row_range",
"=",
"RowRange",
"(",
"start_key",
",",
"end_key",
",",
"start_inclusive",
",",
"end_inclusive",
")",
"self",
".",
"row_ranges",
".",
"append",
"(",
"row_range",
")"
] | Add row range to row_ranges list from the row keys
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_range_from_keys]
:end-before: [END bigtable_row_range_from_keys]
:type start_key: bytes
:param start_key: (Optional) Start key of the row range. If left empty,
will be interpreted as the empty string.
:type end_key: bytes
:param end_key: (Optional) End key of the row range. If left empty,
will be interpreted as the empty string and range will
be unbounded on the high end.
:type start_inclusive: bool
:param start_inclusive: (Optional) Whether the ``start_key`` should be
considered inclusive. The default is True (inclusive).
:type end_inclusive: bool
:param end_inclusive: (Optional) Whether the ``end_key`` should be
considered inclusive. The default is False (exclusive). | [
"Add",
"row",
"range",
"to",
"row_ranges",
"list",
"from",
"the",
"row",
"keys"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row_set.py#L81-L110 |
28,166 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row_set.py | RowSet._update_message_request | def _update_message_request(self, message):
"""Add row keys and row range to given request message
:type message: class:`data_messages_v2_pb2.ReadRowsRequest`
:param message: The ``ReadRowsRequest`` protobuf
"""
for each in self.row_keys:
message.rows.row_keys.append(_to_bytes(each))
for each in self.row_ranges:
r_kwrags = each.get_range_kwargs()
message.rows.row_ranges.add(**r_kwrags) | python | def _update_message_request(self, message):
"""Add row keys and row range to given request message
:type message: class:`data_messages_v2_pb2.ReadRowsRequest`
:param message: The ``ReadRowsRequest`` protobuf
"""
for each in self.row_keys:
message.rows.row_keys.append(_to_bytes(each))
for each in self.row_ranges:
r_kwrags = each.get_range_kwargs()
message.rows.row_ranges.add(**r_kwrags) | [
"def",
"_update_message_request",
"(",
"self",
",",
"message",
")",
":",
"for",
"each",
"in",
"self",
".",
"row_keys",
":",
"message",
".",
"rows",
".",
"row_keys",
".",
"append",
"(",
"_to_bytes",
"(",
"each",
")",
")",
"for",
"each",
"in",
"self",
".",
"row_ranges",
":",
"r_kwrags",
"=",
"each",
".",
"get_range_kwargs",
"(",
")",
"message",
".",
"rows",
".",
"row_ranges",
".",
"add",
"(",
"*",
"*",
"r_kwrags",
")"
] | Add row keys and row range to given request message
:type message: class:`data_messages_v2_pb2.ReadRowsRequest`
:param message: The ``ReadRowsRequest`` protobuf | [
"Add",
"row",
"keys",
"and",
"row",
"range",
"to",
"given",
"request",
"message"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row_set.py#L112-L123 |
28,167 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row_set.py | RowRange.get_range_kwargs | def get_range_kwargs(self):
""" Convert row range object to dict which can be passed to
google.bigtable.v2.RowRange add method.
"""
range_kwargs = {}
if self.start_key is not None:
start_key_key = "start_key_open"
if self.start_inclusive:
start_key_key = "start_key_closed"
range_kwargs[start_key_key] = _to_bytes(self.start_key)
if self.end_key is not None:
end_key_key = "end_key_open"
if self.end_inclusive:
end_key_key = "end_key_closed"
range_kwargs[end_key_key] = _to_bytes(self.end_key)
return range_kwargs | python | def get_range_kwargs(self):
""" Convert row range object to dict which can be passed to
google.bigtable.v2.RowRange add method.
"""
range_kwargs = {}
if self.start_key is not None:
start_key_key = "start_key_open"
if self.start_inclusive:
start_key_key = "start_key_closed"
range_kwargs[start_key_key] = _to_bytes(self.start_key)
if self.end_key is not None:
end_key_key = "end_key_open"
if self.end_inclusive:
end_key_key = "end_key_closed"
range_kwargs[end_key_key] = _to_bytes(self.end_key)
return range_kwargs | [
"def",
"get_range_kwargs",
"(",
"self",
")",
":",
"range_kwargs",
"=",
"{",
"}",
"if",
"self",
".",
"start_key",
"is",
"not",
"None",
":",
"start_key_key",
"=",
"\"start_key_open\"",
"if",
"self",
".",
"start_inclusive",
":",
"start_key_key",
"=",
"\"start_key_closed\"",
"range_kwargs",
"[",
"start_key_key",
"]",
"=",
"_to_bytes",
"(",
"self",
".",
"start_key",
")",
"if",
"self",
".",
"end_key",
"is",
"not",
"None",
":",
"end_key_key",
"=",
"\"end_key_open\"",
"if",
"self",
".",
"end_inclusive",
":",
"end_key_key",
"=",
"\"end_key_closed\"",
"range_kwargs",
"[",
"end_key_key",
"]",
"=",
"_to_bytes",
"(",
"self",
".",
"end_key",
")",
"return",
"range_kwargs"
] | Convert row range object to dict which can be passed to
google.bigtable.v2.RowRange add method. | [
"Convert",
"row",
"range",
"object",
"to",
"dict",
"which",
"can",
"be",
"passed",
"to",
"google",
".",
"bigtable",
".",
"v2",
".",
"RowRange",
"add",
"method",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row_set.py#L176-L192 |
28,168 | googleapis/google-cloud-python | error_reporting/google/cloud/error_reporting/client.py | Client._build_error_report | def _build_error_report(
self, message, report_location=None, http_context=None, user=None
):
"""Builds the Error Reporting object to report.
This builds the object according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
:type message: str
:param message: The stack trace that was reported or logged by the
service.
:type report_location: dict
:param report_location: The location in the source code where the
decision was made to report the error, usually the place
where it was logged. For a logged exception this would be the
source line where the exception is logged, usually close to
the place where it was caught.
This should be a Python dict that contains the keys 'filePath',
'lineNumber', and 'functionName'
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This can
be a user ID, an email address, or an arbitrary token that
uniquely identifies the user. When sending an error
report, leave this field empty if the user was not
logged in. In this case the Error Reporting system will
use other data, such as remote IP address,
to distinguish affected users.
:rtype: dict
:returns: A dict payload ready to be serialized to JSON and sent to
the API.
"""
payload = {
"serviceContext": {"service": self.service},
"message": "{0}".format(message),
}
if self.version:
payload["serviceContext"]["version"] = self.version
if report_location or http_context or user:
payload["context"] = {}
if report_location:
payload["context"]["reportLocation"] = report_location
if http_context:
http_context_dict = http_context.__dict__
# strip out None values
payload["context"]["httpRequest"] = {
key: value
for key, value in six.iteritems(http_context_dict)
if value is not None
}
if user:
payload["context"]["user"] = user
return payload | python | def _build_error_report(
self, message, report_location=None, http_context=None, user=None
):
"""Builds the Error Reporting object to report.
This builds the object according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
:type message: str
:param message: The stack trace that was reported or logged by the
service.
:type report_location: dict
:param report_location: The location in the source code where the
decision was made to report the error, usually the place
where it was logged. For a logged exception this would be the
source line where the exception is logged, usually close to
the place where it was caught.
This should be a Python dict that contains the keys 'filePath',
'lineNumber', and 'functionName'
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This can
be a user ID, an email address, or an arbitrary token that
uniquely identifies the user. When sending an error
report, leave this field empty if the user was not
logged in. In this case the Error Reporting system will
use other data, such as remote IP address,
to distinguish affected users.
:rtype: dict
:returns: A dict payload ready to be serialized to JSON and sent to
the API.
"""
payload = {
"serviceContext": {"service": self.service},
"message": "{0}".format(message),
}
if self.version:
payload["serviceContext"]["version"] = self.version
if report_location or http_context or user:
payload["context"] = {}
if report_location:
payload["context"]["reportLocation"] = report_location
if http_context:
http_context_dict = http_context.__dict__
# strip out None values
payload["context"]["httpRequest"] = {
key: value
for key, value in six.iteritems(http_context_dict)
if value is not None
}
if user:
payload["context"]["user"] = user
return payload | [
"def",
"_build_error_report",
"(",
"self",
",",
"message",
",",
"report_location",
"=",
"None",
",",
"http_context",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"\"serviceContext\"",
":",
"{",
"\"service\"",
":",
"self",
".",
"service",
"}",
",",
"\"message\"",
":",
"\"{0}\"",
".",
"format",
"(",
"message",
")",
",",
"}",
"if",
"self",
".",
"version",
":",
"payload",
"[",
"\"serviceContext\"",
"]",
"[",
"\"version\"",
"]",
"=",
"self",
".",
"version",
"if",
"report_location",
"or",
"http_context",
"or",
"user",
":",
"payload",
"[",
"\"context\"",
"]",
"=",
"{",
"}",
"if",
"report_location",
":",
"payload",
"[",
"\"context\"",
"]",
"[",
"\"reportLocation\"",
"]",
"=",
"report_location",
"if",
"http_context",
":",
"http_context_dict",
"=",
"http_context",
".",
"__dict__",
"# strip out None values",
"payload",
"[",
"\"context\"",
"]",
"[",
"\"httpRequest\"",
"]",
"=",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"http_context_dict",
")",
"if",
"value",
"is",
"not",
"None",
"}",
"if",
"user",
":",
"payload",
"[",
"\"context\"",
"]",
"[",
"\"user\"",
"]",
"=",
"user",
"return",
"payload"
] | Builds the Error Reporting object to report.
This builds the object according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
:type message: str
:param message: The stack trace that was reported or logged by the
service.
:type report_location: dict
:param report_location: The location in the source code where the
decision was made to report the error, usually the place
where it was logged. For a logged exception this would be the
source line where the exception is logged, usually close to
the place where it was caught.
This should be a Python dict that contains the keys 'filePath',
'lineNumber', and 'functionName'
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This can
be a user ID, an email address, or an arbitrary token that
uniquely identifies the user. When sending an error
report, leave this field empty if the user was not
logged in. In this case the Error Reporting system will
use other data, such as remote IP address,
to distinguish affected users.
:rtype: dict
:returns: A dict payload ready to be serialized to JSON and sent to
the API. | [
"Builds",
"the",
"Error",
"Reporting",
"object",
"to",
"report",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/error_reporting/client.py#L184-L247 |
28,169 | googleapis/google-cloud-python | error_reporting/google/cloud/error_reporting/client.py | Client._send_error_report | def _send_error_report(
self, message, report_location=None, http_context=None, user=None
):
"""Makes the call to the Error Reporting API.
This is the lower-level interface to build and send the payload,
generally users will use either report() or report_exception() to
automatically gather the parameters for this method.
:type message: str
:param message: The stack trace that was reported or logged by the
service.
:type report_location: dict
:param report_location: The location in the source code where the
decision was made to report the error, usually the place
where it was logged. For a logged exception this would be the
source line where the exception is logged, usually close to
the place where it was caught.
This should be a Python dict that contains the keys 'filePath',
'lineNumber', and 'functionName'
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This can
be a user ID, an email address, or an arbitrary token that
uniquely identifies the user. When sending an error
report, leave this field empty if the user was not
logged in. In this case the Error Reporting system will
use other data, such as remote IP address,
to distinguish affected users.
"""
error_report = self._build_error_report(
message, report_location, http_context, user
)
self.report_errors_api.report_error_event(error_report) | python | def _send_error_report(
self, message, report_location=None, http_context=None, user=None
):
"""Makes the call to the Error Reporting API.
This is the lower-level interface to build and send the payload,
generally users will use either report() or report_exception() to
automatically gather the parameters for this method.
:type message: str
:param message: The stack trace that was reported or logged by the
service.
:type report_location: dict
:param report_location: The location in the source code where the
decision was made to report the error, usually the place
where it was logged. For a logged exception this would be the
source line where the exception is logged, usually close to
the place where it was caught.
This should be a Python dict that contains the keys 'filePath',
'lineNumber', and 'functionName'
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This can
be a user ID, an email address, or an arbitrary token that
uniquely identifies the user. When sending an error
report, leave this field empty if the user was not
logged in. In this case the Error Reporting system will
use other data, such as remote IP address,
to distinguish affected users.
"""
error_report = self._build_error_report(
message, report_location, http_context, user
)
self.report_errors_api.report_error_event(error_report) | [
"def",
"_send_error_report",
"(",
"self",
",",
"message",
",",
"report_location",
"=",
"None",
",",
"http_context",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"error_report",
"=",
"self",
".",
"_build_error_report",
"(",
"message",
",",
"report_location",
",",
"http_context",
",",
"user",
")",
"self",
".",
"report_errors_api",
".",
"report_error_event",
"(",
"error_report",
")"
] | Makes the call to the Error Reporting API.
This is the lower-level interface to build and send the payload,
generally users will use either report() or report_exception() to
automatically gather the parameters for this method.
:type message: str
:param message: The stack trace that was reported or logged by the
service.
:type report_location: dict
:param report_location: The location in the source code where the
decision was made to report the error, usually the place
where it was logged. For a logged exception this would be the
source line where the exception is logged, usually close to
the place where it was caught.
This should be a Python dict that contains the keys 'filePath',
'lineNumber', and 'functionName'
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This can
be a user ID, an email address, or an arbitrary token that
uniquely identifies the user. When sending an error
report, leave this field empty if the user was not
logged in. In this case the Error Reporting system will
use other data, such as remote IP address,
to distinguish affected users. | [
"Makes",
"the",
"call",
"to",
"the",
"Error",
"Reporting",
"API",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/error_reporting/client.py#L249-L288 |
28,170 | googleapis/google-cloud-python | error_reporting/google/cloud/error_reporting/client.py | Client.report | def report(self, message, http_context=None, user=None):
""" Reports a message to Stackdriver Error Reporting
https://cloud.google.com/error-reporting/docs/formatting-error-messages
:type message: str
:param message: A user-supplied message to report
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This
can be a user ID, an email address, or an arbitrary
token that uniquely identifies the user. When sending
an error report, leave this field empty if the user
was not logged in. In this case the Error Reporting
system will use other data, such as remote IP address,
to distinguish affected users.
Example:
.. code-block:: python
>>> client.report("Something went wrong!")
"""
stack = traceback.extract_stack()
last_call = stack[-2]
file_path = last_call[0]
line_number = last_call[1]
function_name = last_call[2]
report_location = {
"filePath": file_path,
"lineNumber": line_number,
"functionName": function_name,
}
self._send_error_report(
message,
http_context=http_context,
user=user,
report_location=report_location,
) | python | def report(self, message, http_context=None, user=None):
""" Reports a message to Stackdriver Error Reporting
https://cloud.google.com/error-reporting/docs/formatting-error-messages
:type message: str
:param message: A user-supplied message to report
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This
can be a user ID, an email address, or an arbitrary
token that uniquely identifies the user. When sending
an error report, leave this field empty if the user
was not logged in. In this case the Error Reporting
system will use other data, such as remote IP address,
to distinguish affected users.
Example:
.. code-block:: python
>>> client.report("Something went wrong!")
"""
stack = traceback.extract_stack()
last_call = stack[-2]
file_path = last_call[0]
line_number = last_call[1]
function_name = last_call[2]
report_location = {
"filePath": file_path,
"lineNumber": line_number,
"functionName": function_name,
}
self._send_error_report(
message,
http_context=http_context,
user=user,
report_location=report_location,
) | [
"def",
"report",
"(",
"self",
",",
"message",
",",
"http_context",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"stack",
"=",
"traceback",
".",
"extract_stack",
"(",
")",
"last_call",
"=",
"stack",
"[",
"-",
"2",
"]",
"file_path",
"=",
"last_call",
"[",
"0",
"]",
"line_number",
"=",
"last_call",
"[",
"1",
"]",
"function_name",
"=",
"last_call",
"[",
"2",
"]",
"report_location",
"=",
"{",
"\"filePath\"",
":",
"file_path",
",",
"\"lineNumber\"",
":",
"line_number",
",",
"\"functionName\"",
":",
"function_name",
",",
"}",
"self",
".",
"_send_error_report",
"(",
"message",
",",
"http_context",
"=",
"http_context",
",",
"user",
"=",
"user",
",",
"report_location",
"=",
"report_location",
",",
")"
] | Reports a message to Stackdriver Error Reporting
https://cloud.google.com/error-reporting/docs/formatting-error-messages
:type message: str
:param message: A user-supplied message to report
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This
can be a user ID, an email address, or an arbitrary
token that uniquely identifies the user. When sending
an error report, leave this field empty if the user
was not logged in. In this case the Error Reporting
system will use other data, such as remote IP address,
to distinguish affected users.
Example:
.. code-block:: python
>>> client.report("Something went wrong!") | [
"Reports",
"a",
"message",
"to",
"Stackdriver",
"Error",
"Reporting"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/error_reporting/client.py#L290-L333 |
28,171 | googleapis/google-cloud-python | error_reporting/google/cloud/error_reporting/client.py | Client.report_exception | def report_exception(self, http_context=None, user=None):
""" Reports the details of the latest exceptions to Stackdriver Error
Reporting.
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This
can be a user ID, an email address, or an arbitrary
token that uniquely identifies the user. When sending an
error report, leave this field empty if the user was
not logged in. In this case the Error Reporting system
will use other data, such as remote IP address,
to distinguish affected users.
Example::
>>> try:
>>> raise NameError
>>> except Exception:
>>> client.report_exception()
"""
self._send_error_report(
traceback.format_exc(), http_context=http_context, user=user
) | python | def report_exception(self, http_context=None, user=None):
""" Reports the details of the latest exceptions to Stackdriver Error
Reporting.
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This
can be a user ID, an email address, or an arbitrary
token that uniquely identifies the user. When sending an
error report, leave this field empty if the user was
not logged in. In this case the Error Reporting system
will use other data, such as remote IP address,
to distinguish affected users.
Example::
>>> try:
>>> raise NameError
>>> except Exception:
>>> client.report_exception()
"""
self._send_error_report(
traceback.format_exc(), http_context=http_context, user=user
) | [
"def",
"report_exception",
"(",
"self",
",",
"http_context",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"self",
".",
"_send_error_report",
"(",
"traceback",
".",
"format_exc",
"(",
")",
",",
"http_context",
"=",
"http_context",
",",
"user",
"=",
"user",
")"
] | Reports the details of the latest exceptions to Stackdriver Error
Reporting.
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user: str
:param user: The user who caused or was affected by the crash. This
can be a user ID, an email address, or an arbitrary
token that uniquely identifies the user. When sending an
error report, leave this field empty if the user was
not logged in. In this case the Error Reporting system
will use other data, such as remote IP address,
to distinguish affected users.
Example::
>>> try:
>>> raise NameError
>>> except Exception:
>>> client.report_exception() | [
"Reports",
"the",
"details",
"of",
"the",
"latest",
"exceptions",
"to",
"Stackdriver",
"Error",
"Reporting",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/error_reporting/client.py#L335-L361 |
28,172 | googleapis/google-cloud-python | datastore/google/cloud/datastore/transaction.py | Transaction.current | def current(self):
"""Return the topmost transaction.
.. note::
If the topmost element on the stack is not a transaction,
returns None.
:rtype: :class:`google.cloud.datastore.transaction.Transaction` or None
:returns: The current transaction (if any are active).
"""
top = super(Transaction, self).current()
if isinstance(top, Transaction):
return top | python | def current(self):
"""Return the topmost transaction.
.. note::
If the topmost element on the stack is not a transaction,
returns None.
:rtype: :class:`google.cloud.datastore.transaction.Transaction` or None
:returns: The current transaction (if any are active).
"""
top = super(Transaction, self).current()
if isinstance(top, Transaction):
return top | [
"def",
"current",
"(",
"self",
")",
":",
"top",
"=",
"super",
"(",
"Transaction",
",",
"self",
")",
".",
"current",
"(",
")",
"if",
"isinstance",
"(",
"top",
",",
"Transaction",
")",
":",
"return",
"top"
] | Return the topmost transaction.
.. note::
If the topmost element on the stack is not a transaction,
returns None.
:rtype: :class:`google.cloud.datastore.transaction.Transaction` or None
:returns: The current transaction (if any are active). | [
"Return",
"the",
"topmost",
"transaction",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/transaction.py#L181-L194 |
28,173 | googleapis/google-cloud-python | datastore/google/cloud/datastore/transaction.py | Transaction.begin | def begin(self):
"""Begins a transaction.
This method is called automatically when entering a with
statement, however it can be called explicitly if you don't want
to use a context manager.
:raises: :class:`~exceptions.ValueError` if the transaction has
already begun.
"""
super(Transaction, self).begin()
try:
response_pb = self._client._datastore_api.begin_transaction(self.project)
self._id = response_pb.transaction
except: # noqa: E722 do not use bare except, specify exception instead
self._status = self._ABORTED
raise | python | def begin(self):
"""Begins a transaction.
This method is called automatically when entering a with
statement, however it can be called explicitly if you don't want
to use a context manager.
:raises: :class:`~exceptions.ValueError` if the transaction has
already begun.
"""
super(Transaction, self).begin()
try:
response_pb = self._client._datastore_api.begin_transaction(self.project)
self._id = response_pb.transaction
except: # noqa: E722 do not use bare except, specify exception instead
self._status = self._ABORTED
raise | [
"def",
"begin",
"(",
"self",
")",
":",
"super",
"(",
"Transaction",
",",
"self",
")",
".",
"begin",
"(",
")",
"try",
":",
"response_pb",
"=",
"self",
".",
"_client",
".",
"_datastore_api",
".",
"begin_transaction",
"(",
"self",
".",
"project",
")",
"self",
".",
"_id",
"=",
"response_pb",
".",
"transaction",
"except",
":",
"# noqa: E722 do not use bare except, specify exception instead",
"self",
".",
"_status",
"=",
"self",
".",
"_ABORTED",
"raise"
] | Begins a transaction.
This method is called automatically when entering a with
statement, however it can be called explicitly if you don't want
to use a context manager.
:raises: :class:`~exceptions.ValueError` if the transaction has
already begun. | [
"Begins",
"a",
"transaction",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/transaction.py#L196-L212 |
28,174 | googleapis/google-cloud-python | datastore/google/cloud/datastore/transaction.py | Transaction.rollback | def rollback(self):
"""Rolls back the current transaction.
This method has necessary side-effects:
- Sets the current transaction's ID to None.
"""
try:
# No need to use the response it contains nothing.
self._client._datastore_api.rollback(self.project, self._id)
finally:
super(Transaction, self).rollback()
# Clear our own ID in case this gets accidentally reused.
self._id = None | python | def rollback(self):
"""Rolls back the current transaction.
This method has necessary side-effects:
- Sets the current transaction's ID to None.
"""
try:
# No need to use the response it contains nothing.
self._client._datastore_api.rollback(self.project, self._id)
finally:
super(Transaction, self).rollback()
# Clear our own ID in case this gets accidentally reused.
self._id = None | [
"def",
"rollback",
"(",
"self",
")",
":",
"try",
":",
"# No need to use the response it contains nothing.",
"self",
".",
"_client",
".",
"_datastore_api",
".",
"rollback",
"(",
"self",
".",
"project",
",",
"self",
".",
"_id",
")",
"finally",
":",
"super",
"(",
"Transaction",
",",
"self",
")",
".",
"rollback",
"(",
")",
"# Clear our own ID in case this gets accidentally reused.",
"self",
".",
"_id",
"=",
"None"
] | Rolls back the current transaction.
This method has necessary side-effects:
- Sets the current transaction's ID to None. | [
"Rolls",
"back",
"the",
"current",
"transaction",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/transaction.py#L214-L227 |
28,175 | googleapis/google-cloud-python | datastore/google/cloud/datastore/transaction.py | Transaction.put | def put(self, entity):
"""Adds an entity to be committed.
Ensures the transaction is not marked readonly.
Please see documentation at
:meth:`~google.cloud.datastore.batch.Batch.put`
:type entity: :class:`~google.cloud.datastore.entity.Entity`
:param entity: the entity to be saved.
:raises: :class:`RuntimeError` if the transaction
is marked ReadOnly
"""
if self._options.HasField("read_only"):
raise RuntimeError("Transaction is read only")
else:
super(Transaction, self).put(entity) | python | def put(self, entity):
"""Adds an entity to be committed.
Ensures the transaction is not marked readonly.
Please see documentation at
:meth:`~google.cloud.datastore.batch.Batch.put`
:type entity: :class:`~google.cloud.datastore.entity.Entity`
:param entity: the entity to be saved.
:raises: :class:`RuntimeError` if the transaction
is marked ReadOnly
"""
if self._options.HasField("read_only"):
raise RuntimeError("Transaction is read only")
else:
super(Transaction, self).put(entity) | [
"def",
"put",
"(",
"self",
",",
"entity",
")",
":",
"if",
"self",
".",
"_options",
".",
"HasField",
"(",
"\"read_only\"",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Transaction is read only\"",
")",
"else",
":",
"super",
"(",
"Transaction",
",",
"self",
")",
".",
"put",
"(",
"entity",
")"
] | Adds an entity to be committed.
Ensures the transaction is not marked readonly.
Please see documentation at
:meth:`~google.cloud.datastore.batch.Batch.put`
:type entity: :class:`~google.cloud.datastore.entity.Entity`
:param entity: the entity to be saved.
:raises: :class:`RuntimeError` if the transaction
is marked ReadOnly | [
"Adds",
"an",
"entity",
"to",
"be",
"committed",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/transaction.py#L246-L262 |
28,176 | googleapis/google-cloud-python | securitycenter/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py | SecurityCenterClient.list_findings | def list_findings(
self,
parent,
filter_=None,
order_by=None,
read_time=None,
field_mask=None,
page_size=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Lists an organization or source's findings.
To list across all sources provide a ``-`` as the source id. Example:
/v1beta1/organizations/123/sources/-/findings
Example:
>>> from google.cloud import securitycenter_v1beta1
>>>
>>> client = securitycenter_v1beta1.SecurityCenterClient()
>>>
>>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]')
>>>
>>> # Iterate over all results
>>> for element in client.list_findings(parent):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_findings(parent).pages:
... for element in page:
... # process element
... pass
Args:
parent (str): Name of the source the findings belong to. Its format is
"organizations/[organization\_id]/sources/[source\_id]". To list across
all sources provide a source\_id of ``-``. For example:
organizations/123/sources/-
filter_ (str): Expression that defines the filter to apply across findings. The
expression is a list of one or more restrictions combined via logical
operators ``AND`` and ``OR``. Parentheses are not supported, and ``OR``
has higher precedence than ``AND``.
Restrictions have the form ``<field> <operator> <value>`` and may have a
``-`` character in front of them to indicate negation. Examples include:
- name
- source\_properties.a\_property
- security\_marks.marks.marka
The supported operators are:
- ``=`` for all value types.
- ``>``, ``<``, ``>=``, ``<=`` for integer values.
- ``:``, meaning substring matching, for strings.
The supported value types are:
- string literals in quotes.
- integer literals without quotes.
- boolean literals ``true`` and ``false`` without quotes.
For example, ``source_properties.size = 100`` is a valid filter string.
order_by (str): Expression that defines what fields and order to use for sorting. The
string value should follow SQL syntax: comma separated list of fields.
For example: "name,resource\_properties.a\_property". The default
sorting order is ascending. To specify descending order for a field, a
suffix " desc" should be appended to the field name. For example: "name
desc,source\_properties.a\_property". Redundant space characters in the
syntax are insignificant. "name desc,source\_properties.a\_property" and
" name desc , source\_properties.a\_property " are equivalent.
read_time (Union[dict, ~google.cloud.securitycenter_v1beta1.types.Timestamp]): Time used as a reference point when filtering findings. The filter is
limited to findings existing at the supplied time and their values are
those at that specific time. Absence of this field will default to the
API's version of NOW.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1beta1.types.Timestamp`
field_mask (Union[dict, ~google.cloud.securitycenter_v1beta1.types.FieldMask]): Optional.
A field mask to specify the Finding fields to be listed in the response.
An empty field mask will list all fields.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1beta1.types.FieldMask`
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.securitycenter_v1beta1.types.Finding` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "list_findings" not in self._inner_api_calls:
self._inner_api_calls[
"list_findings"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_findings,
default_retry=self._method_configs["ListFindings"].retry,
default_timeout=self._method_configs["ListFindings"].timeout,
client_info=self._client_info,
)
request = securitycenter_service_pb2.ListFindingsRequest(
parent=parent,
filter=filter_,
order_by=order_by,
read_time=read_time,
field_mask=field_mask,
page_size=page_size,
)
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)
iterator = google.api_core.page_iterator.GRPCIterator(
client=None,
method=functools.partial(
self._inner_api_calls["list_findings"],
retry=retry,
timeout=timeout,
metadata=metadata,
),
request=request,
items_field="findings",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | python | def list_findings(
self,
parent,
filter_=None,
order_by=None,
read_time=None,
field_mask=None,
page_size=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Lists an organization or source's findings.
To list across all sources provide a ``-`` as the source id. Example:
/v1beta1/organizations/123/sources/-/findings
Example:
>>> from google.cloud import securitycenter_v1beta1
>>>
>>> client = securitycenter_v1beta1.SecurityCenterClient()
>>>
>>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]')
>>>
>>> # Iterate over all results
>>> for element in client.list_findings(parent):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_findings(parent).pages:
... for element in page:
... # process element
... pass
Args:
parent (str): Name of the source the findings belong to. Its format is
"organizations/[organization\_id]/sources/[source\_id]". To list across
all sources provide a source\_id of ``-``. For example:
organizations/123/sources/-
filter_ (str): Expression that defines the filter to apply across findings. The
expression is a list of one or more restrictions combined via logical
operators ``AND`` and ``OR``. Parentheses are not supported, and ``OR``
has higher precedence than ``AND``.
Restrictions have the form ``<field> <operator> <value>`` and may have a
``-`` character in front of them to indicate negation. Examples include:
- name
- source\_properties.a\_property
- security\_marks.marks.marka
The supported operators are:
- ``=`` for all value types.
- ``>``, ``<``, ``>=``, ``<=`` for integer values.
- ``:``, meaning substring matching, for strings.
The supported value types are:
- string literals in quotes.
- integer literals without quotes.
- boolean literals ``true`` and ``false`` without quotes.
For example, ``source_properties.size = 100`` is a valid filter string.
order_by (str): Expression that defines what fields and order to use for sorting. The
string value should follow SQL syntax: comma separated list of fields.
For example: "name,resource\_properties.a\_property". The default
sorting order is ascending. To specify descending order for a field, a
suffix " desc" should be appended to the field name. For example: "name
desc,source\_properties.a\_property". Redundant space characters in the
syntax are insignificant. "name desc,source\_properties.a\_property" and
" name desc , source\_properties.a\_property " are equivalent.
read_time (Union[dict, ~google.cloud.securitycenter_v1beta1.types.Timestamp]): Time used as a reference point when filtering findings. The filter is
limited to findings existing at the supplied time and their values are
those at that specific time. Absence of this field will default to the
API's version of NOW.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1beta1.types.Timestamp`
field_mask (Union[dict, ~google.cloud.securitycenter_v1beta1.types.FieldMask]): Optional.
A field mask to specify the Finding fields to be listed in the response.
An empty field mask will list all fields.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1beta1.types.FieldMask`
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.securitycenter_v1beta1.types.Finding` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "list_findings" not in self._inner_api_calls:
self._inner_api_calls[
"list_findings"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_findings,
default_retry=self._method_configs["ListFindings"].retry,
default_timeout=self._method_configs["ListFindings"].timeout,
client_info=self._client_info,
)
request = securitycenter_service_pb2.ListFindingsRequest(
parent=parent,
filter=filter_,
order_by=order_by,
read_time=read_time,
field_mask=field_mask,
page_size=page_size,
)
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)
iterator = google.api_core.page_iterator.GRPCIterator(
client=None,
method=functools.partial(
self._inner_api_calls["list_findings"],
retry=retry,
timeout=timeout,
metadata=metadata,
),
request=request,
items_field="findings",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | [
"def",
"list_findings",
"(",
"self",
",",
"parent",
",",
"filter_",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"read_time",
"=",
"None",
",",
"field_mask",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"list_findings\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"list_findings\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"list_findings",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"ListFindings\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"ListFindings\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"securitycenter_service_pb2",
".",
"ListFindingsRequest",
"(",
"parent",
"=",
"parent",
",",
"filter",
"=",
"filter_",
",",
"order_by",
"=",
"order_by",
",",
"read_time",
"=",
"read_time",
",",
"field_mask",
"=",
"field_mask",
",",
"page_size",
"=",
"page_size",
",",
")",
"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",
")",
"iterator",
"=",
"google",
".",
"api_core",
".",
"page_iterator",
".",
"GRPCIterator",
"(",
"client",
"=",
"None",
",",
"method",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_inner_api_calls",
"[",
"\"list_findings\"",
"]",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
",",
")",
",",
"request",
"=",
"request",
",",
"items_field",
"=",
"\"findings\"",
",",
"request_token_field",
"=",
"\"page_token\"",
",",
"response_token_field",
"=",
"\"next_page_token\"",
",",
")",
"return",
"iterator"
] | Lists an organization or source's findings.
To list across all sources provide a ``-`` as the source id. Example:
/v1beta1/organizations/123/sources/-/findings
Example:
>>> from google.cloud import securitycenter_v1beta1
>>>
>>> client = securitycenter_v1beta1.SecurityCenterClient()
>>>
>>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]')
>>>
>>> # Iterate over all results
>>> for element in client.list_findings(parent):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_findings(parent).pages:
... for element in page:
... # process element
... pass
Args:
parent (str): Name of the source the findings belong to. Its format is
"organizations/[organization\_id]/sources/[source\_id]". To list across
all sources provide a source\_id of ``-``. For example:
organizations/123/sources/-
filter_ (str): Expression that defines the filter to apply across findings. The
expression is a list of one or more restrictions combined via logical
operators ``AND`` and ``OR``. Parentheses are not supported, and ``OR``
has higher precedence than ``AND``.
Restrictions have the form ``<field> <operator> <value>`` and may have a
``-`` character in front of them to indicate negation. Examples include:
- name
- source\_properties.a\_property
- security\_marks.marks.marka
The supported operators are:
- ``=`` for all value types.
- ``>``, ``<``, ``>=``, ``<=`` for integer values.
- ``:``, meaning substring matching, for strings.
The supported value types are:
- string literals in quotes.
- integer literals without quotes.
- boolean literals ``true`` and ``false`` without quotes.
For example, ``source_properties.size = 100`` is a valid filter string.
order_by (str): Expression that defines what fields and order to use for sorting. The
string value should follow SQL syntax: comma separated list of fields.
For example: "name,resource\_properties.a\_property". The default
sorting order is ascending. To specify descending order for a field, a
suffix " desc" should be appended to the field name. For example: "name
desc,source\_properties.a\_property". Redundant space characters in the
syntax are insignificant. "name desc,source\_properties.a\_property" and
" name desc , source\_properties.a\_property " are equivalent.
read_time (Union[dict, ~google.cloud.securitycenter_v1beta1.types.Timestamp]): Time used as a reference point when filtering findings. The filter is
limited to findings existing at the supplied time and their values are
those at that specific time. Absence of this field will default to the
API's version of NOW.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1beta1.types.Timestamp`
field_mask (Union[dict, ~google.cloud.securitycenter_v1beta1.types.FieldMask]): Optional.
A field mask to specify the Finding fields to be listed in the response.
An empty field mask will list all fields.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.securitycenter_v1beta1.types.FieldMask`
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.securitycenter_v1beta1.types.Finding` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Lists",
"an",
"organization",
"or",
"source",
"s",
"findings",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/securitycenter/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py#L1157-L1320 |
28,177 | googleapis/google-cloud-python | trace/google/cloud/trace/_gapic.py | _dict_mapping_to_pb | def _dict_mapping_to_pb(mapping, proto_type):
"""
Convert a dict to protobuf.
Args:
mapping (dict): A dict that needs to be converted to protobuf.
proto_type (str): The type of the Protobuf.
Returns:
An instance of the specified protobuf.
"""
converted_pb = getattr(trace_pb2, proto_type)()
ParseDict(mapping, converted_pb)
return converted_pb | python | def _dict_mapping_to_pb(mapping, proto_type):
"""
Convert a dict to protobuf.
Args:
mapping (dict): A dict that needs to be converted to protobuf.
proto_type (str): The type of the Protobuf.
Returns:
An instance of the specified protobuf.
"""
converted_pb = getattr(trace_pb2, proto_type)()
ParseDict(mapping, converted_pb)
return converted_pb | [
"def",
"_dict_mapping_to_pb",
"(",
"mapping",
",",
"proto_type",
")",
":",
"converted_pb",
"=",
"getattr",
"(",
"trace_pb2",
",",
"proto_type",
")",
"(",
")",
"ParseDict",
"(",
"mapping",
",",
"converted_pb",
")",
"return",
"converted_pb"
] | Convert a dict to protobuf.
Args:
mapping (dict): A dict that needs to be converted to protobuf.
proto_type (str): The type of the Protobuf.
Returns:
An instance of the specified protobuf. | [
"Convert",
"a",
"dict",
"to",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/trace/google/cloud/trace/_gapic.py#L245-L258 |
28,178 | googleapis/google-cloud-python | trace/google/cloud/trace/_gapic.py | _span_attrs_to_pb | def _span_attrs_to_pb(span_attr, proto_type):
"""
Convert a span attribute dict to protobuf, including Links, Attributes,
TimeEvents.
Args:
span_attr (dict): A dict that needs to be converted to protobuf.
proto_type (str): The type of the Protobuf.
Returns:
An instance of the specified protobuf.
"""
attr_pb = getattr(trace_pb2.Span, proto_type)()
ParseDict(span_attr, attr_pb)
return attr_pb | python | def _span_attrs_to_pb(span_attr, proto_type):
"""
Convert a span attribute dict to protobuf, including Links, Attributes,
TimeEvents.
Args:
span_attr (dict): A dict that needs to be converted to protobuf.
proto_type (str): The type of the Protobuf.
Returns:
An instance of the specified protobuf.
"""
attr_pb = getattr(trace_pb2.Span, proto_type)()
ParseDict(span_attr, attr_pb)
return attr_pb | [
"def",
"_span_attrs_to_pb",
"(",
"span_attr",
",",
"proto_type",
")",
":",
"attr_pb",
"=",
"getattr",
"(",
"trace_pb2",
".",
"Span",
",",
"proto_type",
")",
"(",
")",
"ParseDict",
"(",
"span_attr",
",",
"attr_pb",
")",
"return",
"attr_pb"
] | Convert a span attribute dict to protobuf, including Links, Attributes,
TimeEvents.
Args:
span_attr (dict): A dict that needs to be converted to protobuf.
proto_type (str): The type of the Protobuf.
Returns:
An instance of the specified protobuf. | [
"Convert",
"a",
"span",
"attribute",
"dict",
"to",
"protobuf",
"including",
"Links",
"Attributes",
"TimeEvents",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/trace/google/cloud/trace/_gapic.py#L261-L275 |
28,179 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/cluster.py | Cluster.from_pb | def from_pb(cls, cluster_pb, instance):
"""Creates an cluster instance from a protobuf.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_cluster_from_pb]
:end-before: [END bigtable_cluster_from_pb]
:type cluster_pb: :class:`instance_pb2.Cluster`
:param cluster_pb: An instance protobuf object.
:type instance: :class:`google.cloud.bigtable.instance.Instance`
:param instance: The instance that owns the cluster.
:rtype: :class:`Cluster`
:returns: The Cluster parsed from the protobuf response.
:raises: :class:`ValueError <exceptions.ValueError>` if the cluster
name does not match
``projects/{project}/instances/{instance_id}/clusters/{cluster_id}``
or if the parsed instance ID does not match the istance ID
on the client.
or if the parsed project ID does not match the project ID
on the client.
"""
match_cluster_name = _CLUSTER_NAME_RE.match(cluster_pb.name)
if match_cluster_name is None:
raise ValueError(
"Cluster protobuf name was not in the " "expected format.",
cluster_pb.name,
)
if match_cluster_name.group("instance") != instance.instance_id:
raise ValueError(
"Instance ID on cluster does not match the " "instance ID on the client"
)
if match_cluster_name.group("project") != instance._client.project:
raise ValueError(
"Project ID on cluster does not match the " "project ID on the client"
)
cluster_id = match_cluster_name.group("cluster_id")
result = cls(cluster_id, instance)
result._update_from_pb(cluster_pb)
return result | python | def from_pb(cls, cluster_pb, instance):
"""Creates an cluster instance from a protobuf.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_cluster_from_pb]
:end-before: [END bigtable_cluster_from_pb]
:type cluster_pb: :class:`instance_pb2.Cluster`
:param cluster_pb: An instance protobuf object.
:type instance: :class:`google.cloud.bigtable.instance.Instance`
:param instance: The instance that owns the cluster.
:rtype: :class:`Cluster`
:returns: The Cluster parsed from the protobuf response.
:raises: :class:`ValueError <exceptions.ValueError>` if the cluster
name does not match
``projects/{project}/instances/{instance_id}/clusters/{cluster_id}``
or if the parsed instance ID does not match the istance ID
on the client.
or if the parsed project ID does not match the project ID
on the client.
"""
match_cluster_name = _CLUSTER_NAME_RE.match(cluster_pb.name)
if match_cluster_name is None:
raise ValueError(
"Cluster protobuf name was not in the " "expected format.",
cluster_pb.name,
)
if match_cluster_name.group("instance") != instance.instance_id:
raise ValueError(
"Instance ID on cluster does not match the " "instance ID on the client"
)
if match_cluster_name.group("project") != instance._client.project:
raise ValueError(
"Project ID on cluster does not match the " "project ID on the client"
)
cluster_id = match_cluster_name.group("cluster_id")
result = cls(cluster_id, instance)
result._update_from_pb(cluster_pb)
return result | [
"def",
"from_pb",
"(",
"cls",
",",
"cluster_pb",
",",
"instance",
")",
":",
"match_cluster_name",
"=",
"_CLUSTER_NAME_RE",
".",
"match",
"(",
"cluster_pb",
".",
"name",
")",
"if",
"match_cluster_name",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cluster protobuf name was not in the \"",
"\"expected format.\"",
",",
"cluster_pb",
".",
"name",
",",
")",
"if",
"match_cluster_name",
".",
"group",
"(",
"\"instance\"",
")",
"!=",
"instance",
".",
"instance_id",
":",
"raise",
"ValueError",
"(",
"\"Instance ID on cluster does not match the \"",
"\"instance ID on the client\"",
")",
"if",
"match_cluster_name",
".",
"group",
"(",
"\"project\"",
")",
"!=",
"instance",
".",
"_client",
".",
"project",
":",
"raise",
"ValueError",
"(",
"\"Project ID on cluster does not match the \"",
"\"project ID on the client\"",
")",
"cluster_id",
"=",
"match_cluster_name",
".",
"group",
"(",
"\"cluster_id\"",
")",
"result",
"=",
"cls",
"(",
"cluster_id",
",",
"instance",
")",
"result",
".",
"_update_from_pb",
"(",
"cluster_pb",
")",
"return",
"result"
] | Creates an cluster instance from a protobuf.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_cluster_from_pb]
:end-before: [END bigtable_cluster_from_pb]
:type cluster_pb: :class:`instance_pb2.Cluster`
:param cluster_pb: An instance protobuf object.
:type instance: :class:`google.cloud.bigtable.instance.Instance`
:param instance: The instance that owns the cluster.
:rtype: :class:`Cluster`
:returns: The Cluster parsed from the protobuf response.
:raises: :class:`ValueError <exceptions.ValueError>` if the cluster
name does not match
``projects/{project}/instances/{instance_id}/clusters/{cluster_id}``
or if the parsed instance ID does not match the istance ID
on the client.
or if the parsed project ID does not match the project ID
on the client. | [
"Creates",
"an",
"cluster",
"instance",
"from",
"a",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/cluster.py#L94-L137 |
28,180 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/cluster.py | Cluster.name | def name(self):
"""Cluster name used in requests.
.. note::
This property will not change if ``_instance`` and ``cluster_id``
do not, but the return value is not cached.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_cluster_name]
:end-before: [END bigtable_cluster_name]
The cluster name is of the form
``"projects/{project}/instances/{instance}/clusters/{cluster_id}"``
:rtype: str
:returns: The cluster name.
"""
return self._instance._client.instance_admin_client.cluster_path(
self._instance._client.project, self._instance.instance_id, self.cluster_id
) | python | def name(self):
"""Cluster name used in requests.
.. note::
This property will not change if ``_instance`` and ``cluster_id``
do not, but the return value is not cached.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_cluster_name]
:end-before: [END bigtable_cluster_name]
The cluster name is of the form
``"projects/{project}/instances/{instance}/clusters/{cluster_id}"``
:rtype: str
:returns: The cluster name.
"""
return self._instance._client.instance_admin_client.cluster_path(
self._instance._client.project, self._instance.instance_id, self.cluster_id
) | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_instance",
".",
"_client",
".",
"instance_admin_client",
".",
"cluster_path",
"(",
"self",
".",
"_instance",
".",
"_client",
".",
"project",
",",
"self",
".",
"_instance",
".",
"instance_id",
",",
"self",
".",
"cluster_id",
")"
] | Cluster name used in requests.
.. note::
This property will not change if ``_instance`` and ``cluster_id``
do not, but the return value is not cached.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_cluster_name]
:end-before: [END bigtable_cluster_name]
The cluster name is of the form
``"projects/{project}/instances/{instance}/clusters/{cluster_id}"``
:rtype: str
:returns: The cluster name. | [
"Cluster",
"name",
"used",
"in",
"requests",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/cluster.py#L150-L172 |
28,181 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/cluster.py | Cluster.reload | def reload(self):
"""Reload the metadata for this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_reload_cluster]
:end-before: [END bigtable_reload_cluster]
"""
cluster_pb = self._instance._client.instance_admin_client.get_cluster(self.name)
# NOTE: _update_from_pb does not check that the project and
# cluster ID on the response match the request.
self._update_from_pb(cluster_pb) | python | def reload(self):
"""Reload the metadata for this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_reload_cluster]
:end-before: [END bigtable_reload_cluster]
"""
cluster_pb = self._instance._client.instance_admin_client.get_cluster(self.name)
# NOTE: _update_from_pb does not check that the project and
# cluster ID on the response match the request.
self._update_from_pb(cluster_pb) | [
"def",
"reload",
"(",
"self",
")",
":",
"cluster_pb",
"=",
"self",
".",
"_instance",
".",
"_client",
".",
"instance_admin_client",
".",
"get_cluster",
"(",
"self",
".",
"name",
")",
"# NOTE: _update_from_pb does not check that the project and",
"# cluster ID on the response match the request.",
"self",
".",
"_update_from_pb",
"(",
"cluster_pb",
")"
] | Reload the metadata for this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_reload_cluster]
:end-before: [END bigtable_reload_cluster] | [
"Reload",
"the",
"metadata",
"for",
"this",
"cluster",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/cluster.py#L201-L214 |
28,182 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/cluster.py | Cluster.exists | def exists(self):
"""Check whether the cluster already exists.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_check_cluster_exists]
:end-before: [END bigtable_check_cluster_exists]
:rtype: bool
:returns: True if the table exists, else False.
"""
client = self._instance._client
try:
client.instance_admin_client.get_cluster(name=self.name)
return True
# NOTE: There could be other exceptions that are returned to the user.
except NotFound:
return False | python | def exists(self):
"""Check whether the cluster already exists.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_check_cluster_exists]
:end-before: [END bigtable_check_cluster_exists]
:rtype: bool
:returns: True if the table exists, else False.
"""
client = self._instance._client
try:
client.instance_admin_client.get_cluster(name=self.name)
return True
# NOTE: There could be other exceptions that are returned to the user.
except NotFound:
return False | [
"def",
"exists",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"_instance",
".",
"_client",
"try",
":",
"client",
".",
"instance_admin_client",
".",
"get_cluster",
"(",
"name",
"=",
"self",
".",
"name",
")",
"return",
"True",
"# NOTE: There could be other exceptions that are returned to the user.",
"except",
"NotFound",
":",
"return",
"False"
] | Check whether the cluster already exists.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_check_cluster_exists]
:end-before: [END bigtable_check_cluster_exists]
:rtype: bool
:returns: True if the table exists, else False. | [
"Check",
"whether",
"the",
"cluster",
"already",
"exists",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/cluster.py#L216-L234 |
28,183 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/cluster.py | Cluster.create | def create(self):
"""Create this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_create_cluster]
:end-before: [END bigtable_create_cluster]
.. note::
Uses the ``project``, ``instance`` and ``cluster_id`` on the
current :class:`Cluster` in addition to the ``serve_nodes``.
To change them before creating, reset the values via
.. code:: python
cluster.serve_nodes = 8
cluster.cluster_id = 'i-changed-my-mind'
before calling :meth:`create`.
:rtype: :class:`~google.api_core.operation.Operation`
:returns: The long-running operation corresponding to the
create operation.
"""
client = self._instance._client
cluster_pb = self._to_pb()
return client.instance_admin_client.create_cluster(
self._instance.name, self.cluster_id, cluster_pb
) | python | def create(self):
"""Create this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_create_cluster]
:end-before: [END bigtable_create_cluster]
.. note::
Uses the ``project``, ``instance`` and ``cluster_id`` on the
current :class:`Cluster` in addition to the ``serve_nodes``.
To change them before creating, reset the values via
.. code:: python
cluster.serve_nodes = 8
cluster.cluster_id = 'i-changed-my-mind'
before calling :meth:`create`.
:rtype: :class:`~google.api_core.operation.Operation`
:returns: The long-running operation corresponding to the
create operation.
"""
client = self._instance._client
cluster_pb = self._to_pb()
return client.instance_admin_client.create_cluster(
self._instance.name, self.cluster_id, cluster_pb
) | [
"def",
"create",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"_instance",
".",
"_client",
"cluster_pb",
"=",
"self",
".",
"_to_pb",
"(",
")",
"return",
"client",
".",
"instance_admin_client",
".",
"create_cluster",
"(",
"self",
".",
"_instance",
".",
"name",
",",
"self",
".",
"cluster_id",
",",
"cluster_pb",
")"
] | Create this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_create_cluster]
:end-before: [END bigtable_create_cluster]
.. note::
Uses the ``project``, ``instance`` and ``cluster_id`` on the
current :class:`Cluster` in addition to the ``serve_nodes``.
To change them before creating, reset the values via
.. code:: python
cluster.serve_nodes = 8
cluster.cluster_id = 'i-changed-my-mind'
before calling :meth:`create`.
:rtype: :class:`~google.api_core.operation.Operation`
:returns: The long-running operation corresponding to the
create operation. | [
"Create",
"this",
"cluster",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/cluster.py#L236-L267 |
28,184 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/cluster.py | Cluster.update | def update(self):
"""Update this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_update_cluster]
:end-before: [END bigtable_update_cluster]
.. note::
Updates the ``serve_nodes``. If you'd like to
change them before updating, reset the values via
.. code:: python
cluster.serve_nodes = 8
before calling :meth:`update`.
:type location: :str:``CreationOnly``
:param location: The location where this cluster's nodes and storage
reside. For best performance, clients should be located as
close as possible to this cluster. Currently only zones are
supported, so values should be of the form
``projects/<project>/locations/<zone>``.
:type serve_nodes: :int
:param serve_nodes: The number of nodes allocated to this cluster.
More nodes enable higher throughput and more consistent
performance.
:rtype: :class:`Operation`
:returns: The long-running operation corresponding to the
update operation.
"""
client = self._instance._client
# We are passing `None` for second argument location.
# Location is set only at the time of creation of a cluster
# and can not be changed after cluster has been created.
return client.instance_admin_client.update_cluster(
self.name, self.serve_nodes, None
) | python | def update(self):
"""Update this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_update_cluster]
:end-before: [END bigtable_update_cluster]
.. note::
Updates the ``serve_nodes``. If you'd like to
change them before updating, reset the values via
.. code:: python
cluster.serve_nodes = 8
before calling :meth:`update`.
:type location: :str:``CreationOnly``
:param location: The location where this cluster's nodes and storage
reside. For best performance, clients should be located as
close as possible to this cluster. Currently only zones are
supported, so values should be of the form
``projects/<project>/locations/<zone>``.
:type serve_nodes: :int
:param serve_nodes: The number of nodes allocated to this cluster.
More nodes enable higher throughput and more consistent
performance.
:rtype: :class:`Operation`
:returns: The long-running operation corresponding to the
update operation.
"""
client = self._instance._client
# We are passing `None` for second argument location.
# Location is set only at the time of creation of a cluster
# and can not be changed after cluster has been created.
return client.instance_admin_client.update_cluster(
self.name, self.serve_nodes, None
) | [
"def",
"update",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"_instance",
".",
"_client",
"# We are passing `None` for second argument location.",
"# Location is set only at the time of creation of a cluster",
"# and can not be changed after cluster has been created.",
"return",
"client",
".",
"instance_admin_client",
".",
"update_cluster",
"(",
"self",
".",
"name",
",",
"self",
".",
"serve_nodes",
",",
"None",
")"
] | Update this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_update_cluster]
:end-before: [END bigtable_update_cluster]
.. note::
Updates the ``serve_nodes``. If you'd like to
change them before updating, reset the values via
.. code:: python
cluster.serve_nodes = 8
before calling :meth:`update`.
:type location: :str:``CreationOnly``
:param location: The location where this cluster's nodes and storage
reside. For best performance, clients should be located as
close as possible to this cluster. Currently only zones are
supported, so values should be of the form
``projects/<project>/locations/<zone>``.
:type serve_nodes: :int
:param serve_nodes: The number of nodes allocated to this cluster.
More nodes enable higher throughput and more consistent
performance.
:rtype: :class:`Operation`
:returns: The long-running operation corresponding to the
update operation. | [
"Update",
"this",
"cluster",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/cluster.py#L269-L311 |
28,185 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/cluster.py | Cluster.delete | def delete(self):
"""Delete this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_delete_cluster]
:end-before: [END bigtable_delete_cluster]
Marks a cluster and all of its tables for permanent deletion in 7 days.
Immediately upon completion of the request:
* Billing will cease for all of the cluster's reserved resources.
* The cluster's ``delete_time`` field will be set 7 days in the future.
Soon afterward:
* All tables within the cluster will become unavailable.
At the cluster's ``delete_time``:
* The cluster and **all of its tables** will immediately and
irrevocably disappear from the API, and their data will be
permanently deleted.
"""
client = self._instance._client
client.instance_admin_client.delete_cluster(self.name) | python | def delete(self):
"""Delete this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_delete_cluster]
:end-before: [END bigtable_delete_cluster]
Marks a cluster and all of its tables for permanent deletion in 7 days.
Immediately upon completion of the request:
* Billing will cease for all of the cluster's reserved resources.
* The cluster's ``delete_time`` field will be set 7 days in the future.
Soon afterward:
* All tables within the cluster will become unavailable.
At the cluster's ``delete_time``:
* The cluster and **all of its tables** will immediately and
irrevocably disappear from the API, and their data will be
permanently deleted.
"""
client = self._instance._client
client.instance_admin_client.delete_cluster(self.name) | [
"def",
"delete",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"_instance",
".",
"_client",
"client",
".",
"instance_admin_client",
".",
"delete_cluster",
"(",
"self",
".",
"name",
")"
] | Delete this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_delete_cluster]
:end-before: [END bigtable_delete_cluster]
Marks a cluster and all of its tables for permanent deletion in 7 days.
Immediately upon completion of the request:
* Billing will cease for all of the cluster's reserved resources.
* The cluster's ``delete_time`` field will be set 7 days in the future.
Soon afterward:
* All tables within the cluster will become unavailable.
At the cluster's ``delete_time``:
* The cluster and **all of its tables** will immediately and
irrevocably disappear from the API, and their data will be
permanently deleted. | [
"Delete",
"this",
"cluster",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/cluster.py#L313-L340 |
28,186 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/cluster.py | Cluster._to_pb | def _to_pb(self):
""" Create cluster proto buff message for API calls """
client = self._instance._client
location = client.instance_admin_client.location_path(
client.project, self.location_id
)
cluster_pb = instance_pb2.Cluster(
location=location,
serve_nodes=self.serve_nodes,
default_storage_type=self.default_storage_type,
)
return cluster_pb | python | def _to_pb(self):
""" Create cluster proto buff message for API calls """
client = self._instance._client
location = client.instance_admin_client.location_path(
client.project, self.location_id
)
cluster_pb = instance_pb2.Cluster(
location=location,
serve_nodes=self.serve_nodes,
default_storage_type=self.default_storage_type,
)
return cluster_pb | [
"def",
"_to_pb",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"_instance",
".",
"_client",
"location",
"=",
"client",
".",
"instance_admin_client",
".",
"location_path",
"(",
"client",
".",
"project",
",",
"self",
".",
"location_id",
")",
"cluster_pb",
"=",
"instance_pb2",
".",
"Cluster",
"(",
"location",
"=",
"location",
",",
"serve_nodes",
"=",
"self",
".",
"serve_nodes",
",",
"default_storage_type",
"=",
"self",
".",
"default_storage_type",
",",
")",
"return",
"cluster_pb"
] | Create cluster proto buff message for API calls | [
"Create",
"cluster",
"proto",
"buff",
"message",
"for",
"API",
"calls"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/cluster.py#L342-L353 |
28,187 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row_data.py | Cell.from_pb | def from_pb(cls, cell_pb):
"""Create a new cell from a Cell protobuf.
:type cell_pb: :class:`._generated.data_pb2.Cell`
:param cell_pb: The protobuf to convert.
:rtype: :class:`Cell`
:returns: The cell corresponding to the protobuf.
"""
if cell_pb.labels:
return cls(cell_pb.value, cell_pb.timestamp_micros, labels=cell_pb.labels)
else:
return cls(cell_pb.value, cell_pb.timestamp_micros) | python | def from_pb(cls, cell_pb):
"""Create a new cell from a Cell protobuf.
:type cell_pb: :class:`._generated.data_pb2.Cell`
:param cell_pb: The protobuf to convert.
:rtype: :class:`Cell`
:returns: The cell corresponding to the protobuf.
"""
if cell_pb.labels:
return cls(cell_pb.value, cell_pb.timestamp_micros, labels=cell_pb.labels)
else:
return cls(cell_pb.value, cell_pb.timestamp_micros) | [
"def",
"from_pb",
"(",
"cls",
",",
"cell_pb",
")",
":",
"if",
"cell_pb",
".",
"labels",
":",
"return",
"cls",
"(",
"cell_pb",
".",
"value",
",",
"cell_pb",
".",
"timestamp_micros",
",",
"labels",
"=",
"cell_pb",
".",
"labels",
")",
"else",
":",
"return",
"cls",
"(",
"cell_pb",
".",
"value",
",",
"cell_pb",
".",
"timestamp_micros",
")"
] | Create a new cell from a Cell protobuf.
:type cell_pb: :class:`._generated.data_pb2.Cell`
:param cell_pb: The protobuf to convert.
:rtype: :class:`Cell`
:returns: The cell corresponding to the protobuf. | [
"Create",
"a",
"new",
"cell",
"from",
"a",
"Cell",
"protobuf",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row_data.py#L59-L71 |
28,188 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row_data.py | PartialRowData.to_dict | def to_dict(self):
"""Convert the cells to a dictionary.
This is intended to be used with HappyBase, so the column family and
column qualiers are combined (with ``:``).
:rtype: dict
:returns: Dictionary containing all the data in the cells of this row.
"""
result = {}
for column_family_id, columns in six.iteritems(self._cells):
for column_qual, cells in six.iteritems(columns):
key = _to_bytes(column_family_id) + b":" + _to_bytes(column_qual)
result[key] = cells
return result | python | def to_dict(self):
"""Convert the cells to a dictionary.
This is intended to be used with HappyBase, so the column family and
column qualiers are combined (with ``:``).
:rtype: dict
:returns: Dictionary containing all the data in the cells of this row.
"""
result = {}
for column_family_id, columns in six.iteritems(self._cells):
for column_qual, cells in six.iteritems(columns):
key = _to_bytes(column_family_id) + b":" + _to_bytes(column_qual)
result[key] = cells
return result | [
"def",
"to_dict",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"column_family_id",
",",
"columns",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_cells",
")",
":",
"for",
"column_qual",
",",
"cells",
"in",
"six",
".",
"iteritems",
"(",
"columns",
")",
":",
"key",
"=",
"_to_bytes",
"(",
"column_family_id",
")",
"+",
"b\":\"",
"+",
"_to_bytes",
"(",
"column_qual",
")",
"result",
"[",
"key",
"]",
"=",
"cells",
"return",
"result"
] | Convert the cells to a dictionary.
This is intended to be used with HappyBase, so the column family and
column qualiers are combined (with ``:``).
:rtype: dict
:returns: Dictionary containing all the data in the cells of this row. | [
"Convert",
"the",
"cells",
"to",
"a",
"dictionary",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row_data.py#L157-L171 |
28,189 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row_data.py | PartialRowData.cell_value | def cell_value(self, column_family_id, column, index=0):
"""Get a single cell value stored on this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_cell_value]
:end-before: [END bigtable_row_cell_value]
Args:
column_family_id (str): The ID of the column family. Must be of the
form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
column (bytes): The column within the column family where the cell
is located.
index (Optional[int]): The offset within the series of values. If
not specified, will return the first cell.
Returns:
~google.cloud.bigtable.row_data.Cell value: The cell value stored
in the specified column and specified index.
Raises:
KeyError: If ``column_family_id`` is not among the cells stored
in this row.
KeyError: If ``column`` is not among the cells stored in this row
for the given ``column_family_id``.
IndexError: If ``index`` cannot be found within the cells stored
in this row for the given ``column_family_id``, ``column``
pair.
"""
cells = self.find_cells(column_family_id, column)
try:
cell = cells[index]
except (TypeError, IndexError):
num_cells = len(cells)
msg = _MISSING_INDEX.format(index, column, column_family_id, num_cells)
raise IndexError(msg)
return cell.value | python | def cell_value(self, column_family_id, column, index=0):
"""Get a single cell value stored on this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_cell_value]
:end-before: [END bigtable_row_cell_value]
Args:
column_family_id (str): The ID of the column family. Must be of the
form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
column (bytes): The column within the column family where the cell
is located.
index (Optional[int]): The offset within the series of values. If
not specified, will return the first cell.
Returns:
~google.cloud.bigtable.row_data.Cell value: The cell value stored
in the specified column and specified index.
Raises:
KeyError: If ``column_family_id`` is not among the cells stored
in this row.
KeyError: If ``column`` is not among the cells stored in this row
for the given ``column_family_id``.
IndexError: If ``index`` cannot be found within the cells stored
in this row for the given ``column_family_id``, ``column``
pair.
"""
cells = self.find_cells(column_family_id, column)
try:
cell = cells[index]
except (TypeError, IndexError):
num_cells = len(cells)
msg = _MISSING_INDEX.format(index, column, column_family_id, num_cells)
raise IndexError(msg)
return cell.value | [
"def",
"cell_value",
"(",
"self",
",",
"column_family_id",
",",
"column",
",",
"index",
"=",
"0",
")",
":",
"cells",
"=",
"self",
".",
"find_cells",
"(",
"column_family_id",
",",
"column",
")",
"try",
":",
"cell",
"=",
"cells",
"[",
"index",
"]",
"except",
"(",
"TypeError",
",",
"IndexError",
")",
":",
"num_cells",
"=",
"len",
"(",
"cells",
")",
"msg",
"=",
"_MISSING_INDEX",
".",
"format",
"(",
"index",
",",
"column",
",",
"column_family_id",
",",
"num_cells",
")",
"raise",
"IndexError",
"(",
"msg",
")",
"return",
"cell",
".",
"value"
] | Get a single cell value stored on this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_cell_value]
:end-before: [END bigtable_row_cell_value]
Args:
column_family_id (str): The ID of the column family. Must be of the
form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.
column (bytes): The column within the column family where the cell
is located.
index (Optional[int]): The offset within the series of values. If
not specified, will return the first cell.
Returns:
~google.cloud.bigtable.row_data.Cell value: The cell value stored
in the specified column and specified index.
Raises:
KeyError: If ``column_family_id`` is not among the cells stored
in this row.
KeyError: If ``column`` is not among the cells stored in this row
for the given ``column_family_id``.
IndexError: If ``index`` cannot be found within the cells stored
in this row for the given ``column_family_id``, ``column``
pair. | [
"Get",
"a",
"single",
"cell",
"value",
"stored",
"on",
"this",
"instance",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row_data.py#L237-L276 |
28,190 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row_data.py | PartialRowsData.consume_all | def consume_all(self, max_loops=None):
"""Consume the streamed responses until there are no more.
.. warning::
This method will be removed in future releases. Please use this
class as a generator instead.
:type max_loops: int
:param max_loops: (Optional) Maximum number of times to try to consume
an additional ``ReadRowsResponse``. You can use this
to avoid long wait times.
"""
for row in self:
self.rows[row.row_key] = row | python | def consume_all(self, max_loops=None):
"""Consume the streamed responses until there are no more.
.. warning::
This method will be removed in future releases. Please use this
class as a generator instead.
:type max_loops: int
:param max_loops: (Optional) Maximum number of times to try to consume
an additional ``ReadRowsResponse``. You can use this
to avoid long wait times.
"""
for row in self:
self.rows[row.row_key] = row | [
"def",
"consume_all",
"(",
"self",
",",
"max_loops",
"=",
"None",
")",
":",
"for",
"row",
"in",
"self",
":",
"self",
".",
"rows",
"[",
"row",
".",
"row_key",
"]",
"=",
"row"
] | Consume the streamed responses until there are no more.
.. warning::
This method will be removed in future releases. Please use this
class as a generator instead.
:type max_loops: int
:param max_loops: (Optional) Maximum number of times to try to consume
an additional ``ReadRowsResponse``. You can use this
to avoid long wait times. | [
"Consume",
"the",
"streamed",
"responses",
"until",
"there",
"are",
"no",
"more",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row_data.py#L417-L430 |
28,191 | googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row_data.py | _ReadRowsRequestManager.build_updated_request | def build_updated_request(self):
""" Updates the given message request as per last scanned key
"""
r_kwargs = {
"table_name": self.message.table_name,
"filter": self.message.filter,
}
if self.message.rows_limit != 0:
r_kwargs["rows_limit"] = max(
1, self.message.rows_limit - self.rows_read_so_far
)
# if neither RowSet.row_keys nor RowSet.row_ranges currently exist,
# add row_range that starts with last_scanned_key as start_key_open
# to request only rows that have not been returned yet
if not self.message.HasField("rows"):
row_range = data_v2_pb2.RowRange(start_key_open=self.last_scanned_key)
r_kwargs["rows"] = data_v2_pb2.RowSet(row_ranges=[row_range])
else:
row_keys = self._filter_rows_keys()
row_ranges = self._filter_row_ranges()
r_kwargs["rows"] = data_v2_pb2.RowSet(
row_keys=row_keys, row_ranges=row_ranges
)
return data_messages_v2_pb2.ReadRowsRequest(**r_kwargs) | python | def build_updated_request(self):
""" Updates the given message request as per last scanned key
"""
r_kwargs = {
"table_name": self.message.table_name,
"filter": self.message.filter,
}
if self.message.rows_limit != 0:
r_kwargs["rows_limit"] = max(
1, self.message.rows_limit - self.rows_read_so_far
)
# if neither RowSet.row_keys nor RowSet.row_ranges currently exist,
# add row_range that starts with last_scanned_key as start_key_open
# to request only rows that have not been returned yet
if not self.message.HasField("rows"):
row_range = data_v2_pb2.RowRange(start_key_open=self.last_scanned_key)
r_kwargs["rows"] = data_v2_pb2.RowSet(row_ranges=[row_range])
else:
row_keys = self._filter_rows_keys()
row_ranges = self._filter_row_ranges()
r_kwargs["rows"] = data_v2_pb2.RowSet(
row_keys=row_keys, row_ranges=row_ranges
)
return data_messages_v2_pb2.ReadRowsRequest(**r_kwargs) | [
"def",
"build_updated_request",
"(",
"self",
")",
":",
"r_kwargs",
"=",
"{",
"\"table_name\"",
":",
"self",
".",
"message",
".",
"table_name",
",",
"\"filter\"",
":",
"self",
".",
"message",
".",
"filter",
",",
"}",
"if",
"self",
".",
"message",
".",
"rows_limit",
"!=",
"0",
":",
"r_kwargs",
"[",
"\"rows_limit\"",
"]",
"=",
"max",
"(",
"1",
",",
"self",
".",
"message",
".",
"rows_limit",
"-",
"self",
".",
"rows_read_so_far",
")",
"# if neither RowSet.row_keys nor RowSet.row_ranges currently exist,",
"# add row_range that starts with last_scanned_key as start_key_open",
"# to request only rows that have not been returned yet",
"if",
"not",
"self",
".",
"message",
".",
"HasField",
"(",
"\"rows\"",
")",
":",
"row_range",
"=",
"data_v2_pb2",
".",
"RowRange",
"(",
"start_key_open",
"=",
"self",
".",
"last_scanned_key",
")",
"r_kwargs",
"[",
"\"rows\"",
"]",
"=",
"data_v2_pb2",
".",
"RowSet",
"(",
"row_ranges",
"=",
"[",
"row_range",
"]",
")",
"else",
":",
"row_keys",
"=",
"self",
".",
"_filter_rows_keys",
"(",
")",
"row_ranges",
"=",
"self",
".",
"_filter_row_ranges",
"(",
")",
"r_kwargs",
"[",
"\"rows\"",
"]",
"=",
"data_v2_pb2",
".",
"RowSet",
"(",
"row_keys",
"=",
"row_keys",
",",
"row_ranges",
"=",
"row_ranges",
")",
"return",
"data_messages_v2_pb2",
".",
"ReadRowsRequest",
"(",
"*",
"*",
"r_kwargs",
")"
] | Updates the given message request as per last scanned key | [
"Updates",
"the",
"given",
"message",
"request",
"as",
"per",
"last",
"scanned",
"key"
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row_data.py#L604-L629 |
28,192 | googleapis/google-cloud-python | trace/google/cloud/trace_v1/gapic/trace_service_client.py | TraceServiceClient.patch_traces | def patch_traces(
self,
project_id,
traces,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Sends new traces to Stackdriver Trace or updates existing traces. If the ID
of a trace that you send matches that of an existing trace, any fields
in the existing trace and its spans are overwritten by the provided values,
and any new fields provided are merged with the existing trace data. If the
ID does not match, a new trace is created.
Example:
>>> from google.cloud import trace_v1
>>>
>>> client = trace_v1.TraceServiceClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> project_id = ''
>>>
>>> # TODO: Initialize `traces`:
>>> traces = {}
>>>
>>> client.patch_traces(project_id, traces)
Args:
project_id (str): ID of the Cloud project where the trace data is stored.
traces (Union[dict, ~google.cloud.trace_v1.types.Traces]): The body of the message.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v1.types.Traces`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "patch_traces" not in self._inner_api_calls:
self._inner_api_calls[
"patch_traces"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.patch_traces,
default_retry=self._method_configs["PatchTraces"].retry,
default_timeout=self._method_configs["PatchTraces"].timeout,
client_info=self._client_info,
)
request = trace_pb2.PatchTracesRequest(project_id=project_id, traces=traces)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("project_id", project_id)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
self._inner_api_calls["patch_traces"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def patch_traces(
self,
project_id,
traces,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Sends new traces to Stackdriver Trace or updates existing traces. If the ID
of a trace that you send matches that of an existing trace, any fields
in the existing trace and its spans are overwritten by the provided values,
and any new fields provided are merged with the existing trace data. If the
ID does not match, a new trace is created.
Example:
>>> from google.cloud import trace_v1
>>>
>>> client = trace_v1.TraceServiceClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> project_id = ''
>>>
>>> # TODO: Initialize `traces`:
>>> traces = {}
>>>
>>> client.patch_traces(project_id, traces)
Args:
project_id (str): ID of the Cloud project where the trace data is stored.
traces (Union[dict, ~google.cloud.trace_v1.types.Traces]): The body of the message.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v1.types.Traces`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "patch_traces" not in self._inner_api_calls:
self._inner_api_calls[
"patch_traces"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.patch_traces,
default_retry=self._method_configs["PatchTraces"].retry,
default_timeout=self._method_configs["PatchTraces"].timeout,
client_info=self._client_info,
)
request = trace_pb2.PatchTracesRequest(project_id=project_id, traces=traces)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("project_id", project_id)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
self._inner_api_calls["patch_traces"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"patch_traces",
"(",
"self",
",",
"project_id",
",",
"traces",
",",
"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",
"\"patch_traces\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"patch_traces\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"patch_traces",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"PatchTraces\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"PatchTraces\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"trace_pb2",
".",
"PatchTracesRequest",
"(",
"project_id",
"=",
"project_id",
",",
"traces",
"=",
"traces",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"project_id\"",
",",
"project_id",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"self",
".",
"_inner_api_calls",
"[",
"\"patch_traces\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Sends new traces to Stackdriver Trace or updates existing traces. If the ID
of a trace that you send matches that of an existing trace, any fields
in the existing trace and its spans are overwritten by the provided values,
and any new fields provided are merged with the existing trace data. If the
ID does not match, a new trace is created.
Example:
>>> from google.cloud import trace_v1
>>>
>>> client = trace_v1.TraceServiceClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> project_id = ''
>>>
>>> # TODO: Initialize `traces`:
>>> traces = {}
>>>
>>> client.patch_traces(project_id, traces)
Args:
project_id (str): ID of the Cloud project where the trace data is stored.
traces (Union[dict, ~google.cloud.trace_v1.types.Traces]): The body of the message.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v1.types.Traces`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Sends",
"new",
"traces",
"to",
"Stackdriver",
"Trace",
"or",
"updates",
"existing",
"traces",
".",
"If",
"the",
"ID",
"of",
"a",
"trace",
"that",
"you",
"send",
"matches",
"that",
"of",
"an",
"existing",
"trace",
"any",
"fields",
"in",
"the",
"existing",
"trace",
"and",
"its",
"spans",
"are",
"overwritten",
"by",
"the",
"provided",
"values",
"and",
"any",
"new",
"fields",
"provided",
"are",
"merged",
"with",
"the",
"existing",
"trace",
"data",
".",
"If",
"the",
"ID",
"does",
"not",
"match",
"a",
"new",
"trace",
"is",
"created",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/trace/google/cloud/trace_v1/gapic/trace_service_client.py#L177-L254 |
28,193 | googleapis/google-cloud-python | trace/google/cloud/trace_v1/gapic/trace_service_client.py | TraceServiceClient.list_traces | def list_traces(
self,
project_id,
view=None,
page_size=None,
start_time=None,
end_time=None,
filter_=None,
order_by=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Returns of a list of traces that match the specified filter conditions.
Example:
>>> from google.cloud import trace_v1
>>>
>>> client = trace_v1.TraceServiceClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> project_id = ''
>>>
>>> # Iterate over all results
>>> for element in client.list_traces(project_id):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_traces(project_id).pages:
... for element in page:
... # process element
... pass
Args:
project_id (str): ID of the Cloud project where the trace data is stored.
view (~google.cloud.trace_v1.types.ViewType): Type of data returned for traces in the list. Optional. Default is
``MINIMAL``.
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
start_time (Union[dict, ~google.cloud.trace_v1.types.Timestamp]): Start of the time interval (inclusive) during which the trace data was
collected from the application.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v1.types.Timestamp`
end_time (Union[dict, ~google.cloud.trace_v1.types.Timestamp]): End of the time interval (inclusive) during which the trace data was
collected from the application.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v1.types.Timestamp`
filter_ (str): An optional filter against labels for the request.
By default, searches use prefix matching. To specify exact match,
prepend a plus symbol (``+``) to the search term. Multiple terms are
ANDed. Syntax:
- ``root:NAME_PREFIX`` or ``NAME_PREFIX``: Return traces where any root
span starts with ``NAME_PREFIX``.
- ``+root:NAME`` or ``+NAME``: Return traces where any root span's name
is exactly ``NAME``.
- ``span:NAME_PREFIX``: Return traces where any span starts with
``NAME_PREFIX``.
- ``+span:NAME``: Return traces where any span's name is exactly
``NAME``.
- ``latency:DURATION``: Return traces whose overall latency is greater
or equal to than ``DURATION``. Accepted units are nanoseconds
(``ns``), milliseconds (``ms``), and seconds (``s``). Default is
``ms``. For example, ``latency:24ms`` returns traces whose overall
latency is greater than or equal to 24 milliseconds.
- ``label:LABEL_KEY``: Return all traces containing the specified label
key (exact match, case-sensitive) regardless of the key:value pair's
value (including empty values).
- ``LABEL_KEY:VALUE_PREFIX``: Return all traces containing the
specified label key (exact match, case-sensitive) whose value starts
with ``VALUE_PREFIX``. Both a key and a value must be specified.
- ``+LABEL_KEY:VALUE``: Return all traces containing a key:value pair
exactly matching the specified text. Both a key and a value must be
specified.
- ``method:VALUE``: Equivalent to ``/http/method:VALUE``.
- ``url:VALUE``: Equivalent to ``/http/url:VALUE``.
order_by (str): Field used to sort the returned traces. Optional. Can be one of the
following:
- ``trace_id``
- ``name`` (``name`` field of root span in the trace)
- ``duration`` (difference between ``end_time`` and ``start_time``
fields of the root span)
- ``start`` (``start_time`` field of the root span)
Descending order can be specified by appending ``desc`` to the sort
field (for example, ``name desc``).
Only one sort field is permitted.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.trace_v1.types.Trace` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "list_traces" not in self._inner_api_calls:
self._inner_api_calls[
"list_traces"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_traces,
default_retry=self._method_configs["ListTraces"].retry,
default_timeout=self._method_configs["ListTraces"].timeout,
client_info=self._client_info,
)
request = trace_pb2.ListTracesRequest(
project_id=project_id,
view=view,
page_size=page_size,
start_time=start_time,
end_time=end_time,
filter=filter_,
order_by=order_by,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("project_id", project_id)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
iterator = google.api_core.page_iterator.GRPCIterator(
client=None,
method=functools.partial(
self._inner_api_calls["list_traces"],
retry=retry,
timeout=timeout,
metadata=metadata,
),
request=request,
items_field="traces",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | python | def list_traces(
self,
project_id,
view=None,
page_size=None,
start_time=None,
end_time=None,
filter_=None,
order_by=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Returns of a list of traces that match the specified filter conditions.
Example:
>>> from google.cloud import trace_v1
>>>
>>> client = trace_v1.TraceServiceClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> project_id = ''
>>>
>>> # Iterate over all results
>>> for element in client.list_traces(project_id):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_traces(project_id).pages:
... for element in page:
... # process element
... pass
Args:
project_id (str): ID of the Cloud project where the trace data is stored.
view (~google.cloud.trace_v1.types.ViewType): Type of data returned for traces in the list. Optional. Default is
``MINIMAL``.
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
start_time (Union[dict, ~google.cloud.trace_v1.types.Timestamp]): Start of the time interval (inclusive) during which the trace data was
collected from the application.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v1.types.Timestamp`
end_time (Union[dict, ~google.cloud.trace_v1.types.Timestamp]): End of the time interval (inclusive) during which the trace data was
collected from the application.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v1.types.Timestamp`
filter_ (str): An optional filter against labels for the request.
By default, searches use prefix matching. To specify exact match,
prepend a plus symbol (``+``) to the search term. Multiple terms are
ANDed. Syntax:
- ``root:NAME_PREFIX`` or ``NAME_PREFIX``: Return traces where any root
span starts with ``NAME_PREFIX``.
- ``+root:NAME`` or ``+NAME``: Return traces where any root span's name
is exactly ``NAME``.
- ``span:NAME_PREFIX``: Return traces where any span starts with
``NAME_PREFIX``.
- ``+span:NAME``: Return traces where any span's name is exactly
``NAME``.
- ``latency:DURATION``: Return traces whose overall latency is greater
or equal to than ``DURATION``. Accepted units are nanoseconds
(``ns``), milliseconds (``ms``), and seconds (``s``). Default is
``ms``. For example, ``latency:24ms`` returns traces whose overall
latency is greater than or equal to 24 milliseconds.
- ``label:LABEL_KEY``: Return all traces containing the specified label
key (exact match, case-sensitive) regardless of the key:value pair's
value (including empty values).
- ``LABEL_KEY:VALUE_PREFIX``: Return all traces containing the
specified label key (exact match, case-sensitive) whose value starts
with ``VALUE_PREFIX``. Both a key and a value must be specified.
- ``+LABEL_KEY:VALUE``: Return all traces containing a key:value pair
exactly matching the specified text. Both a key and a value must be
specified.
- ``method:VALUE``: Equivalent to ``/http/method:VALUE``.
- ``url:VALUE``: Equivalent to ``/http/url:VALUE``.
order_by (str): Field used to sort the returned traces. Optional. Can be one of the
following:
- ``trace_id``
- ``name`` (``name`` field of root span in the trace)
- ``duration`` (difference between ``end_time`` and ``start_time``
fields of the root span)
- ``start`` (``start_time`` field of the root span)
Descending order can be specified by appending ``desc`` to the sort
field (for example, ``name desc``).
Only one sort field is permitted.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.trace_v1.types.Trace` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "list_traces" not in self._inner_api_calls:
self._inner_api_calls[
"list_traces"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_traces,
default_retry=self._method_configs["ListTraces"].retry,
default_timeout=self._method_configs["ListTraces"].timeout,
client_info=self._client_info,
)
request = trace_pb2.ListTracesRequest(
project_id=project_id,
view=view,
page_size=page_size,
start_time=start_time,
end_time=end_time,
filter=filter_,
order_by=order_by,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("project_id", project_id)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
iterator = google.api_core.page_iterator.GRPCIterator(
client=None,
method=functools.partial(
self._inner_api_calls["list_traces"],
retry=retry,
timeout=timeout,
metadata=metadata,
),
request=request,
items_field="traces",
request_token_field="page_token",
response_token_field="next_page_token",
)
return iterator | [
"def",
"list_traces",
"(",
"self",
",",
"project_id",
",",
"view",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"start_time",
"=",
"None",
",",
"end_time",
"=",
"None",
",",
"filter_",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"list_traces\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"list_traces\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"list_traces",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"ListTraces\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"ListTraces\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"trace_pb2",
".",
"ListTracesRequest",
"(",
"project_id",
"=",
"project_id",
",",
"view",
"=",
"view",
",",
"page_size",
"=",
"page_size",
",",
"start_time",
"=",
"start_time",
",",
"end_time",
"=",
"end_time",
",",
"filter",
"=",
"filter_",
",",
"order_by",
"=",
"order_by",
",",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"[",
"]",
"metadata",
"=",
"list",
"(",
"metadata",
")",
"try",
":",
"routing_header",
"=",
"[",
"(",
"\"project_id\"",
",",
"project_id",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"routing_metadata",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"routing_header",
")",
"metadata",
".",
"append",
"(",
"routing_metadata",
")",
"iterator",
"=",
"google",
".",
"api_core",
".",
"page_iterator",
".",
"GRPCIterator",
"(",
"client",
"=",
"None",
",",
"method",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_inner_api_calls",
"[",
"\"list_traces\"",
"]",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
",",
")",
",",
"request",
"=",
"request",
",",
"items_field",
"=",
"\"traces\"",
",",
"request_token_field",
"=",
"\"page_token\"",
",",
"response_token_field",
"=",
"\"next_page_token\"",
",",
")",
"return",
"iterator"
] | Returns of a list of traces that match the specified filter conditions.
Example:
>>> from google.cloud import trace_v1
>>>
>>> client = trace_v1.TraceServiceClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> project_id = ''
>>>
>>> # Iterate over all results
>>> for element in client.list_traces(project_id):
... # process element
... pass
>>>
>>>
>>> # Alternatively:
>>>
>>> # Iterate over results one page at a time
>>> for page in client.list_traces(project_id).pages:
... for element in page:
... # process element
... pass
Args:
project_id (str): ID of the Cloud project where the trace data is stored.
view (~google.cloud.trace_v1.types.ViewType): Type of data returned for traces in the list. Optional. Default is
``MINIMAL``.
page_size (int): The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
start_time (Union[dict, ~google.cloud.trace_v1.types.Timestamp]): Start of the time interval (inclusive) during which the trace data was
collected from the application.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v1.types.Timestamp`
end_time (Union[dict, ~google.cloud.trace_v1.types.Timestamp]): End of the time interval (inclusive) during which the trace data was
collected from the application.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v1.types.Timestamp`
filter_ (str): An optional filter against labels for the request.
By default, searches use prefix matching. To specify exact match,
prepend a plus symbol (``+``) to the search term. Multiple terms are
ANDed. Syntax:
- ``root:NAME_PREFIX`` or ``NAME_PREFIX``: Return traces where any root
span starts with ``NAME_PREFIX``.
- ``+root:NAME`` or ``+NAME``: Return traces where any root span's name
is exactly ``NAME``.
- ``span:NAME_PREFIX``: Return traces where any span starts with
``NAME_PREFIX``.
- ``+span:NAME``: Return traces where any span's name is exactly
``NAME``.
- ``latency:DURATION``: Return traces whose overall latency is greater
or equal to than ``DURATION``. Accepted units are nanoseconds
(``ns``), milliseconds (``ms``), and seconds (``s``). Default is
``ms``. For example, ``latency:24ms`` returns traces whose overall
latency is greater than or equal to 24 milliseconds.
- ``label:LABEL_KEY``: Return all traces containing the specified label
key (exact match, case-sensitive) regardless of the key:value pair's
value (including empty values).
- ``LABEL_KEY:VALUE_PREFIX``: Return all traces containing the
specified label key (exact match, case-sensitive) whose value starts
with ``VALUE_PREFIX``. Both a key and a value must be specified.
- ``+LABEL_KEY:VALUE``: Return all traces containing a key:value pair
exactly matching the specified text. Both a key and a value must be
specified.
- ``method:VALUE``: Equivalent to ``/http/method:VALUE``.
- ``url:VALUE``: Equivalent to ``/http/url:VALUE``.
order_by (str): Field used to sort the returned traces. Optional. Can be one of the
following:
- ``trace_id``
- ``name`` (``name`` field of root span in the trace)
- ``duration`` (difference between ``end_time`` and ``start_time``
fields of the root span)
- ``start`` (``start_time`` field of the root span)
Descending order can be specified by appending ``desc`` to the sort
field (for example, ``name desc``).
Only one sort field is permitted.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.gax.PageIterator` instance. By default, this
is an iterable of :class:`~google.cloud.trace_v1.types.Trace` instances.
This object can also be configured to iterate over the pages
of the response through the `options` parameter.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Returns",
"of",
"a",
"list",
"of",
"traces",
"that",
"match",
"the",
"specified",
"filter",
"conditions",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/trace/google/cloud/trace_v1/gapic/trace_service_client.py#L318-L486 |
28,194 | googleapis/google-cloud-python | redis/google/cloud/redis_v1beta1/gapic/cloud_redis_client.py | CloudRedisClient.get_instance | def get_instance(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets the details of a specific Redis instance.
Example:
>>> from google.cloud import redis_v1beta1
>>>
>>> client = redis_v1beta1.CloudRedisClient()
>>>
>>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]')
>>>
>>> response = client.get_instance(name)
Args:
name (str): Required. Redis instance resource name using the form:
``projects/{project_id}/locations/{location_id}/instances/{instance_id}``
where ``location_id`` refers to a GCP region
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.redis_v1beta1.types.Instance` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "get_instance" not in self._inner_api_calls:
self._inner_api_calls[
"get_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_instance,
default_retry=self._method_configs["GetInstance"].retry,
default_timeout=self._method_configs["GetInstance"].timeout,
client_info=self._client_info,
)
request = cloud_redis_pb2.GetInstanceRequest(name=name)
return self._inner_api_calls["get_instance"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def get_instance(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets the details of a specific Redis instance.
Example:
>>> from google.cloud import redis_v1beta1
>>>
>>> client = redis_v1beta1.CloudRedisClient()
>>>
>>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]')
>>>
>>> response = client.get_instance(name)
Args:
name (str): Required. Redis instance resource name using the form:
``projects/{project_id}/locations/{location_id}/instances/{instance_id}``
where ``location_id`` refers to a GCP region
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.redis_v1beta1.types.Instance` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "get_instance" not in self._inner_api_calls:
self._inner_api_calls[
"get_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_instance,
default_retry=self._method_configs["GetInstance"].retry,
default_timeout=self._method_configs["GetInstance"].timeout,
client_info=self._client_info,
)
request = cloud_redis_pb2.GetInstanceRequest(name=name)
return self._inner_api_calls["get_instance"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"get_instance",
"(",
"self",
",",
"name",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"get_instance\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"get_instance\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"get_instance",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"GetInstance\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"GetInstance\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"cloud_redis_pb2",
".",
"GetInstanceRequest",
"(",
"name",
"=",
"name",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"get_instance\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Gets the details of a specific Redis instance.
Example:
>>> from google.cloud import redis_v1beta1
>>>
>>> client = redis_v1beta1.CloudRedisClient()
>>>
>>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]')
>>>
>>> response = client.get_instance(name)
Args:
name (str): Required. Redis instance resource name using the form:
``projects/{project_id}/locations/{location_id}/instances/{instance_id}``
where ``location_id`` refers to a GCP region
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.redis_v1beta1.types.Instance` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Gets",
"the",
"details",
"of",
"a",
"specific",
"Redis",
"instance",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/redis/google/cloud/redis_v1beta1/gapic/cloud_redis_client.py#L310-L366 |
28,195 | googleapis/google-cloud-python | redis/google/cloud/redis_v1beta1/gapic/cloud_redis_client.py | CloudRedisClient.update_instance | def update_instance(
self,
update_mask,
instance,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates the metadata and configuration of a specific Redis instance.
Completed longrunning.Operation will contain the new instance object
in the response field. The returned operation is automatically deleted
after a few hours, so there is no need to call DeleteOperation.
Example:
>>> from google.cloud import redis_v1beta1
>>>
>>> client = redis_v1beta1.CloudRedisClient()
>>>
>>> paths_element = 'display_name'
>>> paths_element_2 = 'memory_size_gb'
>>> paths = [paths_element, paths_element_2]
>>> update_mask = {'paths': paths}
>>> display_name = 'UpdatedDisplayName'
>>> memory_size_gb = 4
>>> instance = {'display_name': display_name, 'memory_size_gb': memory_size_gb}
>>>
>>> response = client.update_instance(update_mask, instance)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
update_mask (Union[dict, ~google.cloud.redis_v1beta1.types.FieldMask]): Required. Mask of fields to update. At least one path must be supplied
in this field. The elements of the repeated paths field may only include
these fields from ``Instance``: \* ``display_name`` \* ``labels`` \*
``memory_size_gb`` \* ``redis_config``
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.redis_v1beta1.types.FieldMask`
instance (Union[dict, ~google.cloud.redis_v1beta1.types.Instance]): Required. Update description. Only fields specified in update\_mask are
updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.redis_v1beta1.types.Instance`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.redis_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 "update_instance" not in self._inner_api_calls:
self._inner_api_calls[
"update_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_instance,
default_retry=self._method_configs["UpdateInstance"].retry,
default_timeout=self._method_configs["UpdateInstance"].timeout,
client_info=self._client_info,
)
request = cloud_redis_pb2.UpdateInstanceRequest(
update_mask=update_mask, instance=instance
)
operation = self._inner_api_calls["update_instance"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
cloud_redis_pb2.Instance,
metadata_type=any_pb2.Any,
) | python | def update_instance(
self,
update_mask,
instance,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates the metadata and configuration of a specific Redis instance.
Completed longrunning.Operation will contain the new instance object
in the response field. The returned operation is automatically deleted
after a few hours, so there is no need to call DeleteOperation.
Example:
>>> from google.cloud import redis_v1beta1
>>>
>>> client = redis_v1beta1.CloudRedisClient()
>>>
>>> paths_element = 'display_name'
>>> paths_element_2 = 'memory_size_gb'
>>> paths = [paths_element, paths_element_2]
>>> update_mask = {'paths': paths}
>>> display_name = 'UpdatedDisplayName'
>>> memory_size_gb = 4
>>> instance = {'display_name': display_name, 'memory_size_gb': memory_size_gb}
>>>
>>> response = client.update_instance(update_mask, instance)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
update_mask (Union[dict, ~google.cloud.redis_v1beta1.types.FieldMask]): Required. Mask of fields to update. At least one path must be supplied
in this field. The elements of the repeated paths field may only include
these fields from ``Instance``: \* ``display_name`` \* ``labels`` \*
``memory_size_gb`` \* ``redis_config``
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.redis_v1beta1.types.FieldMask`
instance (Union[dict, ~google.cloud.redis_v1beta1.types.Instance]): Required. Update description. Only fields specified in update\_mask are
updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.redis_v1beta1.types.Instance`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.redis_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 "update_instance" not in self._inner_api_calls:
self._inner_api_calls[
"update_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_instance,
default_retry=self._method_configs["UpdateInstance"].retry,
default_timeout=self._method_configs["UpdateInstance"].timeout,
client_info=self._client_info,
)
request = cloud_redis_pb2.UpdateInstanceRequest(
update_mask=update_mask, instance=instance
)
operation = self._inner_api_calls["update_instance"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
cloud_redis_pb2.Instance,
metadata_type=any_pb2.Any,
) | [
"def",
"update_instance",
"(",
"self",
",",
"update_mask",
",",
"instance",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
",",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"\"update_instance\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"update_instance\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"update_instance",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"UpdateInstance\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"UpdateInstance\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"cloud_redis_pb2",
".",
"UpdateInstanceRequest",
"(",
"update_mask",
"=",
"update_mask",
",",
"instance",
"=",
"instance",
")",
"operation",
"=",
"self",
".",
"_inner_api_calls",
"[",
"\"update_instance\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")",
"return",
"google",
".",
"api_core",
".",
"operation",
".",
"from_gapic",
"(",
"operation",
",",
"self",
".",
"transport",
".",
"_operations_client",
",",
"cloud_redis_pb2",
".",
"Instance",
",",
"metadata_type",
"=",
"any_pb2",
".",
"Any",
",",
")"
] | Updates the metadata and configuration of a specific Redis instance.
Completed longrunning.Operation will contain the new instance object
in the response field. The returned operation is automatically deleted
after a few hours, so there is no need to call DeleteOperation.
Example:
>>> from google.cloud import redis_v1beta1
>>>
>>> client = redis_v1beta1.CloudRedisClient()
>>>
>>> paths_element = 'display_name'
>>> paths_element_2 = 'memory_size_gb'
>>> paths = [paths_element, paths_element_2]
>>> update_mask = {'paths': paths}
>>> display_name = 'UpdatedDisplayName'
>>> memory_size_gb = 4
>>> instance = {'display_name': display_name, 'memory_size_gb': memory_size_gb}
>>>
>>> response = client.update_instance(update_mask, instance)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
update_mask (Union[dict, ~google.cloud.redis_v1beta1.types.FieldMask]): Required. Mask of fields to update. At least one path must be supplied
in this field. The elements of the repeated paths field may only include
these fields from ``Instance``: \* ``display_name`` \* ``labels`` \*
``memory_size_gb`` \* ``redis_config``
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.redis_v1beta1.types.FieldMask`
instance (Union[dict, ~google.cloud.redis_v1beta1.types.Instance]): Required. Update description. Only fields specified in update\_mask are
updated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.redis_v1beta1.types.Instance`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.redis_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. | [
"Updates",
"the",
"metadata",
"and",
"configuration",
"of",
"a",
"specific",
"Redis",
"instance",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/redis/google/cloud/redis_v1beta1/gapic/cloud_redis_client.py#L474-L567 |
28,196 | googleapis/google-cloud-python | redis/google/cloud/redis_v1beta1/gapic/cloud_redis_client.py | CloudRedisClient.delete_instance | def delete_instance(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a specific Redis instance. Instance stops serving and data is
deleted.
Example:
>>> from google.cloud import redis_v1beta1
>>>
>>> client = redis_v1beta1.CloudRedisClient()
>>>
>>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]')
>>>
>>> response = client.delete_instance(name)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
name (str): Required. Redis instance resource name using the form:
``projects/{project_id}/locations/{location_id}/instances/{instance_id}``
where ``location_id`` refers to a GCP region
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.redis_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_instance" not in self._inner_api_calls:
self._inner_api_calls[
"delete_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.delete_instance,
default_retry=self._method_configs["DeleteInstance"].retry,
default_timeout=self._method_configs["DeleteInstance"].timeout,
client_info=self._client_info,
)
request = cloud_redis_pb2.DeleteInstanceRequest(name=name)
operation = self._inner_api_calls["delete_instance"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
empty_pb2.Empty,
metadata_type=any_pb2.Any,
) | python | def delete_instance(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a specific Redis instance. Instance stops serving and data is
deleted.
Example:
>>> from google.cloud import redis_v1beta1
>>>
>>> client = redis_v1beta1.CloudRedisClient()
>>>
>>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]')
>>>
>>> response = client.delete_instance(name)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
name (str): Required. Redis instance resource name using the form:
``projects/{project_id}/locations/{location_id}/instances/{instance_id}``
where ``location_id`` refers to a GCP region
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.redis_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_instance" not in self._inner_api_calls:
self._inner_api_calls[
"delete_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.delete_instance,
default_retry=self._method_configs["DeleteInstance"].retry,
default_timeout=self._method_configs["DeleteInstance"].timeout,
client_info=self._client_info,
)
request = cloud_redis_pb2.DeleteInstanceRequest(name=name)
operation = self._inner_api_calls["delete_instance"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
empty_pb2.Empty,
metadata_type=any_pb2.Any,
) | [
"def",
"delete_instance",
"(",
"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_instance\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"delete_instance\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"delete_instance",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"DeleteInstance\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"DeleteInstance\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"cloud_redis_pb2",
".",
"DeleteInstanceRequest",
"(",
"name",
"=",
"name",
")",
"operation",
"=",
"self",
".",
"_inner_api_calls",
"[",
"\"delete_instance\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")",
"return",
"google",
".",
"api_core",
".",
"operation",
".",
"from_gapic",
"(",
"operation",
",",
"self",
".",
"transport",
".",
"_operations_client",
",",
"empty_pb2",
".",
"Empty",
",",
"metadata_type",
"=",
"any_pb2",
".",
"Any",
",",
")"
] | Deletes a specific Redis instance. Instance stops serving and data is
deleted.
Example:
>>> from google.cloud import redis_v1beta1
>>>
>>> client = redis_v1beta1.CloudRedisClient()
>>>
>>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]')
>>>
>>> response = client.delete_instance(name)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
name (str): Required. Redis instance resource name using the form:
``projects/{project_id}/locations/{location_id}/instances/{instance_id}``
where ``location_id`` refers to a GCP region
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.redis_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",
"specific",
"Redis",
"instance",
".",
"Instance",
"stops",
"serving",
"and",
"data",
"is",
"deleted",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/redis/google/cloud/redis_v1beta1/gapic/cloud_redis_client.py#L569-L641 |
28,197 | googleapis/google-cloud-python | dataproc/google/cloud/dataproc_v1beta2/gapic/workflow_template_service_client.py | WorkflowTemplateServiceClient.region_path | def region_path(cls, project, region):
"""Return a fully-qualified region string."""
return google.api_core.path_template.expand(
"projects/{project}/regions/{region}", project=project, region=region
) | python | def region_path(cls, project, region):
"""Return a fully-qualified region string."""
return google.api_core.path_template.expand(
"projects/{project}/regions/{region}", project=project, region=region
) | [
"def",
"region_path",
"(",
"cls",
",",
"project",
",",
"region",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/regions/{region}\"",
",",
"project",
"=",
"project",
",",
"region",
"=",
"region",
")"
] | Return a fully-qualified region string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"region",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/workflow_template_service_client.py#L87-L91 |
28,198 | googleapis/google-cloud-python | dataproc/google/cloud/dataproc_v1beta2/gapic/workflow_template_service_client.py | WorkflowTemplateServiceClient.workflow_template_path | def workflow_template_path(cls, project, region, workflow_template):
"""Return a fully-qualified workflow_template string."""
return google.api_core.path_template.expand(
"projects/{project}/regions/{region}/workflowTemplates/{workflow_template}",
project=project,
region=region,
workflow_template=workflow_template,
) | python | def workflow_template_path(cls, project, region, workflow_template):
"""Return a fully-qualified workflow_template string."""
return google.api_core.path_template.expand(
"projects/{project}/regions/{region}/workflowTemplates/{workflow_template}",
project=project,
region=region,
workflow_template=workflow_template,
) | [
"def",
"workflow_template_path",
"(",
"cls",
",",
"project",
",",
"region",
",",
"workflow_template",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/regions/{region}/workflowTemplates/{workflow_template}\"",
",",
"project",
"=",
"project",
",",
"region",
"=",
"region",
",",
"workflow_template",
"=",
"workflow_template",
",",
")"
] | Return a fully-qualified workflow_template string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"workflow_template",
"string",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/workflow_template_service_client.py#L94-L101 |
28,199 | googleapis/google-cloud-python | dataproc/google/cloud/dataproc_v1beta2/gapic/workflow_template_service_client.py | WorkflowTemplateServiceClient.create_workflow_template | def create_workflow_template(
self,
parent,
template,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates new workflow template.
Example:
>>> from google.cloud import dataproc_v1beta2
>>>
>>> client = dataproc_v1beta2.WorkflowTemplateServiceClient()
>>>
>>> parent = client.region_path('[PROJECT]', '[REGION]')
>>>
>>> # TODO: Initialize `template`:
>>> template = {}
>>>
>>> response = client.create_workflow_template(parent, template)
Args:
parent (str): Required. The "resource name" of the region, as described in
https://cloud.google.com/apis/design/resource\_names of the form
``projects/{project_id}/regions/{region}``
template (Union[dict, ~google.cloud.dataproc_v1beta2.types.WorkflowTemplate]): Required. The Dataproc workflow template to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dataproc_v1beta2.types.WorkflowTemplate`
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.dataproc_v1beta2.types.WorkflowTemplate` 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_workflow_template" not in self._inner_api_calls:
self._inner_api_calls[
"create_workflow_template"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_workflow_template,
default_retry=self._method_configs["CreateWorkflowTemplate"].retry,
default_timeout=self._method_configs["CreateWorkflowTemplate"].timeout,
client_info=self._client_info,
)
request = workflow_templates_pb2.CreateWorkflowTemplateRequest(
parent=parent, template=template
)
return self._inner_api_calls["create_workflow_template"](
request, retry=retry, timeout=timeout, metadata=metadata
) | python | def create_workflow_template(
self,
parent,
template,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates new workflow template.
Example:
>>> from google.cloud import dataproc_v1beta2
>>>
>>> client = dataproc_v1beta2.WorkflowTemplateServiceClient()
>>>
>>> parent = client.region_path('[PROJECT]', '[REGION]')
>>>
>>> # TODO: Initialize `template`:
>>> template = {}
>>>
>>> response = client.create_workflow_template(parent, template)
Args:
parent (str): Required. The "resource name" of the region, as described in
https://cloud.google.com/apis/design/resource\_names of the form
``projects/{project_id}/regions/{region}``
template (Union[dict, ~google.cloud.dataproc_v1beta2.types.WorkflowTemplate]): Required. The Dataproc workflow template to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dataproc_v1beta2.types.WorkflowTemplate`
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.dataproc_v1beta2.types.WorkflowTemplate` 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_workflow_template" not in self._inner_api_calls:
self._inner_api_calls[
"create_workflow_template"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_workflow_template,
default_retry=self._method_configs["CreateWorkflowTemplate"].retry,
default_timeout=self._method_configs["CreateWorkflowTemplate"].timeout,
client_info=self._client_info,
)
request = workflow_templates_pb2.CreateWorkflowTemplateRequest(
parent=parent, template=template
)
return self._inner_api_calls["create_workflow_template"](
request, retry=retry, timeout=timeout, metadata=metadata
) | [
"def",
"create_workflow_template",
"(",
"self",
",",
"parent",
",",
"template",
",",
"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_workflow_template\"",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"\"create_workflow_template\"",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_workflow_template",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateWorkflowTemplate\"",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"\"CreateWorkflowTemplate\"",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"workflow_templates_pb2",
".",
"CreateWorkflowTemplateRequest",
"(",
"parent",
"=",
"parent",
",",
"template",
"=",
"template",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"\"create_workflow_template\"",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | Creates new workflow template.
Example:
>>> from google.cloud import dataproc_v1beta2
>>>
>>> client = dataproc_v1beta2.WorkflowTemplateServiceClient()
>>>
>>> parent = client.region_path('[PROJECT]', '[REGION]')
>>>
>>> # TODO: Initialize `template`:
>>> template = {}
>>>
>>> response = client.create_workflow_template(parent, template)
Args:
parent (str): Required. The "resource name" of the region, as described in
https://cloud.google.com/apis/design/resource\_names of the form
``projects/{project_id}/regions/{region}``
template (Union[dict, ~google.cloud.dataproc_v1beta2.types.WorkflowTemplate]): Required. The Dataproc workflow template to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dataproc_v1beta2.types.WorkflowTemplate`
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.dataproc_v1beta2.types.WorkflowTemplate` 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",
"new",
"workflow",
"template",
"."
] | 85e80125a59cb10f8cb105f25ecc099e4b940b50 | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/workflow_template_service_client.py#L202-L268 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.