repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
googleapis/google-cloud-python
storage/google/cloud/storage/_signing.py
generate_signed_url_v2
def generate_signed_url_v2( credentials, resource, expiration, api_access_endpoint="", method="GET", content_md5=None, content_type=None, response_type=None, response_disposition=None, generation=None, headers=None, query_parameters=None, ): """Generate a V2 signed URL to provide query-string auth'n to a resource. .. note:: Assumes ``credentials`` implements the :class:`google.auth.credentials.Signing` interface. Also assumes ``credentials`` has a ``service_account_email`` property which identifies the credentials. .. note:: If you are on Google Compute Engine, you can't generate a signed URL. Follow `Issue 922`_ for updates on this. If you'd like to be able to generate a signed URL from GCE, you can use a standard service account from a JSON file rather than a GCE service account. See headers `reference`_ for more details on optional arguments. .. _Issue 922: https://github.com/GoogleCloudPlatform/\ google-cloud-python/issues/922 .. _reference: https://cloud.google.com/storage/docs/reference-headers :type credentials: :class:`google.auth.credentials.Signing` :param credentials: Credentials object with an associated private key to sign text. :type resource: str :param resource: A pointer to a specific resource (typically, ``/bucket-name/path/to/blob.txt``). :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :type api_access_endpoint: str :param api_access_endpoint: Optional URI base. Defaults to empty string. :type method: str :param method: The HTTP verb that will be used when requesting the URL. Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the signature will additionally contain the `x-goog-resumable` header, and the method changed to POST. See the signed URL docs regarding this flow: https://cloud.google.com/storage/docs/access-control/signed-urls :type content_md5: str :param content_md5: (Optional) The MD5 hash of the object referenced by ``resource``. :type content_type: str :param content_type: (Optional) The content type of the object referenced by ``resource``. :type response_type: str :param response_type: (Optional) Content type of responses to requests for the signed URL. Used to over-ride the content type of the underlying resource. :type response_disposition: str :param response_disposition: (Optional) Content disposition of responses to requests for the signed URL. :type generation: str :param generation: (Optional) A value that indicates which generation of the resource to fetch. :type headers: Union[dict|List(Tuple(str,str))] :param headers: (Optional) Additional HTTP headers to be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers Requests using the signed URL *must* pass the specified header (name and value) with each request for the URL. :type query_parameters: dict :param query_parameters: (Optional) Additional query paramtersto be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers#query :raises: :exc:`TypeError` when expiration is not a valid type. :raises: :exc:`AttributeError` if credentials is not an instance of :class:`google.auth.credentials.Signing`. :rtype: str :returns: A signed URL you can use to access the resource until expiration. """ expiration_stamp = get_expiration_seconds_v2(expiration) canonical = canonicalize(method, resource, query_parameters, headers) # Generate the string to sign. elements_to_sign = [ canonical.method, content_md5 or "", content_type or "", str(expiration_stamp), ] elements_to_sign.extend(canonical.headers) elements_to_sign.append(canonical.resource) string_to_sign = "\n".join(elements_to_sign) # Set the right query parameters. signed_query_params = get_signed_query_params_v2( credentials, expiration_stamp, string_to_sign ) if response_type is not None: signed_query_params["response-content-type"] = response_type if response_disposition is not None: signed_query_params["response-content-disposition"] = response_disposition if generation is not None: signed_query_params["generation"] = generation signed_query_params.update(canonical.query_parameters) sorted_signed_query_params = sorted(signed_query_params.items()) # Return the built URL. return "{endpoint}{resource}?{querystring}".format( endpoint=api_access_endpoint, resource=resource, querystring=six.moves.urllib.parse.urlencode(sorted_signed_query_params), )
python
def generate_signed_url_v2( credentials, resource, expiration, api_access_endpoint="", method="GET", content_md5=None, content_type=None, response_type=None, response_disposition=None, generation=None, headers=None, query_parameters=None, ): """Generate a V2 signed URL to provide query-string auth'n to a resource. .. note:: Assumes ``credentials`` implements the :class:`google.auth.credentials.Signing` interface. Also assumes ``credentials`` has a ``service_account_email`` property which identifies the credentials. .. note:: If you are on Google Compute Engine, you can't generate a signed URL. Follow `Issue 922`_ for updates on this. If you'd like to be able to generate a signed URL from GCE, you can use a standard service account from a JSON file rather than a GCE service account. See headers `reference`_ for more details on optional arguments. .. _Issue 922: https://github.com/GoogleCloudPlatform/\ google-cloud-python/issues/922 .. _reference: https://cloud.google.com/storage/docs/reference-headers :type credentials: :class:`google.auth.credentials.Signing` :param credentials: Credentials object with an associated private key to sign text. :type resource: str :param resource: A pointer to a specific resource (typically, ``/bucket-name/path/to/blob.txt``). :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :type api_access_endpoint: str :param api_access_endpoint: Optional URI base. Defaults to empty string. :type method: str :param method: The HTTP verb that will be used when requesting the URL. Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the signature will additionally contain the `x-goog-resumable` header, and the method changed to POST. See the signed URL docs regarding this flow: https://cloud.google.com/storage/docs/access-control/signed-urls :type content_md5: str :param content_md5: (Optional) The MD5 hash of the object referenced by ``resource``. :type content_type: str :param content_type: (Optional) The content type of the object referenced by ``resource``. :type response_type: str :param response_type: (Optional) Content type of responses to requests for the signed URL. Used to over-ride the content type of the underlying resource. :type response_disposition: str :param response_disposition: (Optional) Content disposition of responses to requests for the signed URL. :type generation: str :param generation: (Optional) A value that indicates which generation of the resource to fetch. :type headers: Union[dict|List(Tuple(str,str))] :param headers: (Optional) Additional HTTP headers to be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers Requests using the signed URL *must* pass the specified header (name and value) with each request for the URL. :type query_parameters: dict :param query_parameters: (Optional) Additional query paramtersto be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers#query :raises: :exc:`TypeError` when expiration is not a valid type. :raises: :exc:`AttributeError` if credentials is not an instance of :class:`google.auth.credentials.Signing`. :rtype: str :returns: A signed URL you can use to access the resource until expiration. """ expiration_stamp = get_expiration_seconds_v2(expiration) canonical = canonicalize(method, resource, query_parameters, headers) # Generate the string to sign. elements_to_sign = [ canonical.method, content_md5 or "", content_type or "", str(expiration_stamp), ] elements_to_sign.extend(canonical.headers) elements_to_sign.append(canonical.resource) string_to_sign = "\n".join(elements_to_sign) # Set the right query parameters. signed_query_params = get_signed_query_params_v2( credentials, expiration_stamp, string_to_sign ) if response_type is not None: signed_query_params["response-content-type"] = response_type if response_disposition is not None: signed_query_params["response-content-disposition"] = response_disposition if generation is not None: signed_query_params["generation"] = generation signed_query_params.update(canonical.query_parameters) sorted_signed_query_params = sorted(signed_query_params.items()) # Return the built URL. return "{endpoint}{resource}?{querystring}".format( endpoint=api_access_endpoint, resource=resource, querystring=six.moves.urllib.parse.urlencode(sorted_signed_query_params), )
[ "def", "generate_signed_url_v2", "(", "credentials", ",", "resource", ",", "expiration", ",", "api_access_endpoint", "=", "\"\"", ",", "method", "=", "\"GET\"", ",", "content_md5", "=", "None", ",", "content_type", "=", "None", ",", "response_type", "=", "None", ",", "response_disposition", "=", "None", ",", "generation", "=", "None", ",", "headers", "=", "None", ",", "query_parameters", "=", "None", ",", ")", ":", "expiration_stamp", "=", "get_expiration_seconds_v2", "(", "expiration", ")", "canonical", "=", "canonicalize", "(", "method", ",", "resource", ",", "query_parameters", ",", "headers", ")", "# Generate the string to sign.", "elements_to_sign", "=", "[", "canonical", ".", "method", ",", "content_md5", "or", "\"\"", ",", "content_type", "or", "\"\"", ",", "str", "(", "expiration_stamp", ")", ",", "]", "elements_to_sign", ".", "extend", "(", "canonical", ".", "headers", ")", "elements_to_sign", ".", "append", "(", "canonical", ".", "resource", ")", "string_to_sign", "=", "\"\\n\"", ".", "join", "(", "elements_to_sign", ")", "# Set the right query parameters.", "signed_query_params", "=", "get_signed_query_params_v2", "(", "credentials", ",", "expiration_stamp", ",", "string_to_sign", ")", "if", "response_type", "is", "not", "None", ":", "signed_query_params", "[", "\"response-content-type\"", "]", "=", "response_type", "if", "response_disposition", "is", "not", "None", ":", "signed_query_params", "[", "\"response-content-disposition\"", "]", "=", "response_disposition", "if", "generation", "is", "not", "None", ":", "signed_query_params", "[", "\"generation\"", "]", "=", "generation", "signed_query_params", ".", "update", "(", "canonical", ".", "query_parameters", ")", "sorted_signed_query_params", "=", "sorted", "(", "signed_query_params", ".", "items", "(", ")", ")", "# Return the built URL.", "return", "\"{endpoint}{resource}?{querystring}\"", ".", "format", "(", "endpoint", "=", "api_access_endpoint", ",", "resource", "=", "resource", ",", "querystring", "=", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlencode", "(", "sorted_signed_query_params", ")", ",", ")" ]
Generate a V2 signed URL to provide query-string auth'n to a resource. .. note:: Assumes ``credentials`` implements the :class:`google.auth.credentials.Signing` interface. Also assumes ``credentials`` has a ``service_account_email`` property which identifies the credentials. .. note:: If you are on Google Compute Engine, you can't generate a signed URL. Follow `Issue 922`_ for updates on this. If you'd like to be able to generate a signed URL from GCE, you can use a standard service account from a JSON file rather than a GCE service account. See headers `reference`_ for more details on optional arguments. .. _Issue 922: https://github.com/GoogleCloudPlatform/\ google-cloud-python/issues/922 .. _reference: https://cloud.google.com/storage/docs/reference-headers :type credentials: :class:`google.auth.credentials.Signing` :param credentials: Credentials object with an associated private key to sign text. :type resource: str :param resource: A pointer to a specific resource (typically, ``/bucket-name/path/to/blob.txt``). :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :type api_access_endpoint: str :param api_access_endpoint: Optional URI base. Defaults to empty string. :type method: str :param method: The HTTP verb that will be used when requesting the URL. Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the signature will additionally contain the `x-goog-resumable` header, and the method changed to POST. See the signed URL docs regarding this flow: https://cloud.google.com/storage/docs/access-control/signed-urls :type content_md5: str :param content_md5: (Optional) The MD5 hash of the object referenced by ``resource``. :type content_type: str :param content_type: (Optional) The content type of the object referenced by ``resource``. :type response_type: str :param response_type: (Optional) Content type of responses to requests for the signed URL. Used to over-ride the content type of the underlying resource. :type response_disposition: str :param response_disposition: (Optional) Content disposition of responses to requests for the signed URL. :type generation: str :param generation: (Optional) A value that indicates which generation of the resource to fetch. :type headers: Union[dict|List(Tuple(str,str))] :param headers: (Optional) Additional HTTP headers to be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers Requests using the signed URL *must* pass the specified header (name and value) with each request for the URL. :type query_parameters: dict :param query_parameters: (Optional) Additional query paramtersto be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers#query :raises: :exc:`TypeError` when expiration is not a valid type. :raises: :exc:`AttributeError` if credentials is not an instance of :class:`google.auth.credentials.Signing`. :rtype: str :returns: A signed URL you can use to access the resource until expiration.
[ "Generate", "a", "V2", "signed", "URL", "to", "provide", "query", "-", "string", "auth", "n", "to", "a", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_signing.py#L255-L392
train
googleapis/google-cloud-python
storage/google/cloud/storage/_signing.py
generate_signed_url_v4
def generate_signed_url_v4( credentials, resource, expiration, api_access_endpoint=DEFAULT_ENDPOINT, method="GET", content_md5=None, content_type=None, response_type=None, response_disposition=None, generation=None, headers=None, query_parameters=None, _request_timestamp=None, # for testing only ): """Generate a V4 signed URL to provide query-string auth'n to a resource. .. note:: Assumes ``credentials`` implements the :class:`google.auth.credentials.Signing` interface. Also assumes ``credentials`` has a ``service_account_email`` property which identifies the credentials. .. note:: If you are on Google Compute Engine, you can't generate a signed URL. Follow `Issue 922`_ for updates on this. If you'd like to be able to generate a signed URL from GCE, you can use a standard service account from a JSON file rather than a GCE service account. See headers `reference`_ for more details on optional arguments. .. _Issue 922: https://github.com/GoogleCloudPlatform/\ google-cloud-python/issues/922 .. _reference: https://cloud.google.com/storage/docs/reference-headers :type credentials: :class:`google.auth.credentials.Signing` :param credentials: Credentials object with an associated private key to sign text. :type resource: str :param resource: A pointer to a specific resource (typically, ``/bucket-name/path/to/blob.txt``). :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :type api_access_endpoint: str :param api_access_endpoint: Optional URI base. Defaults to "https://storage.googleapis.com/" :type method: str :param method: The HTTP verb that will be used when requesting the URL. Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the signature will additionally contain the `x-goog-resumable` header, and the method changed to POST. See the signed URL docs regarding this flow: https://cloud.google.com/storage/docs/access-control/signed-urls :type content_md5: str :param content_md5: (Optional) The MD5 hash of the object referenced by ``resource``. :type content_type: str :param content_type: (Optional) The content type of the object referenced by ``resource``. :type response_type: str :param response_type: (Optional) Content type of responses to requests for the signed URL. Used to over-ride the content type of the underlying resource. :type response_disposition: str :param response_disposition: (Optional) Content disposition of responses to requests for the signed URL. :type generation: str :param generation: (Optional) A value that indicates which generation of the resource to fetch. :type headers: dict :param headers: (Optional) Additional HTTP headers to be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers Requests using the signed URL *must* pass the specified header (name and value) with each request for the URL. :type query_parameters: dict :param query_parameters: (Optional) Additional query paramtersto be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers#query :raises: :exc:`TypeError` when expiration is not a valid type. :raises: :exc:`AttributeError` if credentials is not an instance of :class:`google.auth.credentials.Signing`. :rtype: str :returns: A signed URL you can use to access the resource until expiration. """ ensure_signed_credentials(credentials) expiration_seconds = get_expiration_seconds_v4(expiration) if _request_timestamp is None: now = NOW() request_timestamp = now.strftime("%Y%m%dT%H%M%SZ") datestamp = now.date().strftime("%Y%m%d") else: request_timestamp = _request_timestamp datestamp = _request_timestamp[:8] client_email = credentials.signer_email credential_scope = "{}/auto/storage/goog4_request".format(datestamp) credential = "{}/{}".format(client_email, credential_scope) if headers is None: headers = {} if content_type is not None: headers["Content-Type"] = content_type if content_md5 is not None: headers["Content-MD5"] = content_md5 header_names = [key.lower() for key in headers] if "host" not in header_names: headers["Host"] = "storage.googleapis.com" if method.upper() == "RESUMABLE": method = "POST" headers["x-goog-resumable"] = "start" canonical_headers, ordered_headers = get_canonical_headers(headers) canonical_header_string = ( "\n".join(canonical_headers) + "\n" ) # Yes, Virginia, the extra newline is part of the spec. signed_headers = ";".join([key for key, _ in ordered_headers]) if query_parameters is None: query_parameters = {} else: query_parameters = {key: value or "" for key, value in query_parameters.items()} query_parameters["X-Goog-Algorithm"] = "GOOG4-RSA-SHA256" query_parameters["X-Goog-Credential"] = credential query_parameters["X-Goog-Date"] = request_timestamp query_parameters["X-Goog-Expires"] = expiration_seconds query_parameters["X-Goog-SignedHeaders"] = signed_headers if response_type is not None: query_parameters["response-content-type"] = response_type if response_disposition is not None: query_parameters["response-content-disposition"] = response_disposition if generation is not None: query_parameters["generation"] = generation ordered_query_parameters = sorted(query_parameters.items()) canonical_query_string = six.moves.urllib.parse.urlencode(ordered_query_parameters) canonical_elements = [ method, resource, canonical_query_string, canonical_header_string, signed_headers, "UNSIGNED-PAYLOAD", ] canonical_request = "\n".join(canonical_elements) canonical_request_hash = hashlib.sha256( canonical_request.encode("ascii") ).hexdigest() string_elements = [ "GOOG4-RSA-SHA256", request_timestamp, credential_scope, canonical_request_hash, ] string_to_sign = "\n".join(string_elements) signature_bytes = credentials.sign_bytes(string_to_sign.encode("ascii")) signature = binascii.hexlify(signature_bytes).decode("ascii") return "{}{}?{}&X-Goog-Signature={}".format( api_access_endpoint, resource, canonical_query_string, signature )
python
def generate_signed_url_v4( credentials, resource, expiration, api_access_endpoint=DEFAULT_ENDPOINT, method="GET", content_md5=None, content_type=None, response_type=None, response_disposition=None, generation=None, headers=None, query_parameters=None, _request_timestamp=None, # for testing only ): """Generate a V4 signed URL to provide query-string auth'n to a resource. .. note:: Assumes ``credentials`` implements the :class:`google.auth.credentials.Signing` interface. Also assumes ``credentials`` has a ``service_account_email`` property which identifies the credentials. .. note:: If you are on Google Compute Engine, you can't generate a signed URL. Follow `Issue 922`_ for updates on this. If you'd like to be able to generate a signed URL from GCE, you can use a standard service account from a JSON file rather than a GCE service account. See headers `reference`_ for more details on optional arguments. .. _Issue 922: https://github.com/GoogleCloudPlatform/\ google-cloud-python/issues/922 .. _reference: https://cloud.google.com/storage/docs/reference-headers :type credentials: :class:`google.auth.credentials.Signing` :param credentials: Credentials object with an associated private key to sign text. :type resource: str :param resource: A pointer to a specific resource (typically, ``/bucket-name/path/to/blob.txt``). :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :type api_access_endpoint: str :param api_access_endpoint: Optional URI base. Defaults to "https://storage.googleapis.com/" :type method: str :param method: The HTTP verb that will be used when requesting the URL. Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the signature will additionally contain the `x-goog-resumable` header, and the method changed to POST. See the signed URL docs regarding this flow: https://cloud.google.com/storage/docs/access-control/signed-urls :type content_md5: str :param content_md5: (Optional) The MD5 hash of the object referenced by ``resource``. :type content_type: str :param content_type: (Optional) The content type of the object referenced by ``resource``. :type response_type: str :param response_type: (Optional) Content type of responses to requests for the signed URL. Used to over-ride the content type of the underlying resource. :type response_disposition: str :param response_disposition: (Optional) Content disposition of responses to requests for the signed URL. :type generation: str :param generation: (Optional) A value that indicates which generation of the resource to fetch. :type headers: dict :param headers: (Optional) Additional HTTP headers to be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers Requests using the signed URL *must* pass the specified header (name and value) with each request for the URL. :type query_parameters: dict :param query_parameters: (Optional) Additional query paramtersto be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers#query :raises: :exc:`TypeError` when expiration is not a valid type. :raises: :exc:`AttributeError` if credentials is not an instance of :class:`google.auth.credentials.Signing`. :rtype: str :returns: A signed URL you can use to access the resource until expiration. """ ensure_signed_credentials(credentials) expiration_seconds = get_expiration_seconds_v4(expiration) if _request_timestamp is None: now = NOW() request_timestamp = now.strftime("%Y%m%dT%H%M%SZ") datestamp = now.date().strftime("%Y%m%d") else: request_timestamp = _request_timestamp datestamp = _request_timestamp[:8] client_email = credentials.signer_email credential_scope = "{}/auto/storage/goog4_request".format(datestamp) credential = "{}/{}".format(client_email, credential_scope) if headers is None: headers = {} if content_type is not None: headers["Content-Type"] = content_type if content_md5 is not None: headers["Content-MD5"] = content_md5 header_names = [key.lower() for key in headers] if "host" not in header_names: headers["Host"] = "storage.googleapis.com" if method.upper() == "RESUMABLE": method = "POST" headers["x-goog-resumable"] = "start" canonical_headers, ordered_headers = get_canonical_headers(headers) canonical_header_string = ( "\n".join(canonical_headers) + "\n" ) # Yes, Virginia, the extra newline is part of the spec. signed_headers = ";".join([key for key, _ in ordered_headers]) if query_parameters is None: query_parameters = {} else: query_parameters = {key: value or "" for key, value in query_parameters.items()} query_parameters["X-Goog-Algorithm"] = "GOOG4-RSA-SHA256" query_parameters["X-Goog-Credential"] = credential query_parameters["X-Goog-Date"] = request_timestamp query_parameters["X-Goog-Expires"] = expiration_seconds query_parameters["X-Goog-SignedHeaders"] = signed_headers if response_type is not None: query_parameters["response-content-type"] = response_type if response_disposition is not None: query_parameters["response-content-disposition"] = response_disposition if generation is not None: query_parameters["generation"] = generation ordered_query_parameters = sorted(query_parameters.items()) canonical_query_string = six.moves.urllib.parse.urlencode(ordered_query_parameters) canonical_elements = [ method, resource, canonical_query_string, canonical_header_string, signed_headers, "UNSIGNED-PAYLOAD", ] canonical_request = "\n".join(canonical_elements) canonical_request_hash = hashlib.sha256( canonical_request.encode("ascii") ).hexdigest() string_elements = [ "GOOG4-RSA-SHA256", request_timestamp, credential_scope, canonical_request_hash, ] string_to_sign = "\n".join(string_elements) signature_bytes = credentials.sign_bytes(string_to_sign.encode("ascii")) signature = binascii.hexlify(signature_bytes).decode("ascii") return "{}{}?{}&X-Goog-Signature={}".format( api_access_endpoint, resource, canonical_query_string, signature )
[ "def", "generate_signed_url_v4", "(", "credentials", ",", "resource", ",", "expiration", ",", "api_access_endpoint", "=", "DEFAULT_ENDPOINT", ",", "method", "=", "\"GET\"", ",", "content_md5", "=", "None", ",", "content_type", "=", "None", ",", "response_type", "=", "None", ",", "response_disposition", "=", "None", ",", "generation", "=", "None", ",", "headers", "=", "None", ",", "query_parameters", "=", "None", ",", "_request_timestamp", "=", "None", ",", "# for testing only", ")", ":", "ensure_signed_credentials", "(", "credentials", ")", "expiration_seconds", "=", "get_expiration_seconds_v4", "(", "expiration", ")", "if", "_request_timestamp", "is", "None", ":", "now", "=", "NOW", "(", ")", "request_timestamp", "=", "now", ".", "strftime", "(", "\"%Y%m%dT%H%M%SZ\"", ")", "datestamp", "=", "now", ".", "date", "(", ")", ".", "strftime", "(", "\"%Y%m%d\"", ")", "else", ":", "request_timestamp", "=", "_request_timestamp", "datestamp", "=", "_request_timestamp", "[", ":", "8", "]", "client_email", "=", "credentials", ".", "signer_email", "credential_scope", "=", "\"{}/auto/storage/goog4_request\"", ".", "format", "(", "datestamp", ")", "credential", "=", "\"{}/{}\"", ".", "format", "(", "client_email", ",", "credential_scope", ")", "if", "headers", "is", "None", ":", "headers", "=", "{", "}", "if", "content_type", "is", "not", "None", ":", "headers", "[", "\"Content-Type\"", "]", "=", "content_type", "if", "content_md5", "is", "not", "None", ":", "headers", "[", "\"Content-MD5\"", "]", "=", "content_md5", "header_names", "=", "[", "key", ".", "lower", "(", ")", "for", "key", "in", "headers", "]", "if", "\"host\"", "not", "in", "header_names", ":", "headers", "[", "\"Host\"", "]", "=", "\"storage.googleapis.com\"", "if", "method", ".", "upper", "(", ")", "==", "\"RESUMABLE\"", ":", "method", "=", "\"POST\"", "headers", "[", "\"x-goog-resumable\"", "]", "=", "\"start\"", "canonical_headers", ",", "ordered_headers", "=", "get_canonical_headers", "(", "headers", ")", "canonical_header_string", "=", "(", "\"\\n\"", ".", "join", "(", "canonical_headers", ")", "+", "\"\\n\"", ")", "# Yes, Virginia, the extra newline is part of the spec.", "signed_headers", "=", "\";\"", ".", "join", "(", "[", "key", "for", "key", ",", "_", "in", "ordered_headers", "]", ")", "if", "query_parameters", "is", "None", ":", "query_parameters", "=", "{", "}", "else", ":", "query_parameters", "=", "{", "key", ":", "value", "or", "\"\"", "for", "key", ",", "value", "in", "query_parameters", ".", "items", "(", ")", "}", "query_parameters", "[", "\"X-Goog-Algorithm\"", "]", "=", "\"GOOG4-RSA-SHA256\"", "query_parameters", "[", "\"X-Goog-Credential\"", "]", "=", "credential", "query_parameters", "[", "\"X-Goog-Date\"", "]", "=", "request_timestamp", "query_parameters", "[", "\"X-Goog-Expires\"", "]", "=", "expiration_seconds", "query_parameters", "[", "\"X-Goog-SignedHeaders\"", "]", "=", "signed_headers", "if", "response_type", "is", "not", "None", ":", "query_parameters", "[", "\"response-content-type\"", "]", "=", "response_type", "if", "response_disposition", "is", "not", "None", ":", "query_parameters", "[", "\"response-content-disposition\"", "]", "=", "response_disposition", "if", "generation", "is", "not", "None", ":", "query_parameters", "[", "\"generation\"", "]", "=", "generation", "ordered_query_parameters", "=", "sorted", "(", "query_parameters", ".", "items", "(", ")", ")", "canonical_query_string", "=", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlencode", "(", "ordered_query_parameters", ")", "canonical_elements", "=", "[", "method", ",", "resource", ",", "canonical_query_string", ",", "canonical_header_string", ",", "signed_headers", ",", "\"UNSIGNED-PAYLOAD\"", ",", "]", "canonical_request", "=", "\"\\n\"", ".", "join", "(", "canonical_elements", ")", "canonical_request_hash", "=", "hashlib", ".", "sha256", "(", "canonical_request", ".", "encode", "(", "\"ascii\"", ")", ")", ".", "hexdigest", "(", ")", "string_elements", "=", "[", "\"GOOG4-RSA-SHA256\"", ",", "request_timestamp", ",", "credential_scope", ",", "canonical_request_hash", ",", "]", "string_to_sign", "=", "\"\\n\"", ".", "join", "(", "string_elements", ")", "signature_bytes", "=", "credentials", ".", "sign_bytes", "(", "string_to_sign", ".", "encode", "(", "\"ascii\"", ")", ")", "signature", "=", "binascii", ".", "hexlify", "(", "signature_bytes", ")", ".", "decode", "(", "\"ascii\"", ")", "return", "\"{}{}?{}&X-Goog-Signature={}\"", ".", "format", "(", "api_access_endpoint", ",", "resource", ",", "canonical_query_string", ",", "signature", ")" ]
Generate a V4 signed URL to provide query-string auth'n to a resource. .. note:: Assumes ``credentials`` implements the :class:`google.auth.credentials.Signing` interface. Also assumes ``credentials`` has a ``service_account_email`` property which identifies the credentials. .. note:: If you are on Google Compute Engine, you can't generate a signed URL. Follow `Issue 922`_ for updates on this. If you'd like to be able to generate a signed URL from GCE, you can use a standard service account from a JSON file rather than a GCE service account. See headers `reference`_ for more details on optional arguments. .. _Issue 922: https://github.com/GoogleCloudPlatform/\ google-cloud-python/issues/922 .. _reference: https://cloud.google.com/storage/docs/reference-headers :type credentials: :class:`google.auth.credentials.Signing` :param credentials: Credentials object with an associated private key to sign text. :type resource: str :param resource: A pointer to a specific resource (typically, ``/bucket-name/path/to/blob.txt``). :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :type api_access_endpoint: str :param api_access_endpoint: Optional URI base. Defaults to "https://storage.googleapis.com/" :type method: str :param method: The HTTP verb that will be used when requesting the URL. Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the signature will additionally contain the `x-goog-resumable` header, and the method changed to POST. See the signed URL docs regarding this flow: https://cloud.google.com/storage/docs/access-control/signed-urls :type content_md5: str :param content_md5: (Optional) The MD5 hash of the object referenced by ``resource``. :type content_type: str :param content_type: (Optional) The content type of the object referenced by ``resource``. :type response_type: str :param response_type: (Optional) Content type of responses to requests for the signed URL. Used to over-ride the content type of the underlying resource. :type response_disposition: str :param response_disposition: (Optional) Content disposition of responses to requests for the signed URL. :type generation: str :param generation: (Optional) A value that indicates which generation of the resource to fetch. :type headers: dict :param headers: (Optional) Additional HTTP headers to be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers Requests using the signed URL *must* pass the specified header (name and value) with each request for the URL. :type query_parameters: dict :param query_parameters: (Optional) Additional query paramtersto be included as part of the signed URLs. See: https://cloud.google.com/storage/docs/xml-api/reference-headers#query :raises: :exc:`TypeError` when expiration is not a valid type. :raises: :exc:`AttributeError` if credentials is not an instance of :class:`google.auth.credentials.Signing`. :rtype: str :returns: A signed URL you can use to access the resource until expiration.
[ "Generate", "a", "V4", "signed", "URL", "to", "provide", "query", "-", "string", "auth", "n", "to", "a", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_signing.py#L399-L591
train
googleapis/google-cloud-python
translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py
TranslationServiceClient.glossary_path
def glossary_path(cls, project, location, glossary): """Return a fully-qualified glossary string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/glossaries/{glossary}", project=project, location=location, glossary=glossary, )
python
def glossary_path(cls, project, location, glossary): """Return a fully-qualified glossary string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/glossaries/{glossary}", project=project, location=location, glossary=glossary, )
[ "def", "glossary_path", "(", "cls", ",", "project", ",", "location", ",", "glossary", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/locations/{location}/glossaries/{glossary}\"", ",", "project", "=", "project", ",", "location", "=", "location", ",", "glossary", "=", "glossary", ",", ")" ]
Return a fully-qualified glossary string.
[ "Return", "a", "fully", "-", "qualified", "glossary", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L88-L95
train
googleapis/google-cloud-python
translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py
TranslationServiceClient.translate_text
def translate_text( self, contents, target_language_code, mime_type=None, source_language_code=None, parent=None, model=None, glossary_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Translates input text and returns translated text. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> # TODO: Initialize `contents`: >>> contents = [] >>> >>> # TODO: Initialize `target_language_code`: >>> target_language_code = '' >>> >>> response = client.translate_text(contents, target_language_code) Args: contents (list[str]): Required. The content of the input in string format. We recommend the total contents to be less than 30k codepoints. Please use BatchTranslateText for larger text. target_language_code (str): Required. The BCP-47 language code to use for translation of the input text, set to one of the language codes listed in Language Support. mime_type (str): Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME type is assumed to be "text/html". source_language_code (str): Optional. The BCP-47 language code of the input text if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support. If the source language isn't specified, the API attempts to identify the source language automatically and returns the the source language within the response. parent (str): Optional. Only used when making regionalized call. Format: projects/{project-id}/locations/{location-id}. Only custom model/glossary within the same location-id can be used. Otherwise 400 is returned. model (str): Optional. The ``model`` type requested for this translation. The format depends on model type: 1. Custom models: projects/{project-id}/locations/{location-id}/models/{model-id}. 2. General (built-in) models: projects/{project-id}/locations/{location-id}/models/general/nmt projects/{project-id}/locations/{location-id}/models/general/base For global (non-regionalized) requests, use {location-id} 'global'. For example, projects/{project-id}/locations/global/models/general/nmt If missing, the system decides which google base model to use. glossary_config (Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]): Optional. Glossary to be applied. The glossary needs to be in the same region as the model, otherwise an INVALID\_ARGUMENT error is returned. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig` 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.translate_v3beta1.types.TranslateTextResponse` 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 "translate_text" not in self._inner_api_calls: self._inner_api_calls[ "translate_text" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.translate_text, default_retry=self._method_configs["TranslateText"].retry, default_timeout=self._method_configs["TranslateText"].timeout, client_info=self._client_info, ) request = translation_service_pb2.TranslateTextRequest( contents=contents, target_language_code=target_language_code, mime_type=mime_type, source_language_code=source_language_code, parent=parent, model=model, glossary_config=glossary_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["translate_text"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def translate_text( self, contents, target_language_code, mime_type=None, source_language_code=None, parent=None, model=None, glossary_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Translates input text and returns translated text. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> # TODO: Initialize `contents`: >>> contents = [] >>> >>> # TODO: Initialize `target_language_code`: >>> target_language_code = '' >>> >>> response = client.translate_text(contents, target_language_code) Args: contents (list[str]): Required. The content of the input in string format. We recommend the total contents to be less than 30k codepoints. Please use BatchTranslateText for larger text. target_language_code (str): Required. The BCP-47 language code to use for translation of the input text, set to one of the language codes listed in Language Support. mime_type (str): Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME type is assumed to be "text/html". source_language_code (str): Optional. The BCP-47 language code of the input text if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support. If the source language isn't specified, the API attempts to identify the source language automatically and returns the the source language within the response. parent (str): Optional. Only used when making regionalized call. Format: projects/{project-id}/locations/{location-id}. Only custom model/glossary within the same location-id can be used. Otherwise 400 is returned. model (str): Optional. The ``model`` type requested for this translation. The format depends on model type: 1. Custom models: projects/{project-id}/locations/{location-id}/models/{model-id}. 2. General (built-in) models: projects/{project-id}/locations/{location-id}/models/general/nmt projects/{project-id}/locations/{location-id}/models/general/base For global (non-regionalized) requests, use {location-id} 'global'. For example, projects/{project-id}/locations/global/models/general/nmt If missing, the system decides which google base model to use. glossary_config (Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]): Optional. Glossary to be applied. The glossary needs to be in the same region as the model, otherwise an INVALID\_ARGUMENT error is returned. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig` 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.translate_v3beta1.types.TranslateTextResponse` 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 "translate_text" not in self._inner_api_calls: self._inner_api_calls[ "translate_text" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.translate_text, default_retry=self._method_configs["TranslateText"].retry, default_timeout=self._method_configs["TranslateText"].timeout, client_info=self._client_info, ) request = translation_service_pb2.TranslateTextRequest( contents=contents, target_language_code=target_language_code, mime_type=mime_type, source_language_code=source_language_code, parent=parent, model=model, glossary_config=glossary_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["translate_text"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "translate_text", "(", "self", ",", "contents", ",", "target_language_code", ",", "mime_type", "=", "None", ",", "source_language_code", "=", "None", ",", "parent", "=", "None", ",", "model", "=", "None", ",", "glossary_config", "=", "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", "\"translate_text\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"translate_text\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "translate_text", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"TranslateText\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"TranslateText\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "translation_service_pb2", ".", "TranslateTextRequest", "(", "contents", "=", "contents", ",", "target_language_code", "=", "target_language_code", ",", "mime_type", "=", "mime_type", ",", "source_language_code", "=", "source_language_code", ",", "parent", "=", "parent", ",", "model", "=", "model", ",", "glossary_config", "=", "glossary_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", "[", "\"translate_text\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Translates input text and returns translated text. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> # TODO: Initialize `contents`: >>> contents = [] >>> >>> # TODO: Initialize `target_language_code`: >>> target_language_code = '' >>> >>> response = client.translate_text(contents, target_language_code) Args: contents (list[str]): Required. The content of the input in string format. We recommend the total contents to be less than 30k codepoints. Please use BatchTranslateText for larger text. target_language_code (str): Required. The BCP-47 language code to use for translation of the input text, set to one of the language codes listed in Language Support. mime_type (str): Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME type is assumed to be "text/html". source_language_code (str): Optional. The BCP-47 language code of the input text if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support. If the source language isn't specified, the API attempts to identify the source language automatically and returns the the source language within the response. parent (str): Optional. Only used when making regionalized call. Format: projects/{project-id}/locations/{location-id}. Only custom model/glossary within the same location-id can be used. Otherwise 400 is returned. model (str): Optional. The ``model`` type requested for this translation. The format depends on model type: 1. Custom models: projects/{project-id}/locations/{location-id}/models/{model-id}. 2. General (built-in) models: projects/{project-id}/locations/{location-id}/models/general/nmt projects/{project-id}/locations/{location-id}/models/general/base For global (non-regionalized) requests, use {location-id} 'global'. For example, projects/{project-id}/locations/global/models/general/nmt If missing, the system decides which google base model to use. glossary_config (Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]): Optional. Glossary to be applied. The glossary needs to be in the same region as the model, otherwise an INVALID\_ARGUMENT error is returned. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig` 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.translate_v3beta1.types.TranslateTextResponse` 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.
[ "Translates", "input", "text", "and", "returns", "translated", "text", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L196-L317
train
googleapis/google-cloud-python
translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py
TranslationServiceClient.detect_language
def detect_language( self, parent=None, model=None, content=None, mime_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Detects the language of text within a request. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> response = client.detect_language() Args: parent (str): Optional. Only used when making regionalized call. Format: projects/{project-id}/locations/{location-id}. Only custom model within the same location-id can be used. Otherwise 400 is returned. model (str): Optional. The language detection model to be used. projects/{project-id}/locations/{location-id}/models/language-detection/{model-id} If not specified, default will be used. content (str): The content of the input stored as a string. mime_type (str): Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME type is assumed to be "text/html". 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.translate_v3beta1.types.DetectLanguageResponse` 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 "detect_language" not in self._inner_api_calls: self._inner_api_calls[ "detect_language" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.detect_language, default_retry=self._method_configs["DetectLanguage"].retry, default_timeout=self._method_configs["DetectLanguage"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof(content=content) request = translation_service_pb2.DetectLanguageRequest( parent=parent, model=model, content=content, mime_type=mime_type ) 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["detect_language"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def detect_language( self, parent=None, model=None, content=None, mime_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Detects the language of text within a request. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> response = client.detect_language() Args: parent (str): Optional. Only used when making regionalized call. Format: projects/{project-id}/locations/{location-id}. Only custom model within the same location-id can be used. Otherwise 400 is returned. model (str): Optional. The language detection model to be used. projects/{project-id}/locations/{location-id}/models/language-detection/{model-id} If not specified, default will be used. content (str): The content of the input stored as a string. mime_type (str): Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME type is assumed to be "text/html". 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.translate_v3beta1.types.DetectLanguageResponse` 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 "detect_language" not in self._inner_api_calls: self._inner_api_calls[ "detect_language" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.detect_language, default_retry=self._method_configs["DetectLanguage"].retry, default_timeout=self._method_configs["DetectLanguage"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof(content=content) request = translation_service_pb2.DetectLanguageRequest( parent=parent, model=model, content=content, mime_type=mime_type ) 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["detect_language"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "detect_language", "(", "self", ",", "parent", "=", "None", ",", "model", "=", "None", ",", "content", "=", "None", ",", "mime_type", "=", "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", "\"detect_language\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"detect_language\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "detect_language", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"DetectLanguage\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"DetectLanguage\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "content", "=", "content", ")", "request", "=", "translation_service_pb2", ".", "DetectLanguageRequest", "(", "parent", "=", "parent", ",", "model", "=", "model", ",", "content", "=", "content", ",", "mime_type", "=", "mime_type", ")", "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", "[", "\"detect_language\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Detects the language of text within a request. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> response = client.detect_language() Args: parent (str): Optional. Only used when making regionalized call. Format: projects/{project-id}/locations/{location-id}. Only custom model within the same location-id can be used. Otherwise 400 is returned. model (str): Optional. The language detection model to be used. projects/{project-id}/locations/{location-id}/models/language-detection/{model-id} If not specified, default will be used. content (str): The content of the input stored as a string. mime_type (str): Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME type is assumed to be "text/html". 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.translate_v3beta1.types.DetectLanguageResponse` 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.
[ "Detects", "the", "language", "of", "text", "within", "a", "request", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L319-L404
train
googleapis/google-cloud-python
translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py
TranslationServiceClient.get_supported_languages
def get_supported_languages( self, parent=None, display_language_code=None, model=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Returns a list of supported languages for translation. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> response = client.get_supported_languages() Args: parent (str): Optional. Used for making regionalized calls. Format: projects/{project-id}/locations/{location-id}. For global calls, use projects/{project-id}/locations/global. If missing, the call is treated as a global call. Only custom model within the same location-id can be used. Otherwise 400 is returned. display_language_code (str): Optional. The language to use to return localized, human readable names of supported languages. If missing, default language is ENGLISH. model (str): Optional. Get supported languages of this model. The format depends on model type: 1. Custom models: projects/{project-id}/locations/{location-id}/models/{model-id}. 2. General (built-in) models: projects/{project-id}/locations/{location-id}/models/general/nmt projects/{project-id}/locations/{location-id}/models/general/base Returns languages supported by the specified model. If missing, we get supported languages of Google general NMT model. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.translate_v3beta1.types.SupportedLanguages` 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_supported_languages" not in self._inner_api_calls: self._inner_api_calls[ "get_supported_languages" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_supported_languages, default_retry=self._method_configs["GetSupportedLanguages"].retry, default_timeout=self._method_configs["GetSupportedLanguages"].timeout, client_info=self._client_info, ) request = translation_service_pb2.GetSupportedLanguagesRequest( parent=parent, display_language_code=display_language_code, model=model ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_supported_languages"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def get_supported_languages( self, parent=None, display_language_code=None, model=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Returns a list of supported languages for translation. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> response = client.get_supported_languages() Args: parent (str): Optional. Used for making regionalized calls. Format: projects/{project-id}/locations/{location-id}. For global calls, use projects/{project-id}/locations/global. If missing, the call is treated as a global call. Only custom model within the same location-id can be used. Otherwise 400 is returned. display_language_code (str): Optional. The language to use to return localized, human readable names of supported languages. If missing, default language is ENGLISH. model (str): Optional. Get supported languages of this model. The format depends on model type: 1. Custom models: projects/{project-id}/locations/{location-id}/models/{model-id}. 2. General (built-in) models: projects/{project-id}/locations/{location-id}/models/general/nmt projects/{project-id}/locations/{location-id}/models/general/base Returns languages supported by the specified model. If missing, we get supported languages of Google general NMT model. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.translate_v3beta1.types.SupportedLanguages` 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_supported_languages" not in self._inner_api_calls: self._inner_api_calls[ "get_supported_languages" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_supported_languages, default_retry=self._method_configs["GetSupportedLanguages"].retry, default_timeout=self._method_configs["GetSupportedLanguages"].timeout, client_info=self._client_info, ) request = translation_service_pb2.GetSupportedLanguagesRequest( parent=parent, display_language_code=display_language_code, model=model ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_supported_languages"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "get_supported_languages", "(", "self", ",", "parent", "=", "None", ",", "display_language_code", "=", "None", ",", "model", "=", "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", "\"get_supported_languages\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"get_supported_languages\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "get_supported_languages", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"GetSupportedLanguages\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"GetSupportedLanguages\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "translation_service_pb2", ".", "GetSupportedLanguagesRequest", "(", "parent", "=", "parent", ",", "display_language_code", "=", "display_language_code", ",", "model", "=", "model", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"parent\"", ",", "parent", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"get_supported_languages\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Returns a list of supported languages for translation. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> response = client.get_supported_languages() Args: parent (str): Optional. Used for making regionalized calls. Format: projects/{project-id}/locations/{location-id}. For global calls, use projects/{project-id}/locations/global. If missing, the call is treated as a global call. Only custom model within the same location-id can be used. Otherwise 400 is returned. display_language_code (str): Optional. The language to use to return localized, human readable names of supported languages. If missing, default language is ENGLISH. model (str): Optional. Get supported languages of this model. The format depends on model type: 1. Custom models: projects/{project-id}/locations/{location-id}/models/{model-id}. 2. General (built-in) models: projects/{project-id}/locations/{location-id}/models/general/nmt projects/{project-id}/locations/{location-id}/models/general/base Returns languages supported by the specified model. If missing, we get supported languages of Google general NMT model. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.translate_v3beta1.types.SupportedLanguages` 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.
[ "Returns", "a", "list", "of", "supported", "languages", "for", "translation", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L406-L492
train
googleapis/google-cloud-python
translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py
TranslationServiceClient.batch_translate_text
def batch_translate_text( self, source_language_code, target_language_codes, input_configs, output_config, parent=None, models=None, glossaries=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Translates a large volume of text in asynchronous batch mode. This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location. This call returns immediately and you can use google.longrunning.Operation.name to poll the status of the call. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> # TODO: Initialize `source_language_code`: >>> source_language_code = '' >>> >>> # TODO: Initialize `target_language_codes`: >>> target_language_codes = [] >>> >>> # TODO: Initialize `input_configs`: >>> input_configs = [] >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.batch_translate_text(source_language_code, target_language_codes, input_configs, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: source_language_code (str): Required. Source language code. target_language_codes (list[str]): Required. Specify up to 10 language codes here. input_configs (list[Union[dict, ~google.cloud.translate_v3beta1.types.InputConfig]]): Required. Input configurations. The total number of files matched should be <= 1000. The total content size should be <= 100M Unicode codepoints. The files must use UTF-8 encoding. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.InputConfig` output_config (Union[dict, ~google.cloud.translate_v3beta1.types.OutputConfig]): Required. Output configuration. If 2 input configs match to the same file (that is, same input path), we don't generate output for duplicate inputs. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.OutputConfig` parent (str): Optional. Only used when making regionalized call. Format: projects/{project-id}/locations/{location-id}. Only custom models/glossaries within the same location-id can be used. Otherwise 400 is returned. models (dict[str -> str]): Optional. The models to use for translation. Map's key is target language code. Map's value is model name. Value can be a built-in general model, or a custom model built by AutoML. The value format depends on model type: 1. Custom models: projects/{project-id}/locations/{location-id}/models/{model-id}. 2. General (built-in) models: projects/{project-id}/locations/{location-id}/models/general/nmt projects/{project-id}/locations/{location-id}/models/general/base If the map is empty or a specific model is not requested for a language pair, then default google model is used. glossaries (dict[str -> Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]]): Optional. Glossaries to be applied for translation. It's keyed by target language code. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig` 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.translate_v3beta1.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 "batch_translate_text" not in self._inner_api_calls: self._inner_api_calls[ "batch_translate_text" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_translate_text, default_retry=self._method_configs["BatchTranslateText"].retry, default_timeout=self._method_configs["BatchTranslateText"].timeout, client_info=self._client_info, ) request = translation_service_pb2.BatchTranslateTextRequest( source_language_code=source_language_code, target_language_codes=target_language_codes, input_configs=input_configs, output_config=output_config, parent=parent, models=models, glossaries=glossaries, ) 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["batch_translate_text"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, translation_service_pb2.BatchTranslateResponse, metadata_type=translation_service_pb2.BatchTranslateMetadata, )
python
def batch_translate_text( self, source_language_code, target_language_codes, input_configs, output_config, parent=None, models=None, glossaries=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Translates a large volume of text in asynchronous batch mode. This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location. This call returns immediately and you can use google.longrunning.Operation.name to poll the status of the call. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> # TODO: Initialize `source_language_code`: >>> source_language_code = '' >>> >>> # TODO: Initialize `target_language_codes`: >>> target_language_codes = [] >>> >>> # TODO: Initialize `input_configs`: >>> input_configs = [] >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.batch_translate_text(source_language_code, target_language_codes, input_configs, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: source_language_code (str): Required. Source language code. target_language_codes (list[str]): Required. Specify up to 10 language codes here. input_configs (list[Union[dict, ~google.cloud.translate_v3beta1.types.InputConfig]]): Required. Input configurations. The total number of files matched should be <= 1000. The total content size should be <= 100M Unicode codepoints. The files must use UTF-8 encoding. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.InputConfig` output_config (Union[dict, ~google.cloud.translate_v3beta1.types.OutputConfig]): Required. Output configuration. If 2 input configs match to the same file (that is, same input path), we don't generate output for duplicate inputs. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.OutputConfig` parent (str): Optional. Only used when making regionalized call. Format: projects/{project-id}/locations/{location-id}. Only custom models/glossaries within the same location-id can be used. Otherwise 400 is returned. models (dict[str -> str]): Optional. The models to use for translation. Map's key is target language code. Map's value is model name. Value can be a built-in general model, or a custom model built by AutoML. The value format depends on model type: 1. Custom models: projects/{project-id}/locations/{location-id}/models/{model-id}. 2. General (built-in) models: projects/{project-id}/locations/{location-id}/models/general/nmt projects/{project-id}/locations/{location-id}/models/general/base If the map is empty or a specific model is not requested for a language pair, then default google model is used. glossaries (dict[str -> Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]]): Optional. Glossaries to be applied for translation. It's keyed by target language code. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig` 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.translate_v3beta1.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 "batch_translate_text" not in self._inner_api_calls: self._inner_api_calls[ "batch_translate_text" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_translate_text, default_retry=self._method_configs["BatchTranslateText"].retry, default_timeout=self._method_configs["BatchTranslateText"].timeout, client_info=self._client_info, ) request = translation_service_pb2.BatchTranslateTextRequest( source_language_code=source_language_code, target_language_codes=target_language_codes, input_configs=input_configs, output_config=output_config, parent=parent, models=models, glossaries=glossaries, ) 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["batch_translate_text"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, translation_service_pb2.BatchTranslateResponse, metadata_type=translation_service_pb2.BatchTranslateMetadata, )
[ "def", "batch_translate_text", "(", "self", ",", "source_language_code", ",", "target_language_codes", ",", "input_configs", ",", "output_config", ",", "parent", "=", "None", ",", "models", "=", "None", ",", "glossaries", "=", "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", "\"batch_translate_text\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"batch_translate_text\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "batch_translate_text", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"BatchTranslateText\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"BatchTranslateText\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "translation_service_pb2", ".", "BatchTranslateTextRequest", "(", "source_language_code", "=", "source_language_code", ",", "target_language_codes", "=", "target_language_codes", ",", "input_configs", "=", "input_configs", ",", "output_config", "=", "output_config", ",", "parent", "=", "parent", ",", "models", "=", "models", ",", "glossaries", "=", "glossaries", ",", ")", "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", "[", "\"batch_translate_text\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "translation_service_pb2", ".", "BatchTranslateResponse", ",", "metadata_type", "=", "translation_service_pb2", ".", "BatchTranslateMetadata", ",", ")" ]
Translates a large volume of text in asynchronous batch mode. This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location. This call returns immediately and you can use google.longrunning.Operation.name to poll the status of the call. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> # TODO: Initialize `source_language_code`: >>> source_language_code = '' >>> >>> # TODO: Initialize `target_language_codes`: >>> target_language_codes = [] >>> >>> # TODO: Initialize `input_configs`: >>> input_configs = [] >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.batch_translate_text(source_language_code, target_language_codes, input_configs, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: source_language_code (str): Required. Source language code. target_language_codes (list[str]): Required. Specify up to 10 language codes here. input_configs (list[Union[dict, ~google.cloud.translate_v3beta1.types.InputConfig]]): Required. Input configurations. The total number of files matched should be <= 1000. The total content size should be <= 100M Unicode codepoints. The files must use UTF-8 encoding. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.InputConfig` output_config (Union[dict, ~google.cloud.translate_v3beta1.types.OutputConfig]): Required. Output configuration. If 2 input configs match to the same file (that is, same input path), we don't generate output for duplicate inputs. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.OutputConfig` parent (str): Optional. Only used when making regionalized call. Format: projects/{project-id}/locations/{location-id}. Only custom models/glossaries within the same location-id can be used. Otherwise 400 is returned. models (dict[str -> str]): Optional. The models to use for translation. Map's key is target language code. Map's value is model name. Value can be a built-in general model, or a custom model built by AutoML. The value format depends on model type: 1. Custom models: projects/{project-id}/locations/{location-id}/models/{model-id}. 2. General (built-in) models: projects/{project-id}/locations/{location-id}/models/general/nmt projects/{project-id}/locations/{location-id}/models/general/base If the map is empty or a specific model is not requested for a language pair, then default google model is used. glossaries (dict[str -> Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]]): Optional. Glossaries to be applied for translation. It's keyed by target language code. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig` 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.translate_v3beta1.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.
[ "Translates", "a", "large", "volume", "of", "text", "in", "asynchronous", "batch", "mode", ".", "This", "function", "provides", "real", "-", "time", "output", "as", "the", "inputs", "are", "being", "processed", ".", "If", "caller", "cancels", "a", "request", "the", "partial", "results", "(", "for", "an", "input", "file", "it", "s", "all", "or", "nothing", ")", "may", "still", "be", "available", "on", "the", "specified", "output", "location", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L494-L644
train
googleapis/google-cloud-python
translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py
TranslationServiceClient.create_glossary
def create_glossary( self, parent, glossary, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a glossary and returns the long-running operation. Returns NOT\_FOUND, if the project doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> >>> # TODO: Initialize `glossary`: >>> glossary = {} >>> >>> response = client.create_glossary(parent, glossary) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project name. glossary (Union[dict, ~google.cloud.translate_v3beta1.types.Glossary]): Required. The glossary to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.Glossary` 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.translate_v3beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_glossary" not in self._inner_api_calls: self._inner_api_calls[ "create_glossary" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_glossary, default_retry=self._method_configs["CreateGlossary"].retry, default_timeout=self._method_configs["CreateGlossary"].timeout, client_info=self._client_info, ) request = translation_service_pb2.CreateGlossaryRequest( parent=parent, glossary=glossary ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["create_glossary"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, translation_service_pb2.Glossary, metadata_type=translation_service_pb2.CreateGlossaryMetadata, )
python
def create_glossary( self, parent, glossary, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a glossary and returns the long-running operation. Returns NOT\_FOUND, if the project doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> >>> # TODO: Initialize `glossary`: >>> glossary = {} >>> >>> response = client.create_glossary(parent, glossary) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project name. glossary (Union[dict, ~google.cloud.translate_v3beta1.types.Glossary]): Required. The glossary to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.Glossary` 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.translate_v3beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_glossary" not in self._inner_api_calls: self._inner_api_calls[ "create_glossary" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_glossary, default_retry=self._method_configs["CreateGlossary"].retry, default_timeout=self._method_configs["CreateGlossary"].timeout, client_info=self._client_info, ) request = translation_service_pb2.CreateGlossaryRequest( parent=parent, glossary=glossary ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["create_glossary"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, translation_service_pb2.Glossary, metadata_type=translation_service_pb2.CreateGlossaryMetadata, )
[ "def", "create_glossary", "(", "self", ",", "parent", ",", "glossary", ",", "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_glossary\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_glossary\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_glossary", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateGlossary\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateGlossary\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "translation_service_pb2", ".", "CreateGlossaryRequest", "(", "parent", "=", "parent", ",", "glossary", "=", "glossary", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"parent\"", ",", "parent", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"create_glossary\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "translation_service_pb2", ".", "Glossary", ",", "metadata_type", "=", "translation_service_pb2", ".", "CreateGlossaryMetadata", ",", ")" ]
Creates a glossary and returns the long-running operation. Returns NOT\_FOUND, if the project doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> >>> # TODO: Initialize `glossary`: >>> glossary = {} >>> >>> response = client.create_glossary(parent, glossary) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project name. glossary (Union[dict, ~google.cloud.translate_v3beta1.types.Glossary]): Required. The glossary to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.translate_v3beta1.types.Glossary` 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.translate_v3beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "a", "glossary", "and", "returns", "the", "long", "-", "running", "operation", ".", "Returns", "NOT", "\\", "_FOUND", "if", "the", "project", "doesn", "t", "exist", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L646-L739
train
googleapis/google-cloud-python
translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py
TranslationServiceClient.delete_glossary
def delete_glossary( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns NOT\_FOUND, if the glossary doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> name = client.glossary_path('[PROJECT]', '[LOCATION]', '[GLOSSARY]') >>> >>> response = client.delete_glossary(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. The name of the glossary to delete. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.translate_v3beta1.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_glossary" not in self._inner_api_calls: self._inner_api_calls[ "delete_glossary" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_glossary, default_retry=self._method_configs["DeleteGlossary"].retry, default_timeout=self._method_configs["DeleteGlossary"].timeout, client_info=self._client_info, ) request = translation_service_pb2.DeleteGlossaryRequest(name=name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["delete_glossary"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, translation_service_pb2.DeleteGlossaryResponse, metadata_type=translation_service_pb2.DeleteGlossaryMetadata, )
python
def delete_glossary( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns NOT\_FOUND, if the glossary doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> name = client.glossary_path('[PROJECT]', '[LOCATION]', '[GLOSSARY]') >>> >>> response = client.delete_glossary(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. The name of the glossary to delete. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.translate_v3beta1.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_glossary" not in self._inner_api_calls: self._inner_api_calls[ "delete_glossary" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_glossary, default_retry=self._method_configs["DeleteGlossary"].retry, default_timeout=self._method_configs["DeleteGlossary"].timeout, client_info=self._client_info, ) request = translation_service_pb2.DeleteGlossaryRequest(name=name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["delete_glossary"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, translation_service_pb2.DeleteGlossaryResponse, metadata_type=translation_service_pb2.DeleteGlossaryMetadata, )
[ "def", "delete_glossary", "(", "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_glossary\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"delete_glossary\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "delete_glossary", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"DeleteGlossary\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"DeleteGlossary\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "translation_service_pb2", ".", "DeleteGlossaryRequest", "(", "name", "=", "name", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"name\"", ",", "name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"delete_glossary\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "translation_service_pb2", ".", "DeleteGlossaryResponse", ",", "metadata_type", "=", "translation_service_pb2", ".", "DeleteGlossaryMetadata", ",", ")" ]
Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns NOT\_FOUND, if the glossary doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> name = client.glossary_path('[PROJECT]', '[LOCATION]', '[GLOSSARY]') >>> >>> response = client.delete_glossary(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. The name of the glossary to delete. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.translate_v3beta1.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", "glossary", "or", "cancels", "glossary", "construction", "if", "the", "glossary", "isn", "t", "created", "yet", ".", "Returns", "NOT", "\\", "_FOUND", "if", "the", "glossary", "doesn", "t", "exist", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py#L916-L999
train
googleapis/google-cloud-python
monitoring/google/cloud/monitoring_v3/_dataframe.py
_extract_header
def _extract_header(time_series): """Return a copy of time_series with the points removed.""" return TimeSeries( metric=time_series.metric, resource=time_series.resource, metric_kind=time_series.metric_kind, value_type=time_series.value_type, )
python
def _extract_header(time_series): """Return a copy of time_series with the points removed.""" return TimeSeries( metric=time_series.metric, resource=time_series.resource, metric_kind=time_series.metric_kind, value_type=time_series.value_type, )
[ "def", "_extract_header", "(", "time_series", ")", ":", "return", "TimeSeries", "(", "metric", "=", "time_series", ".", "metric", ",", "resource", "=", "time_series", ".", "resource", ",", "metric_kind", "=", "time_series", ".", "metric_kind", ",", "value_type", "=", "time_series", ".", "value_type", ",", ")" ]
Return a copy of time_series with the points removed.
[ "Return", "a", "copy", "of", "time_series", "with", "the", "points", "removed", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/_dataframe.py#L29-L36
train
googleapis/google-cloud-python
monitoring/google/cloud/monitoring_v3/_dataframe.py
_extract_labels
def _extract_labels(time_series): """Build the combined resource and metric labels, with resource_type.""" labels = {"resource_type": time_series.resource.type} labels.update(time_series.resource.labels) labels.update(time_series.metric.labels) return labels
python
def _extract_labels(time_series): """Build the combined resource and metric labels, with resource_type.""" labels = {"resource_type": time_series.resource.type} labels.update(time_series.resource.labels) labels.update(time_series.metric.labels) return labels
[ "def", "_extract_labels", "(", "time_series", ")", ":", "labels", "=", "{", "\"resource_type\"", ":", "time_series", ".", "resource", ".", "type", "}", "labels", ".", "update", "(", "time_series", ".", "resource", ".", "labels", ")", "labels", ".", "update", "(", "time_series", ".", "metric", ".", "labels", ")", "return", "labels" ]
Build the combined resource and metric labels, with resource_type.
[ "Build", "the", "combined", "resource", "and", "metric", "labels", "with", "resource_type", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/_dataframe.py#L39-L44
train
googleapis/google-cloud-python
monitoring/google/cloud/monitoring_v3/_dataframe.py
_build_dataframe
def _build_dataframe(time_series_iterable, label=None, labels=None): # pragma: NO COVER """Build a :mod:`pandas` dataframe out of time series. :type time_series_iterable: iterable over :class:`~google.cloud.monitoring_v3.types.TimeSeries` :param time_series_iterable: An iterable (e.g., a query object) yielding time series. :type label: str :param label: (Optional) The label name to use for the dataframe header. This can be the name of a resource label or metric label (e.g., ``"instance_name"``), or the string ``"resource_type"``. :type labels: list of strings, or None :param labels: A list or tuple of label names to use for the dataframe header. If more than one label name is provided, the resulting dataframe will have a multi-level column header. Specifying neither ``label`` or ``labels`` results in a dataframe with a multi-level column header including the resource type and all available resource and metric labels. Specifying both ``label`` and ``labels`` is an error. :rtype: :class:`pandas.DataFrame` :returns: A dataframe where each column represents one time series. :raises: :exc:`RuntimeError` if `pandas` is not installed. """ if pandas is None: raise RuntimeError("This method requires `pandas` to be installed.") if label is not None: if labels: raise ValueError("Cannot specify both `label` and `labels`.") labels = (label,) columns = [] headers = [] for time_series in time_series_iterable: pandas_series = pandas.Series( data=[_extract_value(point.value) for point in time_series.points], index=[ point.interval.end_time.ToNanoseconds() for point in time_series.points ], ) columns.append(pandas_series) headers.append(_extract_header(time_series)) # Implement a smart default of using all available labels. if labels is None: resource_labels = set( itertools.chain.from_iterable(header.resource.labels for header in headers) ) metric_labels = set( itertools.chain.from_iterable(header.metric.labels for header in headers) ) labels = ( ["resource_type"] + _sorted_resource_labels(resource_labels) + sorted(metric_labels) ) # Assemble the columns into a DataFrame. dataframe = pandas.DataFrame.from_records(columns).T # Convert the timestamp strings into a DatetimeIndex. dataframe.index = pandas.to_datetime(dataframe.index) # Build a multi-level stack of column headers. Some labels may # be undefined for some time series. levels = [] for key in labels: level = [_extract_labels(header).get(key, "") for header in headers] levels.append(level) # Build a column Index or MultiIndex. Do not include level names # in the column header if the user requested a single-level header # by specifying "label". dataframe.columns = pandas.MultiIndex.from_arrays( levels, names=labels if not label else None ) # Sort the rows just in case (since the API doesn't guarantee the # ordering), and sort the columns lexicographically. return dataframe.sort_index(axis=0).sort_index(axis=1)
python
def _build_dataframe(time_series_iterable, label=None, labels=None): # pragma: NO COVER """Build a :mod:`pandas` dataframe out of time series. :type time_series_iterable: iterable over :class:`~google.cloud.monitoring_v3.types.TimeSeries` :param time_series_iterable: An iterable (e.g., a query object) yielding time series. :type label: str :param label: (Optional) The label name to use for the dataframe header. This can be the name of a resource label or metric label (e.g., ``"instance_name"``), or the string ``"resource_type"``. :type labels: list of strings, or None :param labels: A list or tuple of label names to use for the dataframe header. If more than one label name is provided, the resulting dataframe will have a multi-level column header. Specifying neither ``label`` or ``labels`` results in a dataframe with a multi-level column header including the resource type and all available resource and metric labels. Specifying both ``label`` and ``labels`` is an error. :rtype: :class:`pandas.DataFrame` :returns: A dataframe where each column represents one time series. :raises: :exc:`RuntimeError` if `pandas` is not installed. """ if pandas is None: raise RuntimeError("This method requires `pandas` to be installed.") if label is not None: if labels: raise ValueError("Cannot specify both `label` and `labels`.") labels = (label,) columns = [] headers = [] for time_series in time_series_iterable: pandas_series = pandas.Series( data=[_extract_value(point.value) for point in time_series.points], index=[ point.interval.end_time.ToNanoseconds() for point in time_series.points ], ) columns.append(pandas_series) headers.append(_extract_header(time_series)) # Implement a smart default of using all available labels. if labels is None: resource_labels = set( itertools.chain.from_iterable(header.resource.labels for header in headers) ) metric_labels = set( itertools.chain.from_iterable(header.metric.labels for header in headers) ) labels = ( ["resource_type"] + _sorted_resource_labels(resource_labels) + sorted(metric_labels) ) # Assemble the columns into a DataFrame. dataframe = pandas.DataFrame.from_records(columns).T # Convert the timestamp strings into a DatetimeIndex. dataframe.index = pandas.to_datetime(dataframe.index) # Build a multi-level stack of column headers. Some labels may # be undefined for some time series. levels = [] for key in labels: level = [_extract_labels(header).get(key, "") for header in headers] levels.append(level) # Build a column Index or MultiIndex. Do not include level names # in the column header if the user requested a single-level header # by specifying "label". dataframe.columns = pandas.MultiIndex.from_arrays( levels, names=labels if not label else None ) # Sort the rows just in case (since the API doesn't guarantee the # ordering), and sort the columns lexicographically. return dataframe.sort_index(axis=0).sort_index(axis=1)
[ "def", "_build_dataframe", "(", "time_series_iterable", ",", "label", "=", "None", ",", "labels", "=", "None", ")", ":", "# pragma: NO COVER", "if", "pandas", "is", "None", ":", "raise", "RuntimeError", "(", "\"This method requires `pandas` to be installed.\"", ")", "if", "label", "is", "not", "None", ":", "if", "labels", ":", "raise", "ValueError", "(", "\"Cannot specify both `label` and `labels`.\"", ")", "labels", "=", "(", "label", ",", ")", "columns", "=", "[", "]", "headers", "=", "[", "]", "for", "time_series", "in", "time_series_iterable", ":", "pandas_series", "=", "pandas", ".", "Series", "(", "data", "=", "[", "_extract_value", "(", "point", ".", "value", ")", "for", "point", "in", "time_series", ".", "points", "]", ",", "index", "=", "[", "point", ".", "interval", ".", "end_time", ".", "ToNanoseconds", "(", ")", "for", "point", "in", "time_series", ".", "points", "]", ",", ")", "columns", ".", "append", "(", "pandas_series", ")", "headers", ".", "append", "(", "_extract_header", "(", "time_series", ")", ")", "# Implement a smart default of using all available labels.", "if", "labels", "is", "None", ":", "resource_labels", "=", "set", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "header", ".", "resource", ".", "labels", "for", "header", "in", "headers", ")", ")", "metric_labels", "=", "set", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "header", ".", "metric", ".", "labels", "for", "header", "in", "headers", ")", ")", "labels", "=", "(", "[", "\"resource_type\"", "]", "+", "_sorted_resource_labels", "(", "resource_labels", ")", "+", "sorted", "(", "metric_labels", ")", ")", "# Assemble the columns into a DataFrame.", "dataframe", "=", "pandas", ".", "DataFrame", ".", "from_records", "(", "columns", ")", ".", "T", "# Convert the timestamp strings into a DatetimeIndex.", "dataframe", ".", "index", "=", "pandas", ".", "to_datetime", "(", "dataframe", ".", "index", ")", "# Build a multi-level stack of column headers. Some labels may", "# be undefined for some time series.", "levels", "=", "[", "]", "for", "key", "in", "labels", ":", "level", "=", "[", "_extract_labels", "(", "header", ")", ".", "get", "(", "key", ",", "\"\"", ")", "for", "header", "in", "headers", "]", "levels", ".", "append", "(", "level", ")", "# Build a column Index or MultiIndex. Do not include level names", "# in the column header if the user requested a single-level header", "# by specifying \"label\".", "dataframe", ".", "columns", "=", "pandas", ".", "MultiIndex", ".", "from_arrays", "(", "levels", ",", "names", "=", "labels", "if", "not", "label", "else", "None", ")", "# Sort the rows just in case (since the API doesn't guarantee the", "# ordering), and sort the columns lexicographically.", "return", "dataframe", ".", "sort_index", "(", "axis", "=", "0", ")", ".", "sort_index", "(", "axis", "=", "1", ")" ]
Build a :mod:`pandas` dataframe out of time series. :type time_series_iterable: iterable over :class:`~google.cloud.monitoring_v3.types.TimeSeries` :param time_series_iterable: An iterable (e.g., a query object) yielding time series. :type label: str :param label: (Optional) The label name to use for the dataframe header. This can be the name of a resource label or metric label (e.g., ``"instance_name"``), or the string ``"resource_type"``. :type labels: list of strings, or None :param labels: A list or tuple of label names to use for the dataframe header. If more than one label name is provided, the resulting dataframe will have a multi-level column header. Specifying neither ``label`` or ``labels`` results in a dataframe with a multi-level column header including the resource type and all available resource and metric labels. Specifying both ``label`` and ``labels`` is an error. :rtype: :class:`pandas.DataFrame` :returns: A dataframe where each column represents one time series. :raises: :exc:`RuntimeError` if `pandas` is not installed.
[ "Build", "a", ":", "mod", ":", "pandas", "dataframe", "out", "of", "time", "series", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/_dataframe.py#L53-L140
train
googleapis/google-cloud-python
monitoring/google/cloud/monitoring_v3/_dataframe.py
_sorted_resource_labels
def _sorted_resource_labels(labels): """Sort label names, putting well-known resource labels first.""" head = [label for label in TOP_RESOURCE_LABELS if label in labels] tail = sorted(label for label in labels if label not in TOP_RESOURCE_LABELS) return head + tail
python
def _sorted_resource_labels(labels): """Sort label names, putting well-known resource labels first.""" head = [label for label in TOP_RESOURCE_LABELS if label in labels] tail = sorted(label for label in labels if label not in TOP_RESOURCE_LABELS) return head + tail
[ "def", "_sorted_resource_labels", "(", "labels", ")", ":", "head", "=", "[", "label", "for", "label", "in", "TOP_RESOURCE_LABELS", "if", "label", "in", "labels", "]", "tail", "=", "sorted", "(", "label", "for", "label", "in", "labels", "if", "label", "not", "in", "TOP_RESOURCE_LABELS", ")", "return", "head", "+", "tail" ]
Sort label names, putting well-known resource labels first.
[ "Sort", "label", "names", "putting", "well", "-", "known", "resource", "labels", "first", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/_dataframe.py#L143-L147
train
googleapis/google-cloud-python
api_core/google/api_core/future/_helpers.py
start_daemon_thread
def start_daemon_thread(*args, **kwargs): """Starts a thread and marks it as a daemon thread.""" thread = threading.Thread(*args, **kwargs) thread.daemon = True thread.start() return thread
python
def start_daemon_thread(*args, **kwargs): """Starts a thread and marks it as a daemon thread.""" thread = threading.Thread(*args, **kwargs) thread.daemon = True thread.start() return thread
[ "def", "start_daemon_thread", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thread", "=", "threading", ".", "Thread", "(", "*", "args", ",", "*", "*", "kwargs", ")", "thread", ".", "daemon", "=", "True", "thread", ".", "start", "(", ")", "return", "thread" ]
Starts a thread and marks it as a daemon thread.
[ "Starts", "a", "thread", "and", "marks", "it", "as", "a", "daemon", "thread", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/future/_helpers.py#L24-L29
train
googleapis/google-cloud-python
api_core/google/api_core/future/_helpers.py
safe_invoke_callback
def safe_invoke_callback(callback, *args, **kwargs): """Invoke a callback, swallowing and logging any exceptions.""" # pylint: disable=bare-except # We intentionally want to swallow all exceptions. try: return callback(*args, **kwargs) except Exception: _LOGGER.exception("Error while executing Future callback.")
python
def safe_invoke_callback(callback, *args, **kwargs): """Invoke a callback, swallowing and logging any exceptions.""" # pylint: disable=bare-except # We intentionally want to swallow all exceptions. try: return callback(*args, **kwargs) except Exception: _LOGGER.exception("Error while executing Future callback.")
[ "def", "safe_invoke_callback", "(", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=bare-except", "# We intentionally want to swallow all exceptions.", "try", ":", "return", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "_LOGGER", ".", "exception", "(", "\"Error while executing Future callback.\"", ")" ]
Invoke a callback, swallowing and logging any exceptions.
[ "Invoke", "a", "callback", "swallowing", "and", "logging", "any", "exceptions", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/future/_helpers.py#L32-L39
train
googleapis/google-cloud-python
resource_manager/google/cloud/resource_manager/client.py
Client.new_project
def new_project(self, project_id, name=None, labels=None): """Create a project bound to the current client. Use :meth:`Project.reload() \ <google.cloud.resource_manager.project.Project.reload>` to retrieve project metadata after creating a :class:`~google.cloud.resource_manager.project.Project` instance. .. note: This does not make an API call. :type project_id: str :param project_id: The ID for this project. :type name: str :param name: The display name of the project. :type labels: dict :param labels: A list of labels associated with the project. :rtype: :class:`~google.cloud.resource_manager.project.Project` :returns: A new instance of a :class:`~google.cloud.resource_manager.project.Project` **without** any metadata loaded. """ return Project(project_id=project_id, client=self, name=name, labels=labels)
python
def new_project(self, project_id, name=None, labels=None): """Create a project bound to the current client. Use :meth:`Project.reload() \ <google.cloud.resource_manager.project.Project.reload>` to retrieve project metadata after creating a :class:`~google.cloud.resource_manager.project.Project` instance. .. note: This does not make an API call. :type project_id: str :param project_id: The ID for this project. :type name: str :param name: The display name of the project. :type labels: dict :param labels: A list of labels associated with the project. :rtype: :class:`~google.cloud.resource_manager.project.Project` :returns: A new instance of a :class:`~google.cloud.resource_manager.project.Project` **without** any metadata loaded. """ return Project(project_id=project_id, client=self, name=name, labels=labels)
[ "def", "new_project", "(", "self", ",", "project_id", ",", "name", "=", "None", ",", "labels", "=", "None", ")", ":", "return", "Project", "(", "project_id", "=", "project_id", ",", "client", "=", "self", ",", "name", "=", "name", ",", "labels", "=", "labels", ")" ]
Create a project bound to the current client. Use :meth:`Project.reload() \ <google.cloud.resource_manager.project.Project.reload>` to retrieve project metadata after creating a :class:`~google.cloud.resource_manager.project.Project` instance. .. note: This does not make an API call. :type project_id: str :param project_id: The ID for this project. :type name: str :param name: The display name of the project. :type labels: dict :param labels: A list of labels associated with the project. :rtype: :class:`~google.cloud.resource_manager.project.Project` :returns: A new instance of a :class:`~google.cloud.resource_manager.project.Project` **without** any metadata loaded.
[ "Create", "a", "project", "bound", "to", "the", "current", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/resource_manager/google/cloud/resource_manager/client.py#L61-L87
train
googleapis/google-cloud-python
resource_manager/google/cloud/resource_manager/client.py
Client.fetch_project
def fetch_project(self, project_id): """Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: The ID for this project. :rtype: :class:`~google.cloud.resource_manager.project.Project` :returns: A :class:`~google.cloud.resource_manager.project.Project` with metadata fetched from the API. """ project = self.new_project(project_id) project.reload() return project
python
def fetch_project(self, project_id): """Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: The ID for this project. :rtype: :class:`~google.cloud.resource_manager.project.Project` :returns: A :class:`~google.cloud.resource_manager.project.Project` with metadata fetched from the API. """ project = self.new_project(project_id) project.reload() return project
[ "def", "fetch_project", "(", "self", ",", "project_id", ")", ":", "project", "=", "self", ".", "new_project", "(", "project_id", ")", "project", ".", "reload", "(", ")", "return", "project" ]
Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: The ID for this project. :rtype: :class:`~google.cloud.resource_manager.project.Project` :returns: A :class:`~google.cloud.resource_manager.project.Project` with metadata fetched from the API.
[ "Fetch", "an", "existing", "project", "and", "it", "s", "relevant", "metadata", "by", "ID", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/resource_manager/google/cloud/resource_manager/client.py#L89-L106
train
googleapis/google-cloud-python
resource_manager/google/cloud/resource_manager/client.py
Client.list_projects
def list_projects(self, filter_params=None, page_size=None): """List the projects visible to this client. Example:: >>> from google.cloud import resource_manager >>> client = resource_manager.Client() >>> for project in client.list_projects(): ... print(project.project_id) List all projects with label ``'environment'`` set to ``'prod'`` (filtering by labels):: >>> from google.cloud import resource_manager >>> client = resource_manager.Client() >>> env_filter = {'labels.environment': 'prod'} >>> for project in client.list_projects(env_filter): ... print(project.project_id) See https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/list Complete filtering example:: >>> project_filter = { # Return projects with... ... 'name': 'My Project', # name set to 'My Project'. ... 'id': 'my-project-id', # id set to 'my-project-id'. ... 'labels.stage': 'prod', # the label 'stage' set to 'prod' ... 'labels.color': '*' # a label 'color' set to anything. ... } >>> client.list_projects(project_filter) :type filter_params: dict :param filter_params: (Optional) A dictionary of filter options where each key is a property to filter on, and each value is the (case-insensitive) value to check (or the glob ``*`` to check for existence of the property). See the example above for more details. :type page_size: int :param page_size: (Optional) The maximum number of projects in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of all :class:`~google.cloud.resource_manager.project.Project`. that the current user has access to. """ extra_params = {} if page_size is not None: extra_params["pageSize"] = page_size if filter_params is not None: extra_params["filter"] = [ "{}:{}".format(key, value) for key, value in six.iteritems(filter_params) ] return page_iterator.HTTPIterator( client=self, api_request=self._connection.api_request, path="/projects", item_to_value=_item_to_project, items_key="projects", extra_params=extra_params, )
python
def list_projects(self, filter_params=None, page_size=None): """List the projects visible to this client. Example:: >>> from google.cloud import resource_manager >>> client = resource_manager.Client() >>> for project in client.list_projects(): ... print(project.project_id) List all projects with label ``'environment'`` set to ``'prod'`` (filtering by labels):: >>> from google.cloud import resource_manager >>> client = resource_manager.Client() >>> env_filter = {'labels.environment': 'prod'} >>> for project in client.list_projects(env_filter): ... print(project.project_id) See https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/list Complete filtering example:: >>> project_filter = { # Return projects with... ... 'name': 'My Project', # name set to 'My Project'. ... 'id': 'my-project-id', # id set to 'my-project-id'. ... 'labels.stage': 'prod', # the label 'stage' set to 'prod' ... 'labels.color': '*' # a label 'color' set to anything. ... } >>> client.list_projects(project_filter) :type filter_params: dict :param filter_params: (Optional) A dictionary of filter options where each key is a property to filter on, and each value is the (case-insensitive) value to check (or the glob ``*`` to check for existence of the property). See the example above for more details. :type page_size: int :param page_size: (Optional) The maximum number of projects in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of all :class:`~google.cloud.resource_manager.project.Project`. that the current user has access to. """ extra_params = {} if page_size is not None: extra_params["pageSize"] = page_size if filter_params is not None: extra_params["filter"] = [ "{}:{}".format(key, value) for key, value in six.iteritems(filter_params) ] return page_iterator.HTTPIterator( client=self, api_request=self._connection.api_request, path="/projects", item_to_value=_item_to_project, items_key="projects", extra_params=extra_params, )
[ "def", "list_projects", "(", "self", ",", "filter_params", "=", "None", ",", "page_size", "=", "None", ")", ":", "extra_params", "=", "{", "}", "if", "page_size", "is", "not", "None", ":", "extra_params", "[", "\"pageSize\"", "]", "=", "page_size", "if", "filter_params", "is", "not", "None", ":", "extra_params", "[", "\"filter\"", "]", "=", "[", "\"{}:{}\"", ".", "format", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "filter_params", ")", "]", "return", "page_iterator", ".", "HTTPIterator", "(", "client", "=", "self", ",", "api_request", "=", "self", ".", "_connection", ".", "api_request", ",", "path", "=", "\"/projects\"", ",", "item_to_value", "=", "_item_to_project", ",", "items_key", "=", "\"projects\"", ",", "extra_params", "=", "extra_params", ",", ")" ]
List the projects visible to this client. Example:: >>> from google.cloud import resource_manager >>> client = resource_manager.Client() >>> for project in client.list_projects(): ... print(project.project_id) List all projects with label ``'environment'`` set to ``'prod'`` (filtering by labels):: >>> from google.cloud import resource_manager >>> client = resource_manager.Client() >>> env_filter = {'labels.environment': 'prod'} >>> for project in client.list_projects(env_filter): ... print(project.project_id) See https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/list Complete filtering example:: >>> project_filter = { # Return projects with... ... 'name': 'My Project', # name set to 'My Project'. ... 'id': 'my-project-id', # id set to 'my-project-id'. ... 'labels.stage': 'prod', # the label 'stage' set to 'prod' ... 'labels.color': '*' # a label 'color' set to anything. ... } >>> client.list_projects(project_filter) :type filter_params: dict :param filter_params: (Optional) A dictionary of filter options where each key is a property to filter on, and each value is the (case-insensitive) value to check (or the glob ``*`` to check for existence of the property). See the example above for more details. :type page_size: int :param page_size: (Optional) The maximum number of projects in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of all :class:`~google.cloud.resource_manager.project.Project`. that the current user has access to.
[ "List", "the", "projects", "visible", "to", "this", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/resource_manager/google/cloud/resource_manager/client.py#L108-L177
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/gapic/spanner_client.py
SpannerClient.session_path
def session_path(cls, project, instance, database, session): """Return a fully-qualified session string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/databases/{database}/sessions/{session}", project=project, instance=instance, database=database, session=session, )
python
def session_path(cls, project, instance, database, session): """Return a fully-qualified session string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/databases/{database}/sessions/{session}", project=project, instance=instance, database=database, session=session, )
[ "def", "session_path", "(", "cls", ",", "project", ",", "instance", ",", "database", ",", "session", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/instances/{instance}/databases/{database}/sessions/{session}\"", ",", "project", "=", "project", ",", "instance", "=", "instance", ",", "database", "=", "database", ",", "session", "=", "session", ",", ")" ]
Return a fully-qualified session string.
[ "Return", "a", "fully", "-", "qualified", "session", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L94-L102
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/gapic/spanner_client.py
SpannerClient.create_session
def create_session( self, database, session=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions. Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit. Cloud Spanner limits the number of sessions that can exist at any given time; thus, it is a good idea to delete idle and/or unneeded sessions. Aside from explicit deletes, Cloud Spanner can delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return ``NOT_FOUND``. Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., ``"SELECT 1"``. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') >>> >>> response = client.create_session(database) Args: database (str): Required. The database in which the new session is created. session (Union[dict, ~google.cloud.spanner_v1.types.Session]): The session to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Session` 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.spanner_v1.types.Session` 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_session" not in self._inner_api_calls: self._inner_api_calls[ "create_session" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_session, default_retry=self._method_configs["CreateSession"].retry, default_timeout=self._method_configs["CreateSession"].timeout, client_info=self._client_info, ) request = spanner_pb2.CreateSessionRequest(database=database, session=session) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("database", database)] 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_session"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_session( self, database, session=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions. Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit. Cloud Spanner limits the number of sessions that can exist at any given time; thus, it is a good idea to delete idle and/or unneeded sessions. Aside from explicit deletes, Cloud Spanner can delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return ``NOT_FOUND``. Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., ``"SELECT 1"``. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') >>> >>> response = client.create_session(database) Args: database (str): Required. The database in which the new session is created. session (Union[dict, ~google.cloud.spanner_v1.types.Session]): The session to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Session` 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.spanner_v1.types.Session` 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_session" not in self._inner_api_calls: self._inner_api_calls[ "create_session" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_session, default_retry=self._method_configs["CreateSession"].retry, default_timeout=self._method_configs["CreateSession"].timeout, client_info=self._client_info, ) request = spanner_pb2.CreateSessionRequest(database=database, session=session) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("database", database)] 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_session"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_session", "(", "self", ",", "database", ",", "session", "=", "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_session\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_session\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_session", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateSession\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateSession\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "spanner_pb2", ".", "CreateSessionRequest", "(", "database", "=", "database", ",", "session", "=", "session", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"database\"", ",", "database", ")", "]", "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_session\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions. Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit. Cloud Spanner limits the number of sessions that can exist at any given time; thus, it is a good idea to delete idle and/or unneeded sessions. Aside from explicit deletes, Cloud Spanner can delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return ``NOT_FOUND``. Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., ``"SELECT 1"``. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') >>> >>> response = client.create_session(database) Args: database (str): Required. The database in which the new session is created. session (Union[dict, ~google.cloud.spanner_v1.types.Session]): The session to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Session` 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.spanner_v1.types.Session` 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", "session", ".", "A", "session", "can", "be", "used", "to", "perform", "transactions", "that", "read", "and", "/", "or", "modify", "data", "in", "a", "Cloud", "Spanner", "database", ".", "Sessions", "are", "meant", "to", "be", "reused", "for", "many", "consecutive", "transactions", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L203-L291
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/gapic/spanner_client.py
SpannerClient.execute_streaming_sql
def execute_streaming_sql( self, session, sql, transaction=None, params=None, param_types=None, resume_token=None, query_mode=None, partition_token=None, seqno=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Like ``ExecuteSql``, except returns the result set as a stream. Unlike ``ExecuteSql``, there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `sql`: >>> sql = '' >>> >>> for element in client.execute_streaming_sql(session, sql): ... # process element ... pass Args: session (str): Required. The session in which the SQL query should be performed. sql (str): Required. The SQL string. transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a temporary read-only transaction with strong concurrency. The transaction to use. For queries, if none is provided, the default is a temporary read-only transaction with strong concurrency. Standard DML statements require a ReadWrite transaction. Single-use transactions are not supported (to avoid replay). The caller must either supply an existing transaction ID or begin a new transaction. Partitioned DML requires an existing PartitionedDml transaction ID. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL string can contain parameter placeholders. A parameter placeholder consists of ``'@'`` followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores. Parameters can appear anywhere that a literal value is expected. The same parameter name can be used more than once, for example: ``"WHERE id > @msg_id AND id < @msg_id + 100"`` It is an error to execute an SQL statement with unbound parameters. Parameter values are specified using ``params``, which is a JSON object whose keys are parameter names, and whose values are the corresponding parameter values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Struct` param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type from a JSON value. For example, values of type ``BYTES`` and values of type ``STRING`` both appear in ``params`` as JSON strings. In these cases, ``param_types`` can be used to specify the exact SQL type for some or all of the SQL statement parameters. See the definition of ``Type`` for more information about SQL types. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Type` resume_token (bytes): If this request is resuming a previously interrupted SQL statement execution, ``resume_token`` should be copied from the last ``PartialResultSet`` yielded before the interruption. Doing this enables the new SQL statement execution to resume where the last one left off. The rest of the request parameters must exactly match the request that yielded this token. query_mode (~google.cloud.spanner_v1.types.QueryMode): Used to control the amount of debugging information returned in ``ResultSetStats``. If ``partition_token`` is set, ``query_mode`` can only be set to ``QueryMode.NORMAL``. partition_token (bytes): If present, results will be restricted to the specified partition previously created using PartitionQuery(). There must be an exact match for the values of fields common to this message and the PartitionQueryRequest message used to create this partition\_token. seqno (long): A per-transaction sequence number used to identify this request. This makes each request idempotent such that if the request is received multiple times, at most one will succeed. The sequence number must be monotonically increasing within the transaction. If a request arrives for the first time with an out-of-order sequence number, the transaction may be aborted. Replays of previously handled requests will yield the same response as the first execution. Required for DML statements. Ignored for queries. 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: Iterable[~google.cloud.spanner_v1.types.PartialResultSet]. 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 "execute_streaming_sql" not in self._inner_api_calls: self._inner_api_calls[ "execute_streaming_sql" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.execute_streaming_sql, default_retry=self._method_configs["ExecuteStreamingSql"].retry, default_timeout=self._method_configs["ExecuteStreamingSql"].timeout, client_info=self._client_info, ) request = spanner_pb2.ExecuteSqlRequest( session=session, sql=sql, transaction=transaction, params=params, param_types=param_types, resume_token=resume_token, query_mode=query_mode, partition_token=partition_token, seqno=seqno, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["execute_streaming_sql"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def execute_streaming_sql( self, session, sql, transaction=None, params=None, param_types=None, resume_token=None, query_mode=None, partition_token=None, seqno=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Like ``ExecuteSql``, except returns the result set as a stream. Unlike ``ExecuteSql``, there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `sql`: >>> sql = '' >>> >>> for element in client.execute_streaming_sql(session, sql): ... # process element ... pass Args: session (str): Required. The session in which the SQL query should be performed. sql (str): Required. The SQL string. transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a temporary read-only transaction with strong concurrency. The transaction to use. For queries, if none is provided, the default is a temporary read-only transaction with strong concurrency. Standard DML statements require a ReadWrite transaction. Single-use transactions are not supported (to avoid replay). The caller must either supply an existing transaction ID or begin a new transaction. Partitioned DML requires an existing PartitionedDml transaction ID. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL string can contain parameter placeholders. A parameter placeholder consists of ``'@'`` followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores. Parameters can appear anywhere that a literal value is expected. The same parameter name can be used more than once, for example: ``"WHERE id > @msg_id AND id < @msg_id + 100"`` It is an error to execute an SQL statement with unbound parameters. Parameter values are specified using ``params``, which is a JSON object whose keys are parameter names, and whose values are the corresponding parameter values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Struct` param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type from a JSON value. For example, values of type ``BYTES`` and values of type ``STRING`` both appear in ``params`` as JSON strings. In these cases, ``param_types`` can be used to specify the exact SQL type for some or all of the SQL statement parameters. See the definition of ``Type`` for more information about SQL types. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Type` resume_token (bytes): If this request is resuming a previously interrupted SQL statement execution, ``resume_token`` should be copied from the last ``PartialResultSet`` yielded before the interruption. Doing this enables the new SQL statement execution to resume where the last one left off. The rest of the request parameters must exactly match the request that yielded this token. query_mode (~google.cloud.spanner_v1.types.QueryMode): Used to control the amount of debugging information returned in ``ResultSetStats``. If ``partition_token`` is set, ``query_mode`` can only be set to ``QueryMode.NORMAL``. partition_token (bytes): If present, results will be restricted to the specified partition previously created using PartitionQuery(). There must be an exact match for the values of fields common to this message and the PartitionQueryRequest message used to create this partition\_token. seqno (long): A per-transaction sequence number used to identify this request. This makes each request idempotent such that if the request is received multiple times, at most one will succeed. The sequence number must be monotonically increasing within the transaction. If a request arrives for the first time with an out-of-order sequence number, the transaction may be aborted. Replays of previously handled requests will yield the same response as the first execution. Required for DML statements. Ignored for queries. 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: Iterable[~google.cloud.spanner_v1.types.PartialResultSet]. 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 "execute_streaming_sql" not in self._inner_api_calls: self._inner_api_calls[ "execute_streaming_sql" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.execute_streaming_sql, default_retry=self._method_configs["ExecuteStreamingSql"].retry, default_timeout=self._method_configs["ExecuteStreamingSql"].timeout, client_info=self._client_info, ) request = spanner_pb2.ExecuteSqlRequest( session=session, sql=sql, transaction=transaction, params=params, param_types=param_types, resume_token=resume_token, query_mode=query_mode, partition_token=partition_token, seqno=seqno, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["execute_streaming_sql"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "execute_streaming_sql", "(", "self", ",", "session", ",", "sql", ",", "transaction", "=", "None", ",", "params", "=", "None", ",", "param_types", "=", "None", ",", "resume_token", "=", "None", ",", "query_mode", "=", "None", ",", "partition_token", "=", "None", ",", "seqno", "=", "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", "\"execute_streaming_sql\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"execute_streaming_sql\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "execute_streaming_sql", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"ExecuteStreamingSql\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"ExecuteStreamingSql\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "spanner_pb2", ".", "ExecuteSqlRequest", "(", "session", "=", "session", ",", "sql", "=", "sql", ",", "transaction", "=", "transaction", ",", "params", "=", "params", ",", "param_types", "=", "param_types", ",", "resume_token", "=", "resume_token", ",", "query_mode", "=", "query_mode", ",", "partition_token", "=", "partition_token", ",", "seqno", "=", "seqno", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"session\"", ",", "session", ")", "]", "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", "[", "\"execute_streaming_sql\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Like ``ExecuteSql``, except returns the result set as a stream. Unlike ``ExecuteSql``, there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `sql`: >>> sql = '' >>> >>> for element in client.execute_streaming_sql(session, sql): ... # process element ... pass Args: session (str): Required. The session in which the SQL query should be performed. sql (str): Required. The SQL string. transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a temporary read-only transaction with strong concurrency. The transaction to use. For queries, if none is provided, the default is a temporary read-only transaction with strong concurrency. Standard DML statements require a ReadWrite transaction. Single-use transactions are not supported (to avoid replay). The caller must either supply an existing transaction ID or begin a new transaction. Partitioned DML requires an existing PartitionedDml transaction ID. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL string can contain parameter placeholders. A parameter placeholder consists of ``'@'`` followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores. Parameters can appear anywhere that a literal value is expected. The same parameter name can be used more than once, for example: ``"WHERE id > @msg_id AND id < @msg_id + 100"`` It is an error to execute an SQL statement with unbound parameters. Parameter values are specified using ``params``, which is a JSON object whose keys are parameter names, and whose values are the corresponding parameter values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Struct` param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type from a JSON value. For example, values of type ``BYTES`` and values of type ``STRING`` both appear in ``params`` as JSON strings. In these cases, ``param_types`` can be used to specify the exact SQL type for some or all of the SQL statement parameters. See the definition of ``Type`` for more information about SQL types. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Type` resume_token (bytes): If this request is resuming a previously interrupted SQL statement execution, ``resume_token`` should be copied from the last ``PartialResultSet`` yielded before the interruption. Doing this enables the new SQL statement execution to resume where the last one left off. The rest of the request parameters must exactly match the request that yielded this token. query_mode (~google.cloud.spanner_v1.types.QueryMode): Used to control the amount of debugging information returned in ``ResultSetStats``. If ``partition_token`` is set, ``query_mode`` can only be set to ``QueryMode.NORMAL``. partition_token (bytes): If present, results will be restricted to the specified partition previously created using PartitionQuery(). There must be an exact match for the values of fields common to this message and the PartitionQueryRequest message used to create this partition\_token. seqno (long): A per-transaction sequence number used to identify this request. This makes each request idempotent such that if the request is received multiple times, at most one will succeed. The sequence number must be monotonically increasing within the transaction. If a request arrives for the first time with an out-of-order sequence number, the transaction may be aborted. Replays of previously handled requests will yield the same response as the first execution. Required for DML statements. Ignored for queries. 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: Iterable[~google.cloud.spanner_v1.types.PartialResultSet]. 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.
[ "Like", "ExecuteSql", "except", "returns", "the", "result", "set", "as", "a", "stream", ".", "Unlike", "ExecuteSql", "there", "is", "no", "limit", "on", "the", "size", "of", "the", "returned", "result", "set", ".", "However", "no", "individual", "row", "in", "the", "result", "set", "can", "exceed", "100", "MiB", "and", "no", "column", "value", "can", "exceed", "10", "MiB", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L712-L872
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/gapic/spanner_client.py
SpannerClient.execute_batch_dml
def execute_batch_dml( self, session, transaction, statements, seqno, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Executes a batch of SQL DML statements. This method allows many statements to be run with lower latency than submitting them sequentially with ``ExecuteSql``. Statements are executed in order, sequentially. ``ExecuteBatchDmlResponse`` will contain a ``ResultSet`` for each DML statement that has successfully executed. If a statement fails, its error status will be returned as part of the ``ExecuteBatchDmlResponse``. Execution will stop at the first failed statement; the remaining statements will not run. ExecuteBatchDml is expected to return an OK status with a response even if there was an error while processing one of the DML statements. Clients must inspect response.status to determine if there were any errors while processing the request. See more details in ``ExecuteBatchDmlRequest`` and ``ExecuteBatchDmlResponse``. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `transaction`: >>> transaction = {} >>> >>> # TODO: Initialize `statements`: >>> statements = [] >>> >>> # TODO: Initialize `seqno`: >>> seqno = 0 >>> >>> response = client.execute_batch_dml(session, transaction, statements, seqno) Args: session (str): Required. The session in which the DML statements should be performed. transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. A ReadWrite transaction is required. Single-use transactions are not supported (to avoid replay). The caller must either supply an existing transaction ID or begin a new transaction. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` statements (list[Union[dict, ~google.cloud.spanner_v1.types.Statement]]): The list of statements to execute in this batch. Statements are executed serially, such that the effects of statement i are visible to statement i+1. Each statement must be a DML statement. Execution will stop at the first failed statement; the remaining statements will not run. REQUIRES: statements\_size() > 0. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Statement` seqno (long): A per-transaction sequence number used to identify this request. This is used in the same space as the seqno in ``ExecuteSqlRequest``. See more details in ``ExecuteSqlRequest``. 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.spanner_v1.types.ExecuteBatchDmlResponse` 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 "execute_batch_dml" not in self._inner_api_calls: self._inner_api_calls[ "execute_batch_dml" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.execute_batch_dml, default_retry=self._method_configs["ExecuteBatchDml"].retry, default_timeout=self._method_configs["ExecuteBatchDml"].timeout, client_info=self._client_info, ) request = spanner_pb2.ExecuteBatchDmlRequest( session=session, transaction=transaction, statements=statements, seqno=seqno ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["execute_batch_dml"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def execute_batch_dml( self, session, transaction, statements, seqno, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Executes a batch of SQL DML statements. This method allows many statements to be run with lower latency than submitting them sequentially with ``ExecuteSql``. Statements are executed in order, sequentially. ``ExecuteBatchDmlResponse`` will contain a ``ResultSet`` for each DML statement that has successfully executed. If a statement fails, its error status will be returned as part of the ``ExecuteBatchDmlResponse``. Execution will stop at the first failed statement; the remaining statements will not run. ExecuteBatchDml is expected to return an OK status with a response even if there was an error while processing one of the DML statements. Clients must inspect response.status to determine if there were any errors while processing the request. See more details in ``ExecuteBatchDmlRequest`` and ``ExecuteBatchDmlResponse``. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `transaction`: >>> transaction = {} >>> >>> # TODO: Initialize `statements`: >>> statements = [] >>> >>> # TODO: Initialize `seqno`: >>> seqno = 0 >>> >>> response = client.execute_batch_dml(session, transaction, statements, seqno) Args: session (str): Required. The session in which the DML statements should be performed. transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. A ReadWrite transaction is required. Single-use transactions are not supported (to avoid replay). The caller must either supply an existing transaction ID or begin a new transaction. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` statements (list[Union[dict, ~google.cloud.spanner_v1.types.Statement]]): The list of statements to execute in this batch. Statements are executed serially, such that the effects of statement i are visible to statement i+1. Each statement must be a DML statement. Execution will stop at the first failed statement; the remaining statements will not run. REQUIRES: statements\_size() > 0. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Statement` seqno (long): A per-transaction sequence number used to identify this request. This is used in the same space as the seqno in ``ExecuteSqlRequest``. See more details in ``ExecuteSqlRequest``. 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.spanner_v1.types.ExecuteBatchDmlResponse` 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 "execute_batch_dml" not in self._inner_api_calls: self._inner_api_calls[ "execute_batch_dml" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.execute_batch_dml, default_retry=self._method_configs["ExecuteBatchDml"].retry, default_timeout=self._method_configs["ExecuteBatchDml"].timeout, client_info=self._client_info, ) request = spanner_pb2.ExecuteBatchDmlRequest( session=session, transaction=transaction, statements=statements, seqno=seqno ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["execute_batch_dml"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "execute_batch_dml", "(", "self", ",", "session", ",", "transaction", ",", "statements", ",", "seqno", ",", "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", "\"execute_batch_dml\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"execute_batch_dml\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "execute_batch_dml", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"ExecuteBatchDml\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"ExecuteBatchDml\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "spanner_pb2", ".", "ExecuteBatchDmlRequest", "(", "session", "=", "session", ",", "transaction", "=", "transaction", ",", "statements", "=", "statements", ",", "seqno", "=", "seqno", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"session\"", ",", "session", ")", "]", "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", "[", "\"execute_batch_dml\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Executes a batch of SQL DML statements. This method allows many statements to be run with lower latency than submitting them sequentially with ``ExecuteSql``. Statements are executed in order, sequentially. ``ExecuteBatchDmlResponse`` will contain a ``ResultSet`` for each DML statement that has successfully executed. If a statement fails, its error status will be returned as part of the ``ExecuteBatchDmlResponse``. Execution will stop at the first failed statement; the remaining statements will not run. ExecuteBatchDml is expected to return an OK status with a response even if there was an error while processing one of the DML statements. Clients must inspect response.status to determine if there were any errors while processing the request. See more details in ``ExecuteBatchDmlRequest`` and ``ExecuteBatchDmlResponse``. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `transaction`: >>> transaction = {} >>> >>> # TODO: Initialize `statements`: >>> statements = [] >>> >>> # TODO: Initialize `seqno`: >>> seqno = 0 >>> >>> response = client.execute_batch_dml(session, transaction, statements, seqno) Args: session (str): Required. The session in which the DML statements should be performed. transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. A ReadWrite transaction is required. Single-use transactions are not supported (to avoid replay). The caller must either supply an existing transaction ID or begin a new transaction. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` statements (list[Union[dict, ~google.cloud.spanner_v1.types.Statement]]): The list of statements to execute in this batch. Statements are executed serially, such that the effects of statement i are visible to statement i+1. Each statement must be a DML statement. Execution will stop at the first failed statement; the remaining statements will not run. REQUIRES: statements\_size() > 0. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Statement` seqno (long): A per-transaction sequence number used to identify this request. This is used in the same space as the seqno in ``ExecuteSqlRequest``. See more details in ``ExecuteSqlRequest``. 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.spanner_v1.types.ExecuteBatchDmlResponse` 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.
[ "Executes", "a", "batch", "of", "SQL", "DML", "statements", ".", "This", "method", "allows", "many", "statements", "to", "be", "run", "with", "lower", "latency", "than", "submitting", "them", "sequentially", "with", "ExecuteSql", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L874-L990
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/gapic/spanner_client.py
SpannerClient.read
def read( self, session, table, columns, key_set, transaction=None, index=None, limit=None, resume_token=None, partition_token=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ``ExecuteSql``. This method cannot be used to return a result set larger than 10 MiB; if the read matches more data than that, the read fails with a ``FAILED_PRECONDITION`` error. Reads inside read-write transactions might return ``ABORTED``. If this occurs, the application should restart the transaction from the beginning. See ``Transaction`` for more details. Larger result sets can be yielded in streaming fashion by calling ``StreamingRead`` instead. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `table`: >>> table = '' >>> >>> # TODO: Initialize `columns`: >>> columns = [] >>> >>> # TODO: Initialize `key_set`: >>> key_set = {} >>> >>> response = client.read(session, table, columns, key_set) Args: session (str): Required. The session in which the read should be performed. table (str): Required. The name of the table in the database to be read. columns (list[str]): The columns of ``table`` to be returned for each row matching this request. key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set`` names the primary keys of the rows in ``table`` to be yielded, unless ``index`` is present. If ``index`` is present, then ``key_set`` instead names index keys in ``index``. If the ``partition_token`` field is empty, rows are yielded in table primary key order (if ``index`` is empty) or index key order (if ``index`` is non-empty). If the ``partition_token`` field is not empty, rows will be yielded in an unspecified order. It is not an error for the ``key_set`` to name rows that do not exist in the database. Read yields nothing for nonexistent rows. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.KeySet` transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a temporary read-only transaction with strong concurrency. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` index (str): If non-empty, the name of an index on ``table``. This index is used instead of the table primary key when interpreting ``key_set`` and sorting result rows. See ``key_set`` for further information. limit (long): If greater than zero, only the first ``limit`` rows are yielded. If ``limit`` is zero, the default is no limit. A limit cannot be specified if ``partition_token`` is set. resume_token (bytes): If this request is resuming a previously interrupted read, ``resume_token`` should be copied from the last ``PartialResultSet`` yielded before the interruption. Doing this enables the new read to resume where the last read left off. The rest of the request parameters must exactly match the request that yielded this token. partition_token (bytes): If present, results will be restricted to the specified partition previously created using PartitionRead(). There must be an exact match for the values of fields common to this message and the PartitionReadRequest message used to create this partition\_token. 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.spanner_v1.types.ResultSet` 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 "read" not in self._inner_api_calls: self._inner_api_calls["read"] = google.api_core.gapic_v1.method.wrap_method( self.transport.read, default_retry=self._method_configs["Read"].retry, default_timeout=self._method_configs["Read"].timeout, client_info=self._client_info, ) request = spanner_pb2.ReadRequest( session=session, table=table, columns=columns, key_set=key_set, transaction=transaction, index=index, limit=limit, resume_token=resume_token, partition_token=partition_token, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["read"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def read( self, session, table, columns, key_set, transaction=None, index=None, limit=None, resume_token=None, partition_token=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ``ExecuteSql``. This method cannot be used to return a result set larger than 10 MiB; if the read matches more data than that, the read fails with a ``FAILED_PRECONDITION`` error. Reads inside read-write transactions might return ``ABORTED``. If this occurs, the application should restart the transaction from the beginning. See ``Transaction`` for more details. Larger result sets can be yielded in streaming fashion by calling ``StreamingRead`` instead. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `table`: >>> table = '' >>> >>> # TODO: Initialize `columns`: >>> columns = [] >>> >>> # TODO: Initialize `key_set`: >>> key_set = {} >>> >>> response = client.read(session, table, columns, key_set) Args: session (str): Required. The session in which the read should be performed. table (str): Required. The name of the table in the database to be read. columns (list[str]): The columns of ``table`` to be returned for each row matching this request. key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set`` names the primary keys of the rows in ``table`` to be yielded, unless ``index`` is present. If ``index`` is present, then ``key_set`` instead names index keys in ``index``. If the ``partition_token`` field is empty, rows are yielded in table primary key order (if ``index`` is empty) or index key order (if ``index`` is non-empty). If the ``partition_token`` field is not empty, rows will be yielded in an unspecified order. It is not an error for the ``key_set`` to name rows that do not exist in the database. Read yields nothing for nonexistent rows. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.KeySet` transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a temporary read-only transaction with strong concurrency. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` index (str): If non-empty, the name of an index on ``table``. This index is used instead of the table primary key when interpreting ``key_set`` and sorting result rows. See ``key_set`` for further information. limit (long): If greater than zero, only the first ``limit`` rows are yielded. If ``limit`` is zero, the default is no limit. A limit cannot be specified if ``partition_token`` is set. resume_token (bytes): If this request is resuming a previously interrupted read, ``resume_token`` should be copied from the last ``PartialResultSet`` yielded before the interruption. Doing this enables the new read to resume where the last read left off. The rest of the request parameters must exactly match the request that yielded this token. partition_token (bytes): If present, results will be restricted to the specified partition previously created using PartitionRead(). There must be an exact match for the values of fields common to this message and the PartitionReadRequest message used to create this partition\_token. 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.spanner_v1.types.ResultSet` 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 "read" not in self._inner_api_calls: self._inner_api_calls["read"] = google.api_core.gapic_v1.method.wrap_method( self.transport.read, default_retry=self._method_configs["Read"].retry, default_timeout=self._method_configs["Read"].timeout, client_info=self._client_info, ) request = spanner_pb2.ReadRequest( session=session, table=table, columns=columns, key_set=key_set, transaction=transaction, index=index, limit=limit, resume_token=resume_token, partition_token=partition_token, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["read"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "read", "(", "self", ",", "session", ",", "table", ",", "columns", ",", "key_set", ",", "transaction", "=", "None", ",", "index", "=", "None", ",", "limit", "=", "None", ",", "resume_token", "=", "None", ",", "partition_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", "\"read\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"read\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "read", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"Read\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"Read\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "spanner_pb2", ".", "ReadRequest", "(", "session", "=", "session", ",", "table", "=", "table", ",", "columns", "=", "columns", ",", "key_set", "=", "key_set", ",", "transaction", "=", "transaction", ",", "index", "=", "index", ",", "limit", "=", "limit", ",", "resume_token", "=", "resume_token", ",", "partition_token", "=", "partition_token", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"session\"", ",", "session", ")", "]", "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", "[", "\"read\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ``ExecuteSql``. This method cannot be used to return a result set larger than 10 MiB; if the read matches more data than that, the read fails with a ``FAILED_PRECONDITION`` error. Reads inside read-write transactions might return ``ABORTED``. If this occurs, the application should restart the transaction from the beginning. See ``Transaction`` for more details. Larger result sets can be yielded in streaming fashion by calling ``StreamingRead`` instead. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `table`: >>> table = '' >>> >>> # TODO: Initialize `columns`: >>> columns = [] >>> >>> # TODO: Initialize `key_set`: >>> key_set = {} >>> >>> response = client.read(session, table, columns, key_set) Args: session (str): Required. The session in which the read should be performed. table (str): Required. The name of the table in the database to be read. columns (list[str]): The columns of ``table`` to be returned for each row matching this request. key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set`` names the primary keys of the rows in ``table`` to be yielded, unless ``index`` is present. If ``index`` is present, then ``key_set`` instead names index keys in ``index``. If the ``partition_token`` field is empty, rows are yielded in table primary key order (if ``index`` is empty) or index key order (if ``index`` is non-empty). If the ``partition_token`` field is not empty, rows will be yielded in an unspecified order. It is not an error for the ``key_set`` to name rows that do not exist in the database. Read yields nothing for nonexistent rows. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.KeySet` transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a temporary read-only transaction with strong concurrency. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` index (str): If non-empty, the name of an index on ``table``. This index is used instead of the table primary key when interpreting ``key_set`` and sorting result rows. See ``key_set`` for further information. limit (long): If greater than zero, only the first ``limit`` rows are yielded. If ``limit`` is zero, the default is no limit. A limit cannot be specified if ``partition_token`` is set. resume_token (bytes): If this request is resuming a previously interrupted read, ``resume_token`` should be copied from the last ``PartialResultSet`` yielded before the interruption. Doing this enables the new read to resume where the last read left off. The rest of the request parameters must exactly match the request that yielded this token. partition_token (bytes): If present, results will be restricted to the specified partition previously created using PartitionRead(). There must be an exact match for the values of fields common to this message and the PartitionReadRequest message used to create this partition\_token. 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.spanner_v1.types.ResultSet` 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.
[ "Reads", "rows", "from", "the", "database", "using", "key", "lookups", "and", "scans", "as", "a", "simple", "key", "/", "value", "style", "alternative", "to", "ExecuteSql", ".", "This", "method", "cannot", "be", "used", "to", "return", "a", "result", "set", "larger", "than", "10", "MiB", ";", "if", "the", "read", "matches", "more", "data", "than", "that", "the", "read", "fails", "with", "a", "FAILED_PRECONDITION", "error", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L992-L1132
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/gapic/spanner_client.py
SpannerClient.commit
def commit( self, session, mutations, transaction_id=None, single_use_transaction=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Commits a transaction. The request includes the mutations to be applied to rows in the database. ``Commit`` might return an ``ABORTED`` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If ``Commit`` returns ``ABORTED``, the caller should re-attempt the transaction from the beginning, re-using the same session. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `mutations`: >>> mutations = [] >>> >>> response = client.commit(session, mutations) Args: session (str): Required. The session in which the transaction to be committed is running. mutations (list[Union[dict, ~google.cloud.spanner_v1.types.Mutation]]): The mutations to be executed when this transaction commits. All mutations are applied atomically, in the order they appear in this list. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Mutation` transaction_id (bytes): Commit a previously-started transaction. single_use_transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Execute mutations in a temporary transaction. Note that unlike commit of a previously-started transaction, commit with a temporary transaction is non-idempotent. That is, if the ``CommitRequest`` is sent to Cloud Spanner more than once (for instance, due to retries in the application, or in the transport library), it is possible that the mutations are executed more than once. If this is undesirable, use ``BeginTransaction`` and ``Commit`` instead. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionOptions` 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.spanner_v1.types.CommitResponse` 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 "commit" not in self._inner_api_calls: self._inner_api_calls[ "commit" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.commit, default_retry=self._method_configs["Commit"].retry, default_timeout=self._method_configs["Commit"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction_id=transaction_id, single_use_transaction=single_use_transaction ) request = spanner_pb2.CommitRequest( session=session, mutations=mutations, transaction_id=transaction_id, single_use_transaction=single_use_transaction, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["commit"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def commit( self, session, mutations, transaction_id=None, single_use_transaction=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Commits a transaction. The request includes the mutations to be applied to rows in the database. ``Commit`` might return an ``ABORTED`` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If ``Commit`` returns ``ABORTED``, the caller should re-attempt the transaction from the beginning, re-using the same session. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `mutations`: >>> mutations = [] >>> >>> response = client.commit(session, mutations) Args: session (str): Required. The session in which the transaction to be committed is running. mutations (list[Union[dict, ~google.cloud.spanner_v1.types.Mutation]]): The mutations to be executed when this transaction commits. All mutations are applied atomically, in the order they appear in this list. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Mutation` transaction_id (bytes): Commit a previously-started transaction. single_use_transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Execute mutations in a temporary transaction. Note that unlike commit of a previously-started transaction, commit with a temporary transaction is non-idempotent. That is, if the ``CommitRequest`` is sent to Cloud Spanner more than once (for instance, due to retries in the application, or in the transport library), it is possible that the mutations are executed more than once. If this is undesirable, use ``BeginTransaction`` and ``Commit`` instead. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionOptions` 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.spanner_v1.types.CommitResponse` 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 "commit" not in self._inner_api_calls: self._inner_api_calls[ "commit" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.commit, default_retry=self._method_configs["Commit"].retry, default_timeout=self._method_configs["Commit"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction_id=transaction_id, single_use_transaction=single_use_transaction ) request = spanner_pb2.CommitRequest( session=session, mutations=mutations, transaction_id=transaction_id, single_use_transaction=single_use_transaction, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["commit"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "commit", "(", "self", ",", "session", ",", "mutations", ",", "transaction_id", "=", "None", ",", "single_use_transaction", "=", "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", "\"commit\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"commit\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "commit", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"Commit\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"Commit\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "transaction_id", "=", "transaction_id", ",", "single_use_transaction", "=", "single_use_transaction", ")", "request", "=", "spanner_pb2", ".", "CommitRequest", "(", "session", "=", "session", ",", "mutations", "=", "mutations", ",", "transaction_id", "=", "transaction_id", ",", "single_use_transaction", "=", "single_use_transaction", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"session\"", ",", "session", ")", "]", "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", "[", "\"commit\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Commits a transaction. The request includes the mutations to be applied to rows in the database. ``Commit`` might return an ``ABORTED`` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If ``Commit`` returns ``ABORTED``, the caller should re-attempt the transaction from the beginning, re-using the same session. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `mutations`: >>> mutations = [] >>> >>> response = client.commit(session, mutations) Args: session (str): Required. The session in which the transaction to be committed is running. mutations (list[Union[dict, ~google.cloud.spanner_v1.types.Mutation]]): The mutations to be executed when this transaction commits. All mutations are applied atomically, in the order they appear in this list. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Mutation` transaction_id (bytes): Commit a previously-started transaction. single_use_transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Execute mutations in a temporary transaction. Note that unlike commit of a previously-started transaction, commit with a temporary transaction is non-idempotent. That is, if the ``CommitRequest`` is sent to Cloud Spanner more than once (for instance, due to retries in the application, or in the transport library), it is possible that the mutations are executed more than once. If this is undesirable, use ``BeginTransaction`` and ``Commit`` instead. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionOptions` 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.spanner_v1.types.CommitResponse` 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.
[ "Commits", "a", "transaction", ".", "The", "request", "includes", "the", "mutations", "to", "be", "applied", "to", "rows", "in", "the", "database", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L1352-L1460
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/gapic/spanner_client.py
SpannerClient.partition_query
def partition_query( self, session, sql, transaction=None, params=None, param_types=None, partition_options=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a set of partition tokens that can be used to execute a query operation in parallel. Each of the returned partition tokens can be used by ``ExecuteStreamingSql`` to specify a subset of the query result to read. The same session and read-only transaction must be used by the PartitionQueryRequest used to create the partition tokens and the ExecuteSqlRequests that use the partition tokens. Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the query, and the whole operation must be restarted from the beginning. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `sql`: >>> sql = '' >>> >>> response = client.partition_query(session, sql) Args: session (str): Required. The session used to create the partitions. sql (str): The query request to generate partitions for. The request will fail if the query is not root partitionable. The query plan of a root partitionable query has a single distributed union operator. A distributed union operator conceptually divides one or more tables into multiple splits, remotely evaluates a subquery independently on each split, and then unions all results. This must not contain DML commands, such as INSERT, UPDATE, or DELETE. Use ``ExecuteStreamingSql`` with a PartitionedDml transaction for large, partition-friendly DML operations. transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use transactions are not. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL query string can contain parameter placeholders. A parameter placeholder consists of ``'@'`` followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores. Parameters can appear anywhere that a literal value is expected. The same parameter name can be used more than once, for example: ``"WHERE id > @msg_id AND id < @msg_id + 100"`` It is an error to execute an SQL query with unbound parameters. Parameter values are specified using ``params``, which is a JSON object whose keys are parameter names, and whose values are the corresponding parameter values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Struct` param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type from a JSON value. For example, values of type ``BYTES`` and values of type ``STRING`` both appear in ``params`` as JSON strings. In these cases, ``param_types`` can be used to specify the exact SQL type for some or all of the SQL query parameters. See the definition of ``Type`` for more information about SQL types. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Type` partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.PartitionOptions` 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.spanner_v1.types.PartitionResponse` 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 "partition_query" not in self._inner_api_calls: self._inner_api_calls[ "partition_query" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.partition_query, default_retry=self._method_configs["PartitionQuery"].retry, default_timeout=self._method_configs["PartitionQuery"].timeout, client_info=self._client_info, ) request = spanner_pb2.PartitionQueryRequest( session=session, sql=sql, transaction=transaction, params=params, param_types=param_types, partition_options=partition_options, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["partition_query"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def partition_query( self, session, sql, transaction=None, params=None, param_types=None, partition_options=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a set of partition tokens that can be used to execute a query operation in parallel. Each of the returned partition tokens can be used by ``ExecuteStreamingSql`` to specify a subset of the query result to read. The same session and read-only transaction must be used by the PartitionQueryRequest used to create the partition tokens and the ExecuteSqlRequests that use the partition tokens. Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the query, and the whole operation must be restarted from the beginning. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `sql`: >>> sql = '' >>> >>> response = client.partition_query(session, sql) Args: session (str): Required. The session used to create the partitions. sql (str): The query request to generate partitions for. The request will fail if the query is not root partitionable. The query plan of a root partitionable query has a single distributed union operator. A distributed union operator conceptually divides one or more tables into multiple splits, remotely evaluates a subquery independently on each split, and then unions all results. This must not contain DML commands, such as INSERT, UPDATE, or DELETE. Use ``ExecuteStreamingSql`` with a PartitionedDml transaction for large, partition-friendly DML operations. transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use transactions are not. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL query string can contain parameter placeholders. A parameter placeholder consists of ``'@'`` followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores. Parameters can appear anywhere that a literal value is expected. The same parameter name can be used more than once, for example: ``"WHERE id > @msg_id AND id < @msg_id + 100"`` It is an error to execute an SQL query with unbound parameters. Parameter values are specified using ``params``, which is a JSON object whose keys are parameter names, and whose values are the corresponding parameter values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Struct` param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type from a JSON value. For example, values of type ``BYTES`` and values of type ``STRING`` both appear in ``params`` as JSON strings. In these cases, ``param_types`` can be used to specify the exact SQL type for some or all of the SQL query parameters. See the definition of ``Type`` for more information about SQL types. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Type` partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.PartitionOptions` 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.spanner_v1.types.PartitionResponse` 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 "partition_query" not in self._inner_api_calls: self._inner_api_calls[ "partition_query" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.partition_query, default_retry=self._method_configs["PartitionQuery"].retry, default_timeout=self._method_configs["PartitionQuery"].timeout, client_info=self._client_info, ) request = spanner_pb2.PartitionQueryRequest( session=session, sql=sql, transaction=transaction, params=params, param_types=param_types, partition_options=partition_options, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["partition_query"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "partition_query", "(", "self", ",", "session", ",", "sql", ",", "transaction", "=", "None", ",", "params", "=", "None", ",", "param_types", "=", "None", ",", "partition_options", "=", "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", "\"partition_query\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"partition_query\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "partition_query", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"PartitionQuery\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"PartitionQuery\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "spanner_pb2", ".", "PartitionQueryRequest", "(", "session", "=", "session", ",", "sql", "=", "sql", ",", "transaction", "=", "transaction", ",", "params", "=", "params", ",", "param_types", "=", "param_types", ",", "partition_options", "=", "partition_options", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"session\"", ",", "session", ")", "]", "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", "[", "\"partition_query\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a set of partition tokens that can be used to execute a query operation in parallel. Each of the returned partition tokens can be used by ``ExecuteStreamingSql`` to specify a subset of the query result to read. The same session and read-only transaction must be used by the PartitionQueryRequest used to create the partition tokens and the ExecuteSqlRequests that use the partition tokens. Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the query, and the whole operation must be restarted from the beginning. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `sql`: >>> sql = '' >>> >>> response = client.partition_query(session, sql) Args: session (str): Required. The session used to create the partitions. sql (str): The query request to generate partitions for. The request will fail if the query is not root partitionable. The query plan of a root partitionable query has a single distributed union operator. A distributed union operator conceptually divides one or more tables into multiple splits, remotely evaluates a subquery independently on each split, and then unions all results. This must not contain DML commands, such as INSERT, UPDATE, or DELETE. Use ``ExecuteStreamingSql`` with a PartitionedDml transaction for large, partition-friendly DML operations. transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use transactions are not. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL query string can contain parameter placeholders. A parameter placeholder consists of ``'@'`` followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores. Parameters can appear anywhere that a literal value is expected. The same parameter name can be used more than once, for example: ``"WHERE id > @msg_id AND id < @msg_id + 100"`` It is an error to execute an SQL query with unbound parameters. Parameter values are specified using ``params``, which is a JSON object whose keys are parameter names, and whose values are the corresponding parameter values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Struct` param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type from a JSON value. For example, values of type ``BYTES`` and values of type ``STRING`` both appear in ``params`` as JSON strings. In these cases, ``param_types`` can be used to specify the exact SQL type for some or all of the SQL query parameters. See the definition of ``Type`` for more information about SQL types. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.Type` partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.PartitionOptions` 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.spanner_v1.types.PartitionResponse` 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", "set", "of", "partition", "tokens", "that", "can", "be", "used", "to", "execute", "a", "query", "operation", "in", "parallel", ".", "Each", "of", "the", "returned", "partition", "tokens", "can", "be", "used", "by", "ExecuteStreamingSql", "to", "specify", "a", "subset", "of", "the", "query", "result", "to", "read", ".", "The", "same", "session", "and", "read", "-", "only", "transaction", "must", "be", "used", "by", "the", "PartitionQueryRequest", "used", "to", "create", "the", "partition", "tokens", "and", "the", "ExecuteSqlRequests", "that", "use", "the", "partition", "tokens", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L1541-L1679
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/gapic/spanner_client.py
SpannerClient.partition_read
def partition_read( self, session, table, key_set, transaction=None, index=None, columns=None, partition_options=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a set of partition tokens that can be used to execute a read operation in parallel. Each of the returned partition tokens can be used by ``StreamingRead`` to specify a subset of the read result to read. The same session and read-only transaction must be used by the PartitionReadRequest used to create the partition tokens and the ReadRequests that use the partition tokens. There are no ordering guarantees on rows returned among the returned partition tokens, or even within each individual StreamingRead call issued with a partition\_token. Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the read, and the whole operation must be restarted from the beginning. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `table`: >>> table = '' >>> >>> # TODO: Initialize `key_set`: >>> key_set = {} >>> >>> response = client.partition_read(session, table, key_set) Args: session (str): Required. The session used to create the partitions. table (str): Required. The name of the table in the database to be read. key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set`` names the primary keys of the rows in ``table`` to be yielded, unless ``index`` is present. If ``index`` is present, then ``key_set`` instead names index keys in ``index``. It is not an error for the ``key_set`` to name rows that do not exist in the database. Read yields nothing for nonexistent rows. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.KeySet` transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use transactions are not. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` index (str): If non-empty, the name of an index on ``table``. This index is used instead of the table primary key when interpreting ``key_set`` and sorting result rows. See ``key_set`` for further information. columns (list[str]): The columns of ``table`` to be returned for each row matching this request. partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.PartitionOptions` 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.spanner_v1.types.PartitionResponse` 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 "partition_read" not in self._inner_api_calls: self._inner_api_calls[ "partition_read" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.partition_read, default_retry=self._method_configs["PartitionRead"].retry, default_timeout=self._method_configs["PartitionRead"].timeout, client_info=self._client_info, ) request = spanner_pb2.PartitionReadRequest( session=session, table=table, key_set=key_set, transaction=transaction, index=index, columns=columns, partition_options=partition_options, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["partition_read"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def partition_read( self, session, table, key_set, transaction=None, index=None, columns=None, partition_options=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a set of partition tokens that can be used to execute a read operation in parallel. Each of the returned partition tokens can be used by ``StreamingRead`` to specify a subset of the read result to read. The same session and read-only transaction must be used by the PartitionReadRequest used to create the partition tokens and the ReadRequests that use the partition tokens. There are no ordering guarantees on rows returned among the returned partition tokens, or even within each individual StreamingRead call issued with a partition\_token. Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the read, and the whole operation must be restarted from the beginning. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `table`: >>> table = '' >>> >>> # TODO: Initialize `key_set`: >>> key_set = {} >>> >>> response = client.partition_read(session, table, key_set) Args: session (str): Required. The session used to create the partitions. table (str): Required. The name of the table in the database to be read. key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set`` names the primary keys of the rows in ``table`` to be yielded, unless ``index`` is present. If ``index`` is present, then ``key_set`` instead names index keys in ``index``. It is not an error for the ``key_set`` to name rows that do not exist in the database. Read yields nothing for nonexistent rows. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.KeySet` transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use transactions are not. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` index (str): If non-empty, the name of an index on ``table``. This index is used instead of the table primary key when interpreting ``key_set`` and sorting result rows. See ``key_set`` for further information. columns (list[str]): The columns of ``table`` to be returned for each row matching this request. partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.PartitionOptions` 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.spanner_v1.types.PartitionResponse` 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 "partition_read" not in self._inner_api_calls: self._inner_api_calls[ "partition_read" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.partition_read, default_retry=self._method_configs["PartitionRead"].retry, default_timeout=self._method_configs["PartitionRead"].timeout, client_info=self._client_info, ) request = spanner_pb2.PartitionReadRequest( session=session, table=table, key_set=key_set, transaction=transaction, index=index, columns=columns, partition_options=partition_options, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session", session)] 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["partition_read"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "partition_read", "(", "self", ",", "session", ",", "table", ",", "key_set", ",", "transaction", "=", "None", ",", "index", "=", "None", ",", "columns", "=", "None", ",", "partition_options", "=", "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", "\"partition_read\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"partition_read\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "partition_read", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"PartitionRead\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"PartitionRead\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "spanner_pb2", ".", "PartitionReadRequest", "(", "session", "=", "session", ",", "table", "=", "table", ",", "key_set", "=", "key_set", ",", "transaction", "=", "transaction", ",", "index", "=", "index", ",", "columns", "=", "columns", ",", "partition_options", "=", "partition_options", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"session\"", ",", "session", ")", "]", "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", "[", "\"partition_read\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a set of partition tokens that can be used to execute a read operation in parallel. Each of the returned partition tokens can be used by ``StreamingRead`` to specify a subset of the read result to read. The same session and read-only transaction must be used by the PartitionReadRequest used to create the partition tokens and the ReadRequests that use the partition tokens. There are no ordering guarantees on rows returned among the returned partition tokens, or even within each individual StreamingRead call issued with a partition\_token. Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the read, and the whole operation must be restarted from the beginning. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') >>> >>> # TODO: Initialize `table`: >>> table = '' >>> >>> # TODO: Initialize `key_set`: >>> key_set = {} >>> >>> response = client.partition_read(session, table, key_set) Args: session (str): Required. The session used to create the partitions. table (str): Required. The name of the table in the database to be read. key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set`` names the primary keys of the rows in ``table`` to be yielded, unless ``index`` is present. If ``index`` is present, then ``key_set`` instead names index keys in ``index``. It is not an error for the ``key_set`` to name rows that do not exist in the database. Read yields nothing for nonexistent rows. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.KeySet` transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use transactions are not. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.TransactionSelector` index (str): If non-empty, the name of an index on ``table``. This index is used instead of the table primary key when interpreting ``key_set`` and sorting result rows. See ``key_set`` for further information. columns (list[str]): The columns of ``table`` to be returned for each row matching this request. partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_v1.types.PartitionOptions` 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.spanner_v1.types.PartitionResponse` 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", "set", "of", "partition", "tokens", "that", "can", "be", "used", "to", "execute", "a", "read", "operation", "in", "parallel", ".", "Each", "of", "the", "returned", "partition", "tokens", "can", "be", "used", "by", "StreamingRead", "to", "specify", "a", "subset", "of", "the", "read", "result", "to", "read", ".", "The", "same", "session", "and", "read", "-", "only", "transaction", "must", "be", "used", "by", "the", "PartitionReadRequest", "used", "to", "create", "the", "partition", "tokens", "and", "the", "ReadRequests", "that", "use", "the", "partition", "tokens", ".", "There", "are", "no", "ordering", "guarantees", "on", "rows", "returned", "among", "the", "returned", "partition", "tokens", "or", "even", "within", "each", "individual", "StreamingRead", "call", "issued", "with", "a", "partition", "\\", "_token", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L1681-L1806
train
googleapis/google-cloud-python
talent/google/cloud/talent_v4beta1/gapic/event_service_client.py
EventServiceClient.create_client_event
def create_client_event( self, parent, client_event, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Report events issued when end user interacts with customer's application that uses Cloud Talent Solution. You may inspect the created events in `self service tools <https://console.cloud.google.com/talent-solution/overview>`__. `Learn more <https://cloud.google.com/talent-solution/docs/management-tools>`__ about self service tools. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.EventServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `client_event`: >>> client_event = {} >>> >>> response = client.create_client_event(parent, client_event) Args: parent (str): Parent project name. client_event (Union[dict, ~google.cloud.talent_v4beta1.types.ClientEvent]): Required. Events issued when end user interacts with customer's application that uses Cloud Talent Solution. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.ClientEvent` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.talent_v4beta1.types.ClientEvent` 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_client_event" not in self._inner_api_calls: self._inner_api_calls[ "create_client_event" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_client_event, default_retry=self._method_configs["CreateClientEvent"].retry, default_timeout=self._method_configs["CreateClientEvent"].timeout, client_info=self._client_info, ) request = event_service_pb2.CreateClientEventRequest( parent=parent, client_event=client_event ) return self._inner_api_calls["create_client_event"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_client_event( self, parent, client_event, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Report events issued when end user interacts with customer's application that uses Cloud Talent Solution. You may inspect the created events in `self service tools <https://console.cloud.google.com/talent-solution/overview>`__. `Learn more <https://cloud.google.com/talent-solution/docs/management-tools>`__ about self service tools. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.EventServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `client_event`: >>> client_event = {} >>> >>> response = client.create_client_event(parent, client_event) Args: parent (str): Parent project name. client_event (Union[dict, ~google.cloud.talent_v4beta1.types.ClientEvent]): Required. Events issued when end user interacts with customer's application that uses Cloud Talent Solution. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.ClientEvent` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.talent_v4beta1.types.ClientEvent` 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_client_event" not in self._inner_api_calls: self._inner_api_calls[ "create_client_event" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_client_event, default_retry=self._method_configs["CreateClientEvent"].retry, default_timeout=self._method_configs["CreateClientEvent"].timeout, client_info=self._client_info, ) request = event_service_pb2.CreateClientEventRequest( parent=parent, client_event=client_event ) return self._inner_api_calls["create_client_event"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_client_event", "(", "self", ",", "parent", ",", "client_event", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"create_client_event\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_client_event\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_client_event", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateClientEvent\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateClientEvent\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "event_service_pb2", ".", "CreateClientEventRequest", "(", "parent", "=", "parent", ",", "client_event", "=", "client_event", ")", "return", "self", ".", "_inner_api_calls", "[", "\"create_client_event\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Report events issued when end user interacts with customer's application that uses Cloud Talent Solution. You may inspect the created events in `self service tools <https://console.cloud.google.com/talent-solution/overview>`__. `Learn more <https://cloud.google.com/talent-solution/docs/management-tools>`__ about self service tools. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.EventServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `client_event`: >>> client_event = {} >>> >>> response = client.create_client_event(parent, client_event) Args: parent (str): Parent project name. client_event (Union[dict, ~google.cloud.talent_v4beta1.types.ClientEvent]): Required. Events issued when end user interacts with customer's application that uses Cloud Talent Solution. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.ClientEvent` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.talent_v4beta1.types.ClientEvent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Report", "events", "issued", "when", "end", "user", "interacts", "with", "customer", "s", "application", "that", "uses", "Cloud", "Talent", "Solution", ".", "You", "may", "inspect", "the", "created", "events", "in", "self", "service", "tools", "<https", ":", "//", "console", ".", "cloud", ".", "google", ".", "com", "/", "talent", "-", "solution", "/", "overview", ">", "__", ".", "Learn", "more", "<https", ":", "//", "cloud", ".", "google", ".", "com", "/", "talent", "-", "solution", "/", "docs", "/", "management", "-", "tools", ">", "__", "about", "self", "service", "tools", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/event_service_client.py#L182-L255
train
googleapis/google-cloud-python
datastore/google/cloud/datastore/_gapic.py
make_datastore_api
def make_datastore_api(client): """Create an instance of the GAPIC Datastore API. :type client: :class:`~google.cloud.datastore.client.Client` :param client: The client that holds configuration details. :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient` :returns: A datastore API instance with the proper credentials. """ parse_result = six.moves.urllib_parse.urlparse(client._base_url) host = parse_result.netloc if parse_result.scheme == "https": channel = make_secure_channel(client._credentials, DEFAULT_USER_AGENT, host) else: channel = insecure_channel(host) return datastore_client.DatastoreClient( channel=channel, client_info=client_info.ClientInfo( client_library_version=__version__, gapic_version=__version__ ), )
python
def make_datastore_api(client): """Create an instance of the GAPIC Datastore API. :type client: :class:`~google.cloud.datastore.client.Client` :param client: The client that holds configuration details. :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient` :returns: A datastore API instance with the proper credentials. """ parse_result = six.moves.urllib_parse.urlparse(client._base_url) host = parse_result.netloc if parse_result.scheme == "https": channel = make_secure_channel(client._credentials, DEFAULT_USER_AGENT, host) else: channel = insecure_channel(host) return datastore_client.DatastoreClient( channel=channel, client_info=client_info.ClientInfo( client_library_version=__version__, gapic_version=__version__ ), )
[ "def", "make_datastore_api", "(", "client", ")", ":", "parse_result", "=", "six", ".", "moves", ".", "urllib_parse", ".", "urlparse", "(", "client", ".", "_base_url", ")", "host", "=", "parse_result", ".", "netloc", "if", "parse_result", ".", "scheme", "==", "\"https\"", ":", "channel", "=", "make_secure_channel", "(", "client", ".", "_credentials", ",", "DEFAULT_USER_AGENT", ",", "host", ")", "else", ":", "channel", "=", "insecure_channel", "(", "host", ")", "return", "datastore_client", ".", "DatastoreClient", "(", "channel", "=", "channel", ",", "client_info", "=", "client_info", ".", "ClientInfo", "(", "client_library_version", "=", "__version__", ",", "gapic_version", "=", "__version__", ")", ",", ")" ]
Create an instance of the GAPIC Datastore API. :type client: :class:`~google.cloud.datastore.client.Client` :param client: The client that holds configuration details. :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient` :returns: A datastore API instance with the proper credentials.
[ "Create", "an", "instance", "of", "the", "GAPIC", "Datastore", "API", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/_gapic.py#L28-L49
train
googleapis/google-cloud-python
bigquery/noxfile.py
default
def default(session): """Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of Python corresponding to the ``nox`` binary the ``PATH`` can run the tests. """ # Install all test dependencies, then install local packages in-place. session.install("mock", "pytest", "pytest-cov") for local_dep in LOCAL_DEPS: session.install("-e", local_dep) # Pyarrow does not support Python 3.7 dev_install = ".[all]" session.install("-e", dev_install) # IPython does not support Python 2 after version 5.x if session.python == "2.7": session.install("ipython==5.5") else: session.install("ipython") # Run py.test against the unit tests. session.run( "py.test", "--quiet", "--cov=google.cloud.bigquery", "--cov=tests.unit", "--cov-append", "--cov-config=.coveragerc", "--cov-report=", "--cov-fail-under=97", os.path.join("tests", "unit"), *session.posargs )
python
def default(session): """Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of Python corresponding to the ``nox`` binary the ``PATH`` can run the tests. """ # Install all test dependencies, then install local packages in-place. session.install("mock", "pytest", "pytest-cov") for local_dep in LOCAL_DEPS: session.install("-e", local_dep) # Pyarrow does not support Python 3.7 dev_install = ".[all]" session.install("-e", dev_install) # IPython does not support Python 2 after version 5.x if session.python == "2.7": session.install("ipython==5.5") else: session.install("ipython") # Run py.test against the unit tests. session.run( "py.test", "--quiet", "--cov=google.cloud.bigquery", "--cov=tests.unit", "--cov-append", "--cov-config=.coveragerc", "--cov-report=", "--cov-fail-under=97", os.path.join("tests", "unit"), *session.posargs )
[ "def", "default", "(", "session", ")", ":", "# Install all test dependencies, then install local packages in-place.", "session", ".", "install", "(", "\"mock\"", ",", "\"pytest\"", ",", "\"pytest-cov\"", ")", "for", "local_dep", "in", "LOCAL_DEPS", ":", "session", ".", "install", "(", "\"-e\"", ",", "local_dep", ")", "# Pyarrow does not support Python 3.7", "dev_install", "=", "\".[all]\"", "session", ".", "install", "(", "\"-e\"", ",", "dev_install", ")", "# IPython does not support Python 2 after version 5.x", "if", "session", ".", "python", "==", "\"2.7\"", ":", "session", ".", "install", "(", "\"ipython==5.5\"", ")", "else", ":", "session", ".", "install", "(", "\"ipython\"", ")", "# Run py.test against the unit tests.", "session", ".", "run", "(", "\"py.test\"", ",", "\"--quiet\"", ",", "\"--cov=google.cloud.bigquery\"", ",", "\"--cov=tests.unit\"", ",", "\"--cov-append\"", ",", "\"--cov-config=.coveragerc\"", ",", "\"--cov-report=\"", ",", "\"--cov-fail-under=97\"", ",", "os", ".", "path", ".", "join", "(", "\"tests\"", ",", "\"unit\"", ")", ",", "*", "session", ".", "posargs", ")" ]
Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of Python corresponding to the ``nox`` binary the ``PATH`` can run the tests.
[ "Default", "unit", "test", "session", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/noxfile.py#L28-L63
train
googleapis/google-cloud-python
bigquery/noxfile.py
snippets
def snippets(session): """Run the snippets test suite.""" # Sanity check: Only run snippets tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable.") # Install all test dependencies, then install local packages in place. session.install("mock", "pytest") for local_dep in LOCAL_DEPS: session.install("-e", local_dep) session.install("-e", os.path.join("..", "storage")) session.install("-e", os.path.join("..", "test_utils")) session.install("-e", ".[all]") # Run py.test against the snippets tests. session.run("py.test", os.path.join("docs", "snippets.py"), *session.posargs) session.run("py.test", "samples", *session.posargs)
python
def snippets(session): """Run the snippets test suite.""" # Sanity check: Only run snippets tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable.") # Install all test dependencies, then install local packages in place. session.install("mock", "pytest") for local_dep in LOCAL_DEPS: session.install("-e", local_dep) session.install("-e", os.path.join("..", "storage")) session.install("-e", os.path.join("..", "test_utils")) session.install("-e", ".[all]") # Run py.test against the snippets tests. session.run("py.test", os.path.join("docs", "snippets.py"), *session.posargs) session.run("py.test", "samples", *session.posargs)
[ "def", "snippets", "(", "session", ")", ":", "# Sanity check: Only run snippets tests if the environment variable is set.", "if", "not", "os", ".", "environ", ".", "get", "(", "\"GOOGLE_APPLICATION_CREDENTIALS\"", ",", "\"\"", ")", ":", "session", ".", "skip", "(", "\"Credentials must be set via environment variable.\"", ")", "# Install all test dependencies, then install local packages in place.", "session", ".", "install", "(", "\"mock\"", ",", "\"pytest\"", ")", "for", "local_dep", "in", "LOCAL_DEPS", ":", "session", ".", "install", "(", "\"-e\"", ",", "local_dep", ")", "session", ".", "install", "(", "\"-e\"", ",", "os", ".", "path", ".", "join", "(", "\"..\"", ",", "\"storage\"", ")", ")", "session", ".", "install", "(", "\"-e\"", ",", "os", ".", "path", ".", "join", "(", "\"..\"", ",", "\"test_utils\"", ")", ")", "session", ".", "install", "(", "\"-e\"", ",", "\".[all]\"", ")", "# Run py.test against the snippets tests.", "session", ".", "run", "(", "\"py.test\"", ",", "os", ".", "path", ".", "join", "(", "\"docs\"", ",", "\"snippets.py\"", ")", ",", "*", "session", ".", "posargs", ")", "session", ".", "run", "(", "\"py.test\"", ",", "\"samples\"", ",", "*", "session", ".", "posargs", ")" ]
Run the snippets test suite.
[ "Run", "the", "snippets", "test", "suite", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/noxfile.py#L104-L121
train
googleapis/google-cloud-python
bigquery/noxfile.py
lint
def lint(session): """Run linters. Returns a failure if the linters find linting errors or sufficiently serious code quality issues. """ session.install("black", "flake8", *LOCAL_DEPS) session.install(".") session.run("flake8", os.path.join("google", "cloud", "bigquery")) session.run("flake8", "tests") session.run("flake8", os.path.join("docs", "snippets.py")) session.run("black", "--check", *BLACK_PATHS)
python
def lint(session): """Run linters. Returns a failure if the linters find linting errors or sufficiently serious code quality issues. """ session.install("black", "flake8", *LOCAL_DEPS) session.install(".") session.run("flake8", os.path.join("google", "cloud", "bigquery")) session.run("flake8", "tests") session.run("flake8", os.path.join("docs", "snippets.py")) session.run("black", "--check", *BLACK_PATHS)
[ "def", "lint", "(", "session", ")", ":", "session", ".", "install", "(", "\"black\"", ",", "\"flake8\"", ",", "*", "LOCAL_DEPS", ")", "session", ".", "install", "(", "\".\"", ")", "session", ".", "run", "(", "\"flake8\"", ",", "os", ".", "path", ".", "join", "(", "\"google\"", ",", "\"cloud\"", ",", "\"bigquery\"", ")", ")", "session", ".", "run", "(", "\"flake8\"", ",", "\"tests\"", ")", "session", ".", "run", "(", "\"flake8\"", ",", "os", ".", "path", ".", "join", "(", "\"docs\"", ",", "\"snippets.py\"", ")", ")", "session", ".", "run", "(", "\"black\"", ",", "\"--check\"", ",", "*", "BLACK_PATHS", ")" ]
Run linters. Returns a failure if the linters find linting errors or sufficiently serious code quality issues.
[ "Run", "linters", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/noxfile.py#L137-L149
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/message.py
_indent
def _indent(lines, prefix=" "): """Indent some text. Note that this is present as ``textwrap.indent``, but not in Python 2. Args: lines (str): The newline delimited string to be indented. prefix (Optional[str]): The prefix to indent each line with. Default to two spaces. Returns: str: The newly indented content. """ indented = [] for line in lines.split("\n"): indented.append(prefix + line) return "\n".join(indented)
python
def _indent(lines, prefix=" "): """Indent some text. Note that this is present as ``textwrap.indent``, but not in Python 2. Args: lines (str): The newline delimited string to be indented. prefix (Optional[str]): The prefix to indent each line with. Default to two spaces. Returns: str: The newly indented content. """ indented = [] for line in lines.split("\n"): indented.append(prefix + line) return "\n".join(indented)
[ "def", "_indent", "(", "lines", ",", "prefix", "=", "\" \"", ")", ":", "indented", "=", "[", "]", "for", "line", "in", "lines", ".", "split", "(", "\"\\n\"", ")", ":", "indented", ".", "append", "(", "prefix", "+", "line", ")", "return", "\"\\n\"", ".", "join", "(", "indented", ")" ]
Indent some text. Note that this is present as ``textwrap.indent``, but not in Python 2. Args: lines (str): The newline delimited string to be indented. prefix (Optional[str]): The prefix to indent each line with. Default to two spaces. Returns: str: The newly indented content.
[ "Indent", "some", "text", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L33-L49
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/message.py
Message.publish_time
def publish_time(self): """Return the time that the message was originally published. Returns: datetime: The date and time that the message was published. """ timestamp = self._message.publish_time delta = datetime.timedelta( seconds=timestamp.seconds, microseconds=timestamp.nanos // 1000 ) return datetime_helpers._UTC_EPOCH + delta
python
def publish_time(self): """Return the time that the message was originally published. Returns: datetime: The date and time that the message was published. """ timestamp = self._message.publish_time delta = datetime.timedelta( seconds=timestamp.seconds, microseconds=timestamp.nanos // 1000 ) return datetime_helpers._UTC_EPOCH + delta
[ "def", "publish_time", "(", "self", ")", ":", "timestamp", "=", "self", ".", "_message", ".", "publish_time", "delta", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "timestamp", ".", "seconds", ",", "microseconds", "=", "timestamp", ".", "nanos", "//", "1000", ")", "return", "datetime_helpers", ".", "_UTC_EPOCH", "+", "delta" ]
Return the time that the message was originally published. Returns: datetime: The date and time that the message was published.
[ "Return", "the", "time", "that", "the", "message", "was", "originally", "published", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L147-L157
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/message.py
Message.ack
def ack(self): """Acknowledge the given message. Acknowledging a message in Pub/Sub means that you are done with it, and it will not be delivered to this subscription again. You should avoid acknowledging messages until you have *finished* processing them, so that in the event of a failure, you receive the message again. .. warning:: Acks in Pub/Sub are best effort. You should always ensure that your processing code is idempotent, as you may receive any given message more than once. """ time_to_ack = math.ceil(time.time() - self._received_timestamp) self._request_queue.put( requests.AckRequest( ack_id=self._ack_id, byte_size=self.size, time_to_ack=time_to_ack ) )
python
def ack(self): """Acknowledge the given message. Acknowledging a message in Pub/Sub means that you are done with it, and it will not be delivered to this subscription again. You should avoid acknowledging messages until you have *finished* processing them, so that in the event of a failure, you receive the message again. .. warning:: Acks in Pub/Sub are best effort. You should always ensure that your processing code is idempotent, as you may receive any given message more than once. """ time_to_ack = math.ceil(time.time() - self._received_timestamp) self._request_queue.put( requests.AckRequest( ack_id=self._ack_id, byte_size=self.size, time_to_ack=time_to_ack ) )
[ "def", "ack", "(", "self", ")", ":", "time_to_ack", "=", "math", ".", "ceil", "(", "time", ".", "time", "(", ")", "-", "self", ".", "_received_timestamp", ")", "self", ".", "_request_queue", ".", "put", "(", "requests", ".", "AckRequest", "(", "ack_id", "=", "self", ".", "_ack_id", ",", "byte_size", "=", "self", ".", "size", ",", "time_to_ack", "=", "time_to_ack", ")", ")" ]
Acknowledge the given message. Acknowledging a message in Pub/Sub means that you are done with it, and it will not be delivered to this subscription again. You should avoid acknowledging messages until you have *finished* processing them, so that in the event of a failure, you receive the message again. .. warning:: Acks in Pub/Sub are best effort. You should always ensure that your processing code is idempotent, as you may receive any given message more than once.
[ "Acknowledge", "the", "given", "message", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L169-L188
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/message.py
Message.drop
def drop(self): """Release the message from lease management. This informs the policy to no longer hold on to the lease for this message. Pub/Sub will re-deliver the message if it is not acknowledged before the existing lease expires. .. warning:: For most use cases, the only reason to drop a message from lease management is on :meth:`ack` or :meth:`nack`; these methods both call this one. You probably do not want to call this method directly. """ self._request_queue.put( requests.DropRequest(ack_id=self._ack_id, byte_size=self.size) )
python
def drop(self): """Release the message from lease management. This informs the policy to no longer hold on to the lease for this message. Pub/Sub will re-deliver the message if it is not acknowledged before the existing lease expires. .. warning:: For most use cases, the only reason to drop a message from lease management is on :meth:`ack` or :meth:`nack`; these methods both call this one. You probably do not want to call this method directly. """ self._request_queue.put( requests.DropRequest(ack_id=self._ack_id, byte_size=self.size) )
[ "def", "drop", "(", "self", ")", ":", "self", ".", "_request_queue", ".", "put", "(", "requests", ".", "DropRequest", "(", "ack_id", "=", "self", ".", "_ack_id", ",", "byte_size", "=", "self", ".", "size", ")", ")" ]
Release the message from lease management. This informs the policy to no longer hold on to the lease for this message. Pub/Sub will re-deliver the message if it is not acknowledged before the existing lease expires. .. warning:: For most use cases, the only reason to drop a message from lease management is on :meth:`ack` or :meth:`nack`; these methods both call this one. You probably do not want to call this method directly.
[ "Release", "the", "message", "from", "lease", "management", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L190-L205
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/message.py
Message.lease
def lease(self): """Inform the policy to lease this message continually. .. note:: This method is called by the constructor, and you should never need to call it manually. """ self._request_queue.put( requests.LeaseRequest(ack_id=self._ack_id, byte_size=self.size) )
python
def lease(self): """Inform the policy to lease this message continually. .. note:: This method is called by the constructor, and you should never need to call it manually. """ self._request_queue.put( requests.LeaseRequest(ack_id=self._ack_id, byte_size=self.size) )
[ "def", "lease", "(", "self", ")", ":", "self", ".", "_request_queue", ".", "put", "(", "requests", ".", "LeaseRequest", "(", "ack_id", "=", "self", ".", "_ack_id", ",", "byte_size", "=", "self", ".", "size", ")", ")" ]
Inform the policy to lease this message continually. .. note:: This method is called by the constructor, and you should never need to call it manually.
[ "Inform", "the", "policy", "to", "lease", "this", "message", "continually", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L207-L216
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/message.py
Message.modify_ack_deadline
def modify_ack_deadline(self, seconds): """Resets the deadline for acknowledgement. New deadline will be the given value of seconds from now. The default implementation handles this for you; you should not need to manually deal with setting ack deadlines. The exception case is if you are implementing your own custom subclass of :class:`~.pubsub_v1.subcriber._consumer.Consumer`. Args: seconds (int): The number of seconds to set the lease deadline to. This should be between 0 and 600. Due to network latency, values below 10 are advised against. """ self._request_queue.put( requests.ModAckRequest(ack_id=self._ack_id, seconds=seconds) )
python
def modify_ack_deadline(self, seconds): """Resets the deadline for acknowledgement. New deadline will be the given value of seconds from now. The default implementation handles this for you; you should not need to manually deal with setting ack deadlines. The exception case is if you are implementing your own custom subclass of :class:`~.pubsub_v1.subcriber._consumer.Consumer`. Args: seconds (int): The number of seconds to set the lease deadline to. This should be between 0 and 600. Due to network latency, values below 10 are advised against. """ self._request_queue.put( requests.ModAckRequest(ack_id=self._ack_id, seconds=seconds) )
[ "def", "modify_ack_deadline", "(", "self", ",", "seconds", ")", ":", "self", ".", "_request_queue", ".", "put", "(", "requests", ".", "ModAckRequest", "(", "ack_id", "=", "self", ".", "_ack_id", ",", "seconds", "=", "seconds", ")", ")" ]
Resets the deadline for acknowledgement. New deadline will be the given value of seconds from now. The default implementation handles this for you; you should not need to manually deal with setting ack deadlines. The exception case is if you are implementing your own custom subclass of :class:`~.pubsub_v1.subcriber._consumer.Consumer`. Args: seconds (int): The number of seconds to set the lease deadline to. This should be between 0 and 600. Due to network latency, values below 10 are advised against.
[ "Resets", "the", "deadline", "for", "acknowledgement", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L218-L235
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/message.py
Message.nack
def nack(self): """Decline to acknowldge the given message. This will cause the message to be re-delivered to the subscription. """ self._request_queue.put( requests.NackRequest(ack_id=self._ack_id, byte_size=self.size) )
python
def nack(self): """Decline to acknowldge the given message. This will cause the message to be re-delivered to the subscription. """ self._request_queue.put( requests.NackRequest(ack_id=self._ack_id, byte_size=self.size) )
[ "def", "nack", "(", "self", ")", ":", "self", ".", "_request_queue", ".", "put", "(", "requests", ".", "NackRequest", "(", "ack_id", "=", "self", ".", "_ack_id", ",", "byte_size", "=", "self", ".", "size", ")", ")" ]
Decline to acknowldge the given message. This will cause the message to be re-delivered to the subscription.
[ "Decline", "to", "acknowldge", "the", "given", "message", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/message.py#L237-L244
train
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/magics.py
_run_query
def _run_query(client, query, job_config=None): """Runs a query while printing status updates Args: client (google.cloud.bigquery.client.Client): Client to bundle configuration needed for API requests. query (str): SQL query to be executed. Defaults to the standard SQL dialect. Use the ``job_config`` parameter to change dialects. job_config (google.cloud.bigquery.job.QueryJobConfig, optional): Extra configuration options for the job. Returns: google.cloud.bigquery.job.QueryJob: the query job created Example: >>> client = bigquery.Client() >>> _run_query(client, "SELECT 17") Executing query with job ID: bf633912-af2c-4780-b568-5d868058632b Query executing: 1.66s Query complete after 2.07s 'bf633912-af2c-4780-b568-5d868058632b' """ start_time = time.time() query_job = client.query(query, job_config=job_config) print("Executing query with job ID: {}".format(query_job.job_id)) while True: print("\rQuery executing: {:0.2f}s".format(time.time() - start_time), end="") try: query_job.result(timeout=0.5) break except futures.TimeoutError: continue print("\nQuery complete after {:0.2f}s".format(time.time() - start_time)) return query_job
python
def _run_query(client, query, job_config=None): """Runs a query while printing status updates Args: client (google.cloud.bigquery.client.Client): Client to bundle configuration needed for API requests. query (str): SQL query to be executed. Defaults to the standard SQL dialect. Use the ``job_config`` parameter to change dialects. job_config (google.cloud.bigquery.job.QueryJobConfig, optional): Extra configuration options for the job. Returns: google.cloud.bigquery.job.QueryJob: the query job created Example: >>> client = bigquery.Client() >>> _run_query(client, "SELECT 17") Executing query with job ID: bf633912-af2c-4780-b568-5d868058632b Query executing: 1.66s Query complete after 2.07s 'bf633912-af2c-4780-b568-5d868058632b' """ start_time = time.time() query_job = client.query(query, job_config=job_config) print("Executing query with job ID: {}".format(query_job.job_id)) while True: print("\rQuery executing: {:0.2f}s".format(time.time() - start_time), end="") try: query_job.result(timeout=0.5) break except futures.TimeoutError: continue print("\nQuery complete after {:0.2f}s".format(time.time() - start_time)) return query_job
[ "def", "_run_query", "(", "client", ",", "query", ",", "job_config", "=", "None", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "query_job", "=", "client", ".", "query", "(", "query", ",", "job_config", "=", "job_config", ")", "print", "(", "\"Executing query with job ID: {}\"", ".", "format", "(", "query_job", ".", "job_id", ")", ")", "while", "True", ":", "print", "(", "\"\\rQuery executing: {:0.2f}s\"", ".", "format", "(", "time", ".", "time", "(", ")", "-", "start_time", ")", ",", "end", "=", "\"\"", ")", "try", ":", "query_job", ".", "result", "(", "timeout", "=", "0.5", ")", "break", "except", "futures", ".", "TimeoutError", ":", "continue", "print", "(", "\"\\nQuery complete after {:0.2f}s\"", ".", "format", "(", "time", ".", "time", "(", ")", "-", "start_time", ")", ")", "return", "query_job" ]
Runs a query while printing status updates Args: client (google.cloud.bigquery.client.Client): Client to bundle configuration needed for API requests. query (str): SQL query to be executed. Defaults to the standard SQL dialect. Use the ``job_config`` parameter to change dialects. job_config (google.cloud.bigquery.job.QueryJobConfig, optional): Extra configuration options for the job. Returns: google.cloud.bigquery.job.QueryJob: the query job created Example: >>> client = bigquery.Client() >>> _run_query(client, "SELECT 17") Executing query with job ID: bf633912-af2c-4780-b568-5d868058632b Query executing: 1.66s Query complete after 2.07s 'bf633912-af2c-4780-b568-5d868058632b'
[ "Runs", "a", "query", "while", "printing", "status", "updates" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/magics.py#L243-L278
train
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/magics.py
_cell_magic
def _cell_magic(line, query): """Underlying function for bigquery cell magic Note: This function contains the underlying logic for the 'bigquery' cell magic. This function is not meant to be called directly. Args: line (str): "%%bigquery" followed by arguments as required query (str): SQL query to run Returns: pandas.DataFrame: the query results. """ args = magic_arguments.parse_argstring(_cell_magic, line) params = [] if args.params is not None: try: params = _helpers.to_query_parameters( ast.literal_eval("".join(args.params)) ) except Exception: raise SyntaxError( "--params is not a correctly formatted JSON string or a JSON " "serializable dictionary" ) project = args.project or context.project client = bigquery.Client(project=project, credentials=context.credentials) bqstorage_client = _make_bqstorage_client( args.use_bqstorage_api or context.use_bqstorage_api, context.credentials ) job_config = bigquery.job.QueryJobConfig() job_config.query_parameters = params job_config.use_legacy_sql = args.use_legacy_sql query_job = _run_query(client, query, job_config) if not args.verbose: display.clear_output() result = query_job.to_dataframe(bqstorage_client=bqstorage_client) if args.destination_var: IPython.get_ipython().push({args.destination_var: result}) else: return result
python
def _cell_magic(line, query): """Underlying function for bigquery cell magic Note: This function contains the underlying logic for the 'bigquery' cell magic. This function is not meant to be called directly. Args: line (str): "%%bigquery" followed by arguments as required query (str): SQL query to run Returns: pandas.DataFrame: the query results. """ args = magic_arguments.parse_argstring(_cell_magic, line) params = [] if args.params is not None: try: params = _helpers.to_query_parameters( ast.literal_eval("".join(args.params)) ) except Exception: raise SyntaxError( "--params is not a correctly formatted JSON string or a JSON " "serializable dictionary" ) project = args.project or context.project client = bigquery.Client(project=project, credentials=context.credentials) bqstorage_client = _make_bqstorage_client( args.use_bqstorage_api or context.use_bqstorage_api, context.credentials ) job_config = bigquery.job.QueryJobConfig() job_config.query_parameters = params job_config.use_legacy_sql = args.use_legacy_sql query_job = _run_query(client, query, job_config) if not args.verbose: display.clear_output() result = query_job.to_dataframe(bqstorage_client=bqstorage_client) if args.destination_var: IPython.get_ipython().push({args.destination_var: result}) else: return result
[ "def", "_cell_magic", "(", "line", ",", "query", ")", ":", "args", "=", "magic_arguments", ".", "parse_argstring", "(", "_cell_magic", ",", "line", ")", "params", "=", "[", "]", "if", "args", ".", "params", "is", "not", "None", ":", "try", ":", "params", "=", "_helpers", ".", "to_query_parameters", "(", "ast", ".", "literal_eval", "(", "\"\"", ".", "join", "(", "args", ".", "params", ")", ")", ")", "except", "Exception", ":", "raise", "SyntaxError", "(", "\"--params is not a correctly formatted JSON string or a JSON \"", "\"serializable dictionary\"", ")", "project", "=", "args", ".", "project", "or", "context", ".", "project", "client", "=", "bigquery", ".", "Client", "(", "project", "=", "project", ",", "credentials", "=", "context", ".", "credentials", ")", "bqstorage_client", "=", "_make_bqstorage_client", "(", "args", ".", "use_bqstorage_api", "or", "context", ".", "use_bqstorage_api", ",", "context", ".", "credentials", ")", "job_config", "=", "bigquery", ".", "job", ".", "QueryJobConfig", "(", ")", "job_config", ".", "query_parameters", "=", "params", "job_config", ".", "use_legacy_sql", "=", "args", ".", "use_legacy_sql", "query_job", "=", "_run_query", "(", "client", ",", "query", ",", "job_config", ")", "if", "not", "args", ".", "verbose", ":", "display", ".", "clear_output", "(", ")", "result", "=", "query_job", ".", "to_dataframe", "(", "bqstorage_client", "=", "bqstorage_client", ")", "if", "args", ".", "destination_var", ":", "IPython", ".", "get_ipython", "(", ")", ".", "push", "(", "{", "args", ".", "destination_var", ":", "result", "}", ")", "else", ":", "return", "result" ]
Underlying function for bigquery cell magic Note: This function contains the underlying logic for the 'bigquery' cell magic. This function is not meant to be called directly. Args: line (str): "%%bigquery" followed by arguments as required query (str): SQL query to run Returns: pandas.DataFrame: the query results.
[ "Underlying", "function", "for", "bigquery", "cell", "magic" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/magics.py#L336-L381
train
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/magics.py
Context.credentials
def credentials(self): """google.auth.credentials.Credentials: Credentials to use for queries performed through IPython magics Note: These credentials do not need to be explicitly defined if you are using Application Default Credentials. If you are not using Application Default Credentials, manually construct a :class:`google.auth.credentials.Credentials` object and set it as the context credentials as demonstrated in the example below. See `auth docs`_ for more information on obtaining credentials. Example: Manually setting the context credentials: >>> from google.cloud.bigquery import magics >>> from google.oauth2 import service_account >>> credentials = (service_account ... .Credentials.from_service_account_file( ... '/path/to/key.json')) >>> magics.context.credentials = credentials .. _auth docs: http://google-auth.readthedocs.io /en/latest/user-guide.html#obtaining-credentials """ if self._credentials is None: self._credentials, _ = google.auth.default() return self._credentials
python
def credentials(self): """google.auth.credentials.Credentials: Credentials to use for queries performed through IPython magics Note: These credentials do not need to be explicitly defined if you are using Application Default Credentials. If you are not using Application Default Credentials, manually construct a :class:`google.auth.credentials.Credentials` object and set it as the context credentials as demonstrated in the example below. See `auth docs`_ for more information on obtaining credentials. Example: Manually setting the context credentials: >>> from google.cloud.bigquery import magics >>> from google.oauth2 import service_account >>> credentials = (service_account ... .Credentials.from_service_account_file( ... '/path/to/key.json')) >>> magics.context.credentials = credentials .. _auth docs: http://google-auth.readthedocs.io /en/latest/user-guide.html#obtaining-credentials """ if self._credentials is None: self._credentials, _ = google.auth.default() return self._credentials
[ "def", "credentials", "(", "self", ")", ":", "if", "self", ".", "_credentials", "is", "None", ":", "self", ".", "_credentials", ",", "_", "=", "google", ".", "auth", ".", "default", "(", ")", "return", "self", ".", "_credentials" ]
google.auth.credentials.Credentials: Credentials to use for queries performed through IPython magics Note: These credentials do not need to be explicitly defined if you are using Application Default Credentials. If you are not using Application Default Credentials, manually construct a :class:`google.auth.credentials.Credentials` object and set it as the context credentials as demonstrated in the example below. See `auth docs`_ for more information on obtaining credentials. Example: Manually setting the context credentials: >>> from google.cloud.bigquery import magics >>> from google.oauth2 import service_account >>> credentials = (service_account ... .Credentials.from_service_account_file( ... '/path/to/key.json')) >>> magics.context.credentials = credentials .. _auth docs: http://google-auth.readthedocs.io /en/latest/user-guide.html#obtaining-credentials
[ "google", ".", "auth", ".", "credentials", ".", "Credentials", ":", "Credentials", "to", "use", "for", "queries", "performed", "through", "IPython", "magics" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/magics.py#L165-L193
train
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/magics.py
Context.project
def project(self): """str: Default project to use for queries performed through IPython magics Note: The project does not need to be explicitly defined if you have an environment default project set. If you do not have a default project set in your environment, manually assign the project as demonstrated in the example below. Example: Manually setting the context project: >>> from google.cloud.bigquery import magics >>> magics.context.project = 'my-project' """ if self._project is None: _, self._project = google.auth.default() return self._project
python
def project(self): """str: Default project to use for queries performed through IPython magics Note: The project does not need to be explicitly defined if you have an environment default project set. If you do not have a default project set in your environment, manually assign the project as demonstrated in the example below. Example: Manually setting the context project: >>> from google.cloud.bigquery import magics >>> magics.context.project = 'my-project' """ if self._project is None: _, self._project = google.auth.default() return self._project
[ "def", "project", "(", "self", ")", ":", "if", "self", ".", "_project", "is", "None", ":", "_", ",", "self", ".", "_project", "=", "google", ".", "auth", ".", "default", "(", ")", "return", "self", ".", "_project" ]
str: Default project to use for queries performed through IPython magics Note: The project does not need to be explicitly defined if you have an environment default project set. If you do not have a default project set in your environment, manually assign the project as demonstrated in the example below. Example: Manually setting the context project: >>> from google.cloud.bigquery import magics >>> magics.context.project = 'my-project'
[ "str", ":", "Default", "project", "to", "use", "for", "queries", "performed", "through", "IPython", "magics" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/magics.py#L200-L218
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.database_root_path
def database_root_path(cls, project, database): """Return a fully-qualified database_root string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}", project=project, database=database, )
python
def database_root_path(cls, project, database): """Return a fully-qualified database_root string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}", project=project, database=database, )
[ "def", "database_root_path", "(", "cls", ",", "project", ",", "database", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/databases/{database}\"", ",", "project", "=", "project", ",", "database", "=", "database", ",", ")" ]
Return a fully-qualified database_root string.
[ "Return", "a", "fully", "-", "qualified", "database_root", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L99-L105
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.document_root_path
def document_root_path(cls, project, database): """Return a fully-qualified document_root string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents", project=project, database=database, )
python
def document_root_path(cls, project, database): """Return a fully-qualified document_root string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents", project=project, database=database, )
[ "def", "document_root_path", "(", "cls", ",", "project", ",", "database", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/databases/{database}/documents\"", ",", "project", "=", "project", ",", "database", "=", "database", ",", ")" ]
Return a fully-qualified document_root string.
[ "Return", "a", "fully", "-", "qualified", "document_root", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L108-L114
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.document_path_path
def document_path_path(cls, project, database, document_path): """Return a fully-qualified document_path string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents/{document_path=**}", project=project, database=database, document_path=document_path, )
python
def document_path_path(cls, project, database, document_path): """Return a fully-qualified document_path string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents/{document_path=**}", project=project, database=database, document_path=document_path, )
[ "def", "document_path_path", "(", "cls", ",", "project", ",", "database", ",", "document_path", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/databases/{database}/documents/{document_path=**}\"", ",", "project", "=", "project", ",", "database", "=", "database", ",", "document_path", "=", "document_path", ",", ")" ]
Return a fully-qualified document_path string.
[ "Return", "a", "fully", "-", "qualified", "document_path", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L117-L124
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.any_path_path
def any_path_path(cls, project, database, document, any_path): """Return a fully-qualified any_path string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents/{document}/{any_path=**}", project=project, database=database, document=document, any_path=any_path, )
python
def any_path_path(cls, project, database, document, any_path): """Return a fully-qualified any_path string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents/{document}/{any_path=**}", project=project, database=database, document=document, any_path=any_path, )
[ "def", "any_path_path", "(", "cls", ",", "project", ",", "database", ",", "document", ",", "any_path", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/databases/{database}/documents/{document}/{any_path=**}\"", ",", "project", "=", "project", ",", "database", "=", "database", ",", "document", "=", "document", ",", "any_path", "=", "any_path", ",", ")" ]
Return a fully-qualified any_path string.
[ "Return", "a", "fully", "-", "qualified", "any_path", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L127-L135
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.get_document
def get_document( self, name, mask=None, transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets a single document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> response = client.get_document(name) Args: name (str): The resource name of the Document to get. In the format: ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If the document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` transaction (bytes): Reads the document in a transaction. read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads the version of the document at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.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.firestore_v1beta1.types.Document` 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_document" not in self._inner_api_calls: self._inner_api_calls[ "get_document" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_document, default_retry=self._method_configs["GetDocument"].retry, default_timeout=self._method_configs["GetDocument"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction=transaction, read_time=read_time ) request = firestore_pb2.GetDocumentRequest( name=name, mask=mask, transaction=transaction, read_time=read_time ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_document"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def get_document( self, name, mask=None, transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets a single document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> response = client.get_document(name) Args: name (str): The resource name of the Document to get. In the format: ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If the document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` transaction (bytes): Reads the document in a transaction. read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads the version of the document at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.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.firestore_v1beta1.types.Document` 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_document" not in self._inner_api_calls: self._inner_api_calls[ "get_document" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_document, default_retry=self._method_configs["GetDocument"].retry, default_timeout=self._method_configs["GetDocument"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction=transaction, read_time=read_time ) request = firestore_pb2.GetDocumentRequest( name=name, mask=mask, transaction=transaction, read_time=read_time ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_document"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "get_document", "(", "self", ",", "name", ",", "mask", "=", "None", ",", "transaction", "=", "None", ",", "read_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", "\"get_document\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"get_document\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "get_document", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"GetDocument\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"GetDocument\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "transaction", "=", "transaction", ",", "read_time", "=", "read_time", ")", "request", "=", "firestore_pb2", ".", "GetDocumentRequest", "(", "name", "=", "name", ",", "mask", "=", "mask", ",", "transaction", "=", "transaction", ",", "read_time", "=", "read_time", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"name\"", ",", "name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"get_document\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Gets a single document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> response = client.get_document(name) Args: name (str): The resource name of the Document to get. In the format: ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If the document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` transaction (bytes): Reads the document in a transaction. read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads the version of the document at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.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.firestore_v1beta1.types.Document` 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", "a", "single", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L236-L328
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.list_documents
def list_documents( self, parent, collection_id, page_size=None, order_by=None, mask=None, transaction=None, read_time=None, show_missing=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists documents. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> # TODO: Initialize `collection_id`: >>> collection_id = '' >>> >>> # Iterate over all results >>> for element in client.list_documents(parent, collection_id): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_documents(parent, collection_id).pages: ... for element in page: ... # process element ... pass Args: parent (str): The parent resource name. In the format: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. For example: ``projects/my-project/databases/my-database/documents`` or ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`` collection_id (str): The collection ID, relative to ``parent``, to list. For example: ``chatrooms`` or ``messages``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. order_by (str): The order to sort results by. For example: ``priority desc, name``. mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If a document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` transaction (bytes): Reads documents in a transaction. read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Timestamp` show_missing (bool): If the list should show missing documents. A missing document is a document that does not exist but has sub-documents. These documents will be returned with a key but will not have fields, ``Document.create_time``, or ``Document.update_time`` set. Requests with ``show_missing`` may not specify ``where`` or ``order_by``. 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.firestore_v1beta1.types.Document` 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_documents" not in self._inner_api_calls: self._inner_api_calls[ "list_documents" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_documents, default_retry=self._method_configs["ListDocuments"].retry, default_timeout=self._method_configs["ListDocuments"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction=transaction, read_time=read_time ) request = firestore_pb2.ListDocumentsRequest( parent=parent, collection_id=collection_id, page_size=page_size, order_by=order_by, mask=mask, transaction=transaction, read_time=read_time, show_missing=show_missing, ) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_documents"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="documents", request_token_field="page_token", response_token_field="next_page_token", ) return iterator
python
def list_documents( self, parent, collection_id, page_size=None, order_by=None, mask=None, transaction=None, read_time=None, show_missing=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists documents. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> # TODO: Initialize `collection_id`: >>> collection_id = '' >>> >>> # Iterate over all results >>> for element in client.list_documents(parent, collection_id): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_documents(parent, collection_id).pages: ... for element in page: ... # process element ... pass Args: parent (str): The parent resource name. In the format: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. For example: ``projects/my-project/databases/my-database/documents`` or ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`` collection_id (str): The collection ID, relative to ``parent``, to list. For example: ``chatrooms`` or ``messages``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. order_by (str): The order to sort results by. For example: ``priority desc, name``. mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If a document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` transaction (bytes): Reads documents in a transaction. read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Timestamp` show_missing (bool): If the list should show missing documents. A missing document is a document that does not exist but has sub-documents. These documents will be returned with a key but will not have fields, ``Document.create_time``, or ``Document.update_time`` set. Requests with ``show_missing`` may not specify ``where`` or ``order_by``. 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.firestore_v1beta1.types.Document` 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_documents" not in self._inner_api_calls: self._inner_api_calls[ "list_documents" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_documents, default_retry=self._method_configs["ListDocuments"].retry, default_timeout=self._method_configs["ListDocuments"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction=transaction, read_time=read_time ) request = firestore_pb2.ListDocumentsRequest( parent=parent, collection_id=collection_id, page_size=page_size, order_by=order_by, mask=mask, transaction=transaction, read_time=read_time, show_missing=show_missing, ) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_documents"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="documents", request_token_field="page_token", response_token_field="next_page_token", ) return iterator
[ "def", "list_documents", "(", "self", ",", "parent", ",", "collection_id", ",", "page_size", "=", "None", ",", "order_by", "=", "None", ",", "mask", "=", "None", ",", "transaction", "=", "None", ",", "read_time", "=", "None", ",", "show_missing", "=", "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_documents\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"list_documents\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "list_documents", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"ListDocuments\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"ListDocuments\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "transaction", "=", "transaction", ",", "read_time", "=", "read_time", ")", "request", "=", "firestore_pb2", ".", "ListDocumentsRequest", "(", "parent", "=", "parent", ",", "collection_id", "=", "collection_id", ",", "page_size", "=", "page_size", ",", "order_by", "=", "order_by", ",", "mask", "=", "mask", ",", "transaction", "=", "transaction", ",", "read_time", "=", "read_time", ",", "show_missing", "=", "show_missing", ",", ")", "iterator", "=", "google", ".", "api_core", ".", "page_iterator", ".", "GRPCIterator", "(", "client", "=", "None", ",", "method", "=", "functools", ".", "partial", "(", "self", ".", "_inner_api_calls", "[", "\"list_documents\"", "]", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ",", ")", ",", "request", "=", "request", ",", "items_field", "=", "\"documents\"", ",", "request_token_field", "=", "\"page_token\"", ",", "response_token_field", "=", "\"next_page_token\"", ",", ")", "return", "iterator" ]
Lists documents. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> # TODO: Initialize `collection_id`: >>> collection_id = '' >>> >>> # Iterate over all results >>> for element in client.list_documents(parent, collection_id): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_documents(parent, collection_id).pages: ... for element in page: ... # process element ... pass Args: parent (str): The parent resource name. In the format: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. For example: ``projects/my-project/databases/my-database/documents`` or ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`` collection_id (str): The collection ID, relative to ``parent``, to list. For example: ``chatrooms`` or ``messages``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. order_by (str): The order to sort results by. For example: ``priority desc, name``. mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If a document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` transaction (bytes): Reads documents in a transaction. read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Timestamp` show_missing (bool): If the list should show missing documents. A missing document is a document that does not exist but has sub-documents. These documents will be returned with a key but will not have fields, ``Document.create_time``, or ``Document.update_time`` set. Requests with ``show_missing`` may not specify ``where`` or ``order_by``. 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.firestore_v1beta1.types.Document` 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", "documents", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L330-L467
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.create_document
def create_document( self, parent, collection_id, document_id, document, mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> # TODO: Initialize `collection_id`: >>> collection_id = '' >>> >>> # TODO: Initialize `document_id`: >>> document_id = '' >>> >>> # TODO: Initialize `document`: >>> document = {} >>> >>> response = client.create_document(parent, collection_id, document_id, document) Args: parent (str): The parent resource. For example: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}`` collection_id (str): The collection ID, relative to ``parent``, to list. For example: ``chatrooms``. document_id (str): The client-assigned document ID to use for this document. Optional. If not specified, an ID will be assigned by the service. document (Union[dict, ~google.cloud.firestore_v1beta1.types.Document]): The document to create. ``name`` must not be set. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Document` mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If the document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` 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.firestore_v1beta1.types.Document` 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_document" not in self._inner_api_calls: self._inner_api_calls[ "create_document" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_document, default_retry=self._method_configs["CreateDocument"].retry, default_timeout=self._method_configs["CreateDocument"].timeout, client_info=self._client_info, ) request = firestore_pb2.CreateDocumentRequest( parent=parent, collection_id=collection_id, document_id=document_id, document=document, mask=mask, ) return self._inner_api_calls["create_document"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_document( self, parent, collection_id, document_id, document, mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> # TODO: Initialize `collection_id`: >>> collection_id = '' >>> >>> # TODO: Initialize `document_id`: >>> document_id = '' >>> >>> # TODO: Initialize `document`: >>> document = {} >>> >>> response = client.create_document(parent, collection_id, document_id, document) Args: parent (str): The parent resource. For example: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}`` collection_id (str): The collection ID, relative to ``parent``, to list. For example: ``chatrooms``. document_id (str): The client-assigned document ID to use for this document. Optional. If not specified, an ID will be assigned by the service. document (Union[dict, ~google.cloud.firestore_v1beta1.types.Document]): The document to create. ``name`` must not be set. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Document` mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If the document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` 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.firestore_v1beta1.types.Document` 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_document" not in self._inner_api_calls: self._inner_api_calls[ "create_document" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_document, default_retry=self._method_configs["CreateDocument"].retry, default_timeout=self._method_configs["CreateDocument"].timeout, client_info=self._client_info, ) request = firestore_pb2.CreateDocumentRequest( parent=parent, collection_id=collection_id, document_id=document_id, document=document, mask=mask, ) return self._inner_api_calls["create_document"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_document", "(", "self", ",", "parent", ",", "collection_id", ",", "document_id", ",", "document", ",", "mask", "=", "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_document\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_document\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_document", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateDocument\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateDocument\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "firestore_pb2", ".", "CreateDocumentRequest", "(", "parent", "=", "parent", ",", "collection_id", "=", "collection_id", ",", "document_id", "=", "document_id", ",", "document", "=", "document", ",", "mask", "=", "mask", ",", ")", "return", "self", ".", "_inner_api_calls", "[", "\"create_document\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a new document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> # TODO: Initialize `collection_id`: >>> collection_id = '' >>> >>> # TODO: Initialize `document_id`: >>> document_id = '' >>> >>> # TODO: Initialize `document`: >>> document = {} >>> >>> response = client.create_document(parent, collection_id, document_id, document) Args: parent (str): The parent resource. For example: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}`` collection_id (str): The collection ID, relative to ``parent``, to list. For example: ``chatrooms``. document_id (str): The client-assigned document ID to use for this document. Optional. If not specified, an ID will be assigned by the service. document (Union[dict, ~google.cloud.firestore_v1beta1.types.Document]): The document to create. ``name`` must not be set. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Document` mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If the document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` 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.firestore_v1beta1.types.Document` 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", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L469-L560
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.update_document
def update_document( self, document, update_mask, mask=None, current_document=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates or inserts a document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> # TODO: Initialize `document`: >>> document = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_document(document, update_mask) Args: document (Union[dict, ~google.cloud.firestore_v1beta1.types.Document]): The updated document. Creates the document if it does not already exist. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Document` update_mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to update. None of the field paths in the mask may contain a reserved name. If the document exists on the server and has fields not referenced in the mask, they are left unchanged. Fields referenced in the mask, but not present in the input document, are deleted from the document on the server. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If the document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document. The request will fail if this is set and not met by the target document. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Precondition` 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.firestore_v1beta1.types.Document` 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_document" not in self._inner_api_calls: self._inner_api_calls[ "update_document" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_document, default_retry=self._method_configs["UpdateDocument"].retry, default_timeout=self._method_configs["UpdateDocument"].timeout, client_info=self._client_info, ) request = firestore_pb2.UpdateDocumentRequest( document=document, update_mask=update_mask, mask=mask, current_document=current_document, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("document.name", document.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_document"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def update_document( self, document, update_mask, mask=None, current_document=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates or inserts a document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> # TODO: Initialize `document`: >>> document = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_document(document, update_mask) Args: document (Union[dict, ~google.cloud.firestore_v1beta1.types.Document]): The updated document. Creates the document if it does not already exist. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Document` update_mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to update. None of the field paths in the mask may contain a reserved name. If the document exists on the server and has fields not referenced in the mask, they are left unchanged. Fields referenced in the mask, but not present in the input document, are deleted from the document on the server. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If the document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document. The request will fail if this is set and not met by the target document. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Precondition` 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.firestore_v1beta1.types.Document` 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_document" not in self._inner_api_calls: self._inner_api_calls[ "update_document" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_document, default_retry=self._method_configs["UpdateDocument"].retry, default_timeout=self._method_configs["UpdateDocument"].timeout, client_info=self._client_info, ) request = firestore_pb2.UpdateDocumentRequest( document=document, update_mask=update_mask, mask=mask, current_document=current_document, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("document.name", document.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_document"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "update_document", "(", "self", ",", "document", ",", "update_mask", ",", "mask", "=", "None", ",", "current_document", "=", "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_document\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"update_document\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "update_document", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"UpdateDocument\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"UpdateDocument\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "firestore_pb2", ".", "UpdateDocumentRequest", "(", "document", "=", "document", ",", "update_mask", "=", "update_mask", ",", "mask", "=", "mask", ",", "current_document", "=", "current_document", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"document.name\"", ",", "document", ".", "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_document\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Updates or inserts a document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> # TODO: Initialize `document`: >>> document = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_document(document, update_mask) Args: document (Union[dict, ~google.cloud.firestore_v1beta1.types.Document]): The updated document. Creates the document if it does not already exist. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Document` update_mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to update. None of the field paths in the mask may contain a reserved name. If the document exists on the server and has fields not referenced in the mask, they are left unchanged. Fields referenced in the mask, but not present in the input document, are deleted from the document on the server. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If the document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document. The request will fail if this is set and not met by the target document. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Precondition` 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.firestore_v1beta1.types.Document` 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", "or", "inserts", "a", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L562-L667
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.delete_document
def delete_document( self, name, current_document=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> client.delete_document(name) Args: name (str): The resource name of the Document to delete. In the format: ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document. The request will fail if this is set and not met by the target document. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Precondition` 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 "delete_document" not in self._inner_api_calls: self._inner_api_calls[ "delete_document" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_document, default_retry=self._method_configs["DeleteDocument"].retry, default_timeout=self._method_configs["DeleteDocument"].timeout, client_info=self._client_info, ) request = firestore_pb2.DeleteDocumentRequest( name=name, current_document=current_document ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) self._inner_api_calls["delete_document"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def delete_document( self, name, current_document=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> client.delete_document(name) Args: name (str): The resource name of the Document to delete. In the format: ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document. The request will fail if this is set and not met by the target document. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Precondition` 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 "delete_document" not in self._inner_api_calls: self._inner_api_calls[ "delete_document" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_document, default_retry=self._method_configs["DeleteDocument"].retry, default_timeout=self._method_configs["DeleteDocument"].timeout, client_info=self._client_info, ) request = firestore_pb2.DeleteDocumentRequest( name=name, current_document=current_document ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) self._inner_api_calls["delete_document"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "delete_document", "(", "self", ",", "name", ",", "current_document", "=", "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", "\"delete_document\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"delete_document\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "delete_document", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"DeleteDocument\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"DeleteDocument\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "firestore_pb2", ".", "DeleteDocumentRequest", "(", "name", "=", "name", ",", "current_document", "=", "current_document", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"name\"", ",", "name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "self", ".", "_inner_api_calls", "[", "\"delete_document\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Deletes a document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> client.delete_document(name) Args: name (str): The resource name of the Document to delete. In the format: ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document. The request will fail if this is set and not met by the target document. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Precondition` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "a", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L669-L742
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.batch_get_documents
def batch_get_documents( self, database, documents, mask=None, transaction=None, new_transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets multiple documents. Documents returned by this method are not guaranteed to be returned in the same order that they were requested. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> >>> # TODO: Initialize `documents`: >>> documents = [] >>> >>> for element in client.batch_get_documents(database, documents): ... # process element ... pass Args: database (str): The database name. In the format: ``projects/{project_id}/databases/{database_id}``. documents (list[str]): The names of the documents to retrieve. In the format: ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. The request will fail if any of the document is not a child resource of the given ``database``. Duplicate names will be elided. mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If a document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` transaction (bytes): Reads documents in a transaction. new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents. Defaults to a read-only transaction. The new transaction ID will be returned as the first response in the stream. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.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: Iterable[~google.cloud.firestore_v1beta1.types.BatchGetDocumentsResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "batch_get_documents" not in self._inner_api_calls: self._inner_api_calls[ "batch_get_documents" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_get_documents, default_retry=self._method_configs["BatchGetDocuments"].retry, default_timeout=self._method_configs["BatchGetDocuments"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) request = firestore_pb2.BatchGetDocumentsRequest( database=database, documents=documents, mask=mask, transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("database", database)] 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["batch_get_documents"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def batch_get_documents( self, database, documents, mask=None, transaction=None, new_transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets multiple documents. Documents returned by this method are not guaranteed to be returned in the same order that they were requested. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> >>> # TODO: Initialize `documents`: >>> documents = [] >>> >>> for element in client.batch_get_documents(database, documents): ... # process element ... pass Args: database (str): The database name. In the format: ``projects/{project_id}/databases/{database_id}``. documents (list[str]): The names of the documents to retrieve. In the format: ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. The request will fail if any of the document is not a child resource of the given ``database``. Duplicate names will be elided. mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If a document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` transaction (bytes): Reads documents in a transaction. new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents. Defaults to a read-only transaction. The new transaction ID will be returned as the first response in the stream. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.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: Iterable[~google.cloud.firestore_v1beta1.types.BatchGetDocumentsResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "batch_get_documents" not in self._inner_api_calls: self._inner_api_calls[ "batch_get_documents" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_get_documents, default_retry=self._method_configs["BatchGetDocuments"].retry, default_timeout=self._method_configs["BatchGetDocuments"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) request = firestore_pb2.BatchGetDocumentsRequest( database=database, documents=documents, mask=mask, transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("database", database)] 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["batch_get_documents"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "batch_get_documents", "(", "self", ",", "database", ",", "documents", ",", "mask", "=", "None", ",", "transaction", "=", "None", ",", "new_transaction", "=", "None", ",", "read_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", "\"batch_get_documents\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"batch_get_documents\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "batch_get_documents", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"BatchGetDocuments\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"BatchGetDocuments\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "transaction", "=", "transaction", ",", "new_transaction", "=", "new_transaction", ",", "read_time", "=", "read_time", ",", ")", "request", "=", "firestore_pb2", ".", "BatchGetDocumentsRequest", "(", "database", "=", "database", ",", "documents", "=", "documents", ",", "mask", "=", "mask", ",", "transaction", "=", "transaction", ",", "new_transaction", "=", "new_transaction", ",", "read_time", "=", "read_time", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"database\"", ",", "database", ")", "]", "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", "[", "\"batch_get_documents\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Gets multiple documents. Documents returned by this method are not guaranteed to be returned in the same order that they were requested. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> >>> # TODO: Initialize `documents`: >>> documents = [] >>> >>> for element in client.batch_get_documents(database, documents): ... # process element ... pass Args: database (str): The database name. In the format: ``projects/{project_id}/databases/{database_id}``. documents (list[str]): The names of the documents to retrieve. In the format: ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. The request will fail if any of the document is not a child resource of the given ``database``. Duplicate names will be elided. mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields. If a document has a field that is not present in this mask, that field will not be returned in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask` transaction (bytes): Reads documents in a transaction. new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents. Defaults to a read-only transaction. The new transaction ID will be returned as the first response in the stream. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.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: Iterable[~google.cloud.firestore_v1beta1.types.BatchGetDocumentsResponse]. 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", "multiple", "documents", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L744-L864
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.begin_transaction
def begin_transaction( self, database, options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a new transaction. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> >>> response = client.begin_transaction(database) Args: database (str): The database name. In the format: ``projects/{project_id}/databases/{database_id}``. options_ (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): The options for the transaction. Defaults to a read-write transaction. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` 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.firestore_v1beta1.types.BeginTransactionResponse` 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 "begin_transaction" not in self._inner_api_calls: self._inner_api_calls[ "begin_transaction" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.begin_transaction, default_retry=self._method_configs["BeginTransaction"].retry, default_timeout=self._method_configs["BeginTransaction"].timeout, client_info=self._client_info, ) request = firestore_pb2.BeginTransactionRequest( database=database, options=options_ ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("database", database)] 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["begin_transaction"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def begin_transaction( self, database, options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a new transaction. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> >>> response = client.begin_transaction(database) Args: database (str): The database name. In the format: ``projects/{project_id}/databases/{database_id}``. options_ (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): The options for the transaction. Defaults to a read-write transaction. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` 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.firestore_v1beta1.types.BeginTransactionResponse` 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 "begin_transaction" not in self._inner_api_calls: self._inner_api_calls[ "begin_transaction" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.begin_transaction, default_retry=self._method_configs["BeginTransaction"].retry, default_timeout=self._method_configs["BeginTransaction"].timeout, client_info=self._client_info, ) request = firestore_pb2.BeginTransactionRequest( database=database, options=options_ ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("database", database)] 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["begin_transaction"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "begin_transaction", "(", "self", ",", "database", ",", "options_", "=", "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", "\"begin_transaction\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"begin_transaction\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "begin_transaction", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"BeginTransaction\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"BeginTransaction\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "firestore_pb2", ".", "BeginTransactionRequest", "(", "database", "=", "database", ",", "options", "=", "options_", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"database\"", ",", "database", ")", "]", "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", "[", "\"begin_transaction\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Starts a new transaction. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> >>> response = client.begin_transaction(database) Args: database (str): The database name. In the format: ``projects/{project_id}/databases/{database_id}``. options_ (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): The options for the transaction. Defaults to a read-write transaction. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` 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.firestore_v1beta1.types.BeginTransactionResponse` 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.
[ "Starts", "a", "new", "transaction", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L866-L942
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.run_query
def run_query( self, parent, structured_query=None, transaction=None, new_transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Runs a query. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> for element in client.run_query(parent): ... # process element ... pass Args: parent (str): The parent resource name. In the format: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. For example: ``projects/my-project/databases/my-database/documents`` or ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`` structured_query (Union[dict, ~google.cloud.firestore_v1beta1.types.StructuredQuery]): A structured query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.StructuredQuery` transaction (bytes): Reads documents in a transaction. new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents. Defaults to a read-only transaction. The new transaction ID will be returned as the first response in the stream. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.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: Iterable[~google.cloud.firestore_v1beta1.types.RunQueryResponse]. 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_query" not in self._inner_api_calls: self._inner_api_calls[ "run_query" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.run_query, default_retry=self._method_configs["RunQuery"].retry, default_timeout=self._method_configs["RunQuery"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof(structured_query=structured_query) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) request = firestore_pb2.RunQueryRequest( parent=parent, structured_query=structured_query, transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) 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["run_query"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def run_query( self, parent, structured_query=None, transaction=None, new_transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Runs a query. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> for element in client.run_query(parent): ... # process element ... pass Args: parent (str): The parent resource name. In the format: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. For example: ``projects/my-project/databases/my-database/documents`` or ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`` structured_query (Union[dict, ~google.cloud.firestore_v1beta1.types.StructuredQuery]): A structured query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.StructuredQuery` transaction (bytes): Reads documents in a transaction. new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents. Defaults to a read-only transaction. The new transaction ID will be returned as the first response in the stream. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.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: Iterable[~google.cloud.firestore_v1beta1.types.RunQueryResponse]. 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_query" not in self._inner_api_calls: self._inner_api_calls[ "run_query" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.run_query, default_retry=self._method_configs["RunQuery"].retry, default_timeout=self._method_configs["RunQuery"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof(structured_query=structured_query) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) request = firestore_pb2.RunQueryRequest( parent=parent, structured_query=structured_query, transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) 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["run_query"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "run_query", "(", "self", ",", "parent", ",", "structured_query", "=", "None", ",", "transaction", "=", "None", ",", "new_transaction", "=", "None", ",", "read_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", "\"run_query\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"run_query\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "run_query", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"RunQuery\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"RunQuery\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "structured_query", "=", "structured_query", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "transaction", "=", "transaction", ",", "new_transaction", "=", "new_transaction", ",", "read_time", "=", "read_time", ",", ")", "request", "=", "firestore_pb2", ".", "RunQueryRequest", "(", "parent", "=", "parent", ",", "structured_query", "=", "structured_query", ",", "transaction", "=", "transaction", ",", "new_transaction", "=", "new_transaction", ",", "read_time", "=", "read_time", ",", ")", "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", "[", "\"run_query\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Runs a query. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> for element in client.run_query(parent): ... # process element ... pass Args: parent (str): The parent resource name. In the format: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. For example: ``projects/my-project/databases/my-database/documents`` or ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`` structured_query (Union[dict, ~google.cloud.firestore_v1beta1.types.StructuredQuery]): A structured query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.StructuredQuery` transaction (bytes): Reads documents in a transaction. new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents. Defaults to a read-only transaction. The new transaction ID will be returned as the first response in the stream. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.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: Iterable[~google.cloud.firestore_v1beta1.types.RunQueryResponse]. 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", "a", "query", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L1102-L1214
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.write
def write( self, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Streams batches of document updates and deletes, in order. EXPERIMENTAL: This method interface might change in the future. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> request = {'database': database} >>> >>> requests = [request] >>> for element in client.write(requests): ... # process element ... pass Args: requests (iterator[dict|google.cloud.firestore_v1beta1.proto.firestore_pb2.WriteRequest]): The input objects. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.WriteRequest` 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: Iterable[~google.cloud.firestore_v1beta1.types.WriteResponse]. 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 "write" not in self._inner_api_calls: self._inner_api_calls[ "write" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.write, default_retry=self._method_configs["Write"].retry, default_timeout=self._method_configs["Write"].timeout, client_info=self._client_info, ) return self._inner_api_calls["write"]( requests, retry=retry, timeout=timeout, metadata=metadata )
python
def write( self, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Streams batches of document updates and deletes, in order. EXPERIMENTAL: This method interface might change in the future. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> request = {'database': database} >>> >>> requests = [request] >>> for element in client.write(requests): ... # process element ... pass Args: requests (iterator[dict|google.cloud.firestore_v1beta1.proto.firestore_pb2.WriteRequest]): The input objects. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.WriteRequest` 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: Iterable[~google.cloud.firestore_v1beta1.types.WriteResponse]. 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 "write" not in self._inner_api_calls: self._inner_api_calls[ "write" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.write, default_retry=self._method_configs["Write"].retry, default_timeout=self._method_configs["Write"].timeout, client_info=self._client_info, ) return self._inner_api_calls["write"]( requests, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "write", "(", "self", ",", "requests", ",", "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", "\"write\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"write\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "write", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"Write\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"Write\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "return", "self", ".", "_inner_api_calls", "[", "\"write\"", "]", "(", "requests", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Streams batches of document updates and deletes, in order. EXPERIMENTAL: This method interface might change in the future. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> request = {'database': database} >>> >>> requests = [request] >>> for element in client.write(requests): ... # process element ... pass Args: requests (iterator[dict|google.cloud.firestore_v1beta1.proto.firestore_pb2.WriteRequest]): The input objects. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.WriteRequest` 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: Iterable[~google.cloud.firestore_v1beta1.types.WriteResponse]. 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.
[ "Streams", "batches", "of", "document", "updates", "and", "deletes", "in", "order", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L1216-L1276
train
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py
LoggingServiceV2Client.log_path
def log_path(cls, project, log): """Return a fully-qualified log string.""" return google.api_core.path_template.expand( "projects/{project}/logs/{log}", project=project, log=log )
python
def log_path(cls, project, log): """Return a fully-qualified log string.""" return google.api_core.path_template.expand( "projects/{project}/logs/{log}", project=project, log=log )
[ "def", "log_path", "(", "cls", ",", "project", ",", "log", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/logs/{log}\"", ",", "project", "=", "project", ",", "log", "=", "log", ")" ]
Return a fully-qualified log string.
[ "Return", "a", "fully", "-", "qualified", "log", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py#L75-L79
train
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py
LoggingServiceV2Client.delete_log
def delete_log( self, log_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> log_name = client.log_path('[PROJECT]', '[LOG]') >>> >>> client.delete_log(log_name) Args: log_name (str): Required. The resource name of the log to delete: :: "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" ``[LOG_ID]`` must be URL-encoded. For example, ``"projects/my-project-id/logs/syslog"``, ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. For more information about log names, see ``LogEntry``. 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 "delete_log" not in self._inner_api_calls: self._inner_api_calls[ "delete_log" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_log, default_retry=self._method_configs["DeleteLog"].retry, default_timeout=self._method_configs["DeleteLog"].timeout, client_info=self._client_info, ) request = logging_pb2.DeleteLogRequest(log_name=log_name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("log_name", log_name)] 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["delete_log"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def delete_log( self, log_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> log_name = client.log_path('[PROJECT]', '[LOG]') >>> >>> client.delete_log(log_name) Args: log_name (str): Required. The resource name of the log to delete: :: "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" ``[LOG_ID]`` must be URL-encoded. For example, ``"projects/my-project-id/logs/syslog"``, ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. For more information about log names, see ``LogEntry``. 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 "delete_log" not in self._inner_api_calls: self._inner_api_calls[ "delete_log" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_log, default_retry=self._method_configs["DeleteLog"].retry, default_timeout=self._method_configs["DeleteLog"].timeout, client_info=self._client_info, ) request = logging_pb2.DeleteLogRequest(log_name=log_name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("log_name", log_name)] 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["delete_log"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "delete_log", "(", "self", ",", "log_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_log\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"delete_log\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "delete_log", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"DeleteLog\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"DeleteLog\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "logging_pb2", ".", "DeleteLogRequest", "(", "log_name", "=", "log_name", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"log_name\"", ",", "log_name", ")", "]", "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", "[", "\"delete_log\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> log_name = client.log_path('[PROJECT]', '[LOG]') >>> >>> client.delete_log(log_name) Args: log_name (str): Required. The resource name of the log to delete: :: "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" ``[LOG_ID]`` must be URL-encoded. For example, ``"projects/my-project-id/logs/syslog"``, ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. For more information about log names, see ``LogEntry``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "all", "the", "log", "entries", "in", "a", "log", ".", "The", "log", "reappears", "if", "it", "receives", "new", "entries", ".", "Log", "entries", "written", "shortly", "before", "the", "delete", "operation", "might", "not", "be", "deleted", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py#L187-L266
train
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py
LoggingServiceV2Client.write_log_entries
def write_log_entries( self, entries, log_name=None, resource=None, labels=None, partial_success=None, dry_run=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent (fluentd) and all logging libraries configured to use Logging. A single request may contain log entries for a maximum of 1000 different resources (projects, organizations, billing accounts or folders) Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> # TODO: Initialize `entries`: >>> entries = [] >>> >>> response = client.write_log_entries(entries) Args: entries (list[Union[dict, ~google.cloud.logging_v2.types.LogEntry]]): Required. The log entries to send to Logging. The order of log entries in this list does not matter. Values supplied in this method's ``log_name``, ``resource``, and ``labels`` fields are copied into those log entries in this list that do not include values for their corresponding fields. For more information, see the ``LogEntry`` type. If the ``timestamp`` or ``insert_id`` fields are missing in log entries, then this method supplies the current time or a unique identifier, respectively. The supplied values are chosen so that, among the log entries that did not supply their own values, the entries earlier in the list will sort before the entries later in the list. See the ``entries.list`` method. Log entries with timestamps that are more than the `logs retention period <https://cloud.google.com/logging/quota-policy>`__ in the past or more than 24 hours in the future will not be available when calling ``entries.list``. However, those log entries can still be exported with `LogSinks <https://cloud.google.com/logging/docs/api/tasks/exporting-logs>`__. To improve throughput and to avoid exceeding the `quota limit <https://cloud.google.com/logging/quota-policy>`__ for calls to ``entries.write``, you should try to include several log entries in this list, rather than calling this method for each individual log entry. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogEntry` log_name (str): Optional. A default log resource name that is assigned to all log entries in ``entries`` that do not specify a value for ``log_name``: :: "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" ``[LOG_ID]`` must be URL-encoded. For example: :: "projects/my-project-id/logs/syslog" "organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity" The permission logging.logEntries.create is needed on each project, organization, billing account, or folder that is receiving new log entries, whether the resource is specified in logName or in an individual log entry. resource (Union[dict, ~google.cloud.logging_v2.types.MonitoredResource]): Optional. A default monitored resource object that is assigned to all log entries in ``entries`` that do not specify a value for ``resource``. Example: :: { "type": "gce_instance", "labels": { "zone": "us-central1-a", "instance_id": "00000000000000000000" }} See ``LogEntry``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.MonitoredResource` labels (dict[str -> str]): Optional. Default labels that are added to the ``labels`` field of all log entries in ``entries``. If a log entry already has a label with the same key as a label in this parameter, then the log entry's label is not changed. See ``LogEntry``. partial_success (bool): Optional. Whether valid entries should be written even if some other entries fail due to INVALID\_ARGUMENT or PERMISSION\_DENIED errors. If any entry is not written, then the response status is the error associated with one of the failed entries and the response includes error details keyed by the entries' zero-based index in the ``entries.write`` method. dry_run (bool): Optional. If true, the request should expect normal response, but the entries won't be persisted nor exported. Useful for checking whether the logging API endpoints are working properly before sending valuable data. 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.logging_v2.types.WriteLogEntriesResponse` 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 "write_log_entries" not in self._inner_api_calls: self._inner_api_calls[ "write_log_entries" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.write_log_entries, default_retry=self._method_configs["WriteLogEntries"].retry, default_timeout=self._method_configs["WriteLogEntries"].timeout, client_info=self._client_info, ) request = logging_pb2.WriteLogEntriesRequest( entries=entries, log_name=log_name, resource=resource, labels=labels, partial_success=partial_success, dry_run=dry_run, ) return self._inner_api_calls["write_log_entries"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def write_log_entries( self, entries, log_name=None, resource=None, labels=None, partial_success=None, dry_run=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent (fluentd) and all logging libraries configured to use Logging. A single request may contain log entries for a maximum of 1000 different resources (projects, organizations, billing accounts or folders) Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> # TODO: Initialize `entries`: >>> entries = [] >>> >>> response = client.write_log_entries(entries) Args: entries (list[Union[dict, ~google.cloud.logging_v2.types.LogEntry]]): Required. The log entries to send to Logging. The order of log entries in this list does not matter. Values supplied in this method's ``log_name``, ``resource``, and ``labels`` fields are copied into those log entries in this list that do not include values for their corresponding fields. For more information, see the ``LogEntry`` type. If the ``timestamp`` or ``insert_id`` fields are missing in log entries, then this method supplies the current time or a unique identifier, respectively. The supplied values are chosen so that, among the log entries that did not supply their own values, the entries earlier in the list will sort before the entries later in the list. See the ``entries.list`` method. Log entries with timestamps that are more than the `logs retention period <https://cloud.google.com/logging/quota-policy>`__ in the past or more than 24 hours in the future will not be available when calling ``entries.list``. However, those log entries can still be exported with `LogSinks <https://cloud.google.com/logging/docs/api/tasks/exporting-logs>`__. To improve throughput and to avoid exceeding the `quota limit <https://cloud.google.com/logging/quota-policy>`__ for calls to ``entries.write``, you should try to include several log entries in this list, rather than calling this method for each individual log entry. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogEntry` log_name (str): Optional. A default log resource name that is assigned to all log entries in ``entries`` that do not specify a value for ``log_name``: :: "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" ``[LOG_ID]`` must be URL-encoded. For example: :: "projects/my-project-id/logs/syslog" "organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity" The permission logging.logEntries.create is needed on each project, organization, billing account, or folder that is receiving new log entries, whether the resource is specified in logName or in an individual log entry. resource (Union[dict, ~google.cloud.logging_v2.types.MonitoredResource]): Optional. A default monitored resource object that is assigned to all log entries in ``entries`` that do not specify a value for ``resource``. Example: :: { "type": "gce_instance", "labels": { "zone": "us-central1-a", "instance_id": "00000000000000000000" }} See ``LogEntry``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.MonitoredResource` labels (dict[str -> str]): Optional. Default labels that are added to the ``labels`` field of all log entries in ``entries``. If a log entry already has a label with the same key as a label in this parameter, then the log entry's label is not changed. See ``LogEntry``. partial_success (bool): Optional. Whether valid entries should be written even if some other entries fail due to INVALID\_ARGUMENT or PERMISSION\_DENIED errors. If any entry is not written, then the response status is the error associated with one of the failed entries and the response includes error details keyed by the entries' zero-based index in the ``entries.write`` method. dry_run (bool): Optional. If true, the request should expect normal response, but the entries won't be persisted nor exported. Useful for checking whether the logging API endpoints are working properly before sending valuable data. 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.logging_v2.types.WriteLogEntriesResponse` 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 "write_log_entries" not in self._inner_api_calls: self._inner_api_calls[ "write_log_entries" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.write_log_entries, default_retry=self._method_configs["WriteLogEntries"].retry, default_timeout=self._method_configs["WriteLogEntries"].timeout, client_info=self._client_info, ) request = logging_pb2.WriteLogEntriesRequest( entries=entries, log_name=log_name, resource=resource, labels=labels, partial_success=partial_success, dry_run=dry_run, ) return self._inner_api_calls["write_log_entries"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "write_log_entries", "(", "self", ",", "entries", ",", "log_name", "=", "None", ",", "resource", "=", "None", ",", "labels", "=", "None", ",", "partial_success", "=", "None", ",", "dry_run", "=", "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", "\"write_log_entries\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"write_log_entries\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "write_log_entries", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"WriteLogEntries\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"WriteLogEntries\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "logging_pb2", ".", "WriteLogEntriesRequest", "(", "entries", "=", "entries", ",", "log_name", "=", "log_name", ",", "resource", "=", "resource", ",", "labels", "=", "labels", ",", "partial_success", "=", "partial_success", ",", "dry_run", "=", "dry_run", ",", ")", "return", "self", ".", "_inner_api_calls", "[", "\"write_log_entries\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent (fluentd) and all logging libraries configured to use Logging. A single request may contain log entries for a maximum of 1000 different resources (projects, organizations, billing accounts or folders) Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> # TODO: Initialize `entries`: >>> entries = [] >>> >>> response = client.write_log_entries(entries) Args: entries (list[Union[dict, ~google.cloud.logging_v2.types.LogEntry]]): Required. The log entries to send to Logging. The order of log entries in this list does not matter. Values supplied in this method's ``log_name``, ``resource``, and ``labels`` fields are copied into those log entries in this list that do not include values for their corresponding fields. For more information, see the ``LogEntry`` type. If the ``timestamp`` or ``insert_id`` fields are missing in log entries, then this method supplies the current time or a unique identifier, respectively. The supplied values are chosen so that, among the log entries that did not supply their own values, the entries earlier in the list will sort before the entries later in the list. See the ``entries.list`` method. Log entries with timestamps that are more than the `logs retention period <https://cloud.google.com/logging/quota-policy>`__ in the past or more than 24 hours in the future will not be available when calling ``entries.list``. However, those log entries can still be exported with `LogSinks <https://cloud.google.com/logging/docs/api/tasks/exporting-logs>`__. To improve throughput and to avoid exceeding the `quota limit <https://cloud.google.com/logging/quota-policy>`__ for calls to ``entries.write``, you should try to include several log entries in this list, rather than calling this method for each individual log entry. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogEntry` log_name (str): Optional. A default log resource name that is assigned to all log entries in ``entries`` that do not specify a value for ``log_name``: :: "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" ``[LOG_ID]`` must be URL-encoded. For example: :: "projects/my-project-id/logs/syslog" "organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity" The permission logging.logEntries.create is needed on each project, organization, billing account, or folder that is receiving new log entries, whether the resource is specified in logName or in an individual log entry. resource (Union[dict, ~google.cloud.logging_v2.types.MonitoredResource]): Optional. A default monitored resource object that is assigned to all log entries in ``entries`` that do not specify a value for ``resource``. Example: :: { "type": "gce_instance", "labels": { "zone": "us-central1-a", "instance_id": "00000000000000000000" }} See ``LogEntry``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.MonitoredResource` labels (dict[str -> str]): Optional. Default labels that are added to the ``labels`` field of all log entries in ``entries``. If a log entry already has a label with the same key as a label in this parameter, then the log entry's label is not changed. See ``LogEntry``. partial_success (bool): Optional. Whether valid entries should be written even if some other entries fail due to INVALID\_ARGUMENT or PERMISSION\_DENIED errors. If any entry is not written, then the response status is the error associated with one of the failed entries and the response includes error details keyed by the entries' zero-based index in the ``entries.write`` method. dry_run (bool): Optional. If true, the request should expect normal response, but the entries won't be persisted nor exported. Useful for checking whether the logging API endpoints are working properly before sending valuable data. 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.logging_v2.types.WriteLogEntriesResponse` 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.
[ "Writes", "log", "entries", "to", "Logging", ".", "This", "API", "method", "is", "the", "only", "way", "to", "send", "log", "entries", "to", "Logging", ".", "This", "method", "is", "used", "directly", "or", "indirectly", "by", "the", "Logging", "agent", "(", "fluentd", ")", "and", "all", "logging", "libraries", "configured", "to", "use", "Logging", ".", "A", "single", "request", "may", "contain", "log", "entries", "for", "a", "maximum", "of", "1000", "different", "resources", "(", "projects", "organizations", "billing", "accounts", "or", "folders", ")" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py#L268-L414
train
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py
LoggingServiceV2Client.list_log_entries
def list_log_entries( self, resource_names, project_ids=None, filter_=None, order_by=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists log entries. Use this method to retrieve log entries from Logging. For ways to export log entries, see `Exporting Logs <https://cloud.google.com/logging/docs/export>`__. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> # TODO: Initialize `resource_names`: >>> resource_names = [] >>> >>> # Iterate over all results >>> for element in client.list_log_entries(resource_names): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_log_entries(resource_names).pages: ... for element in page: ... # process element ... pass Args: resource_names (list[str]): Required. Names of one or more parent resources from which to retrieve log entries: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Projects listed in the ``project_ids`` field are added to this list. project_ids (list[str]): Deprecated. Use ``resource_names`` instead. One or more project identifiers or project numbers from which to retrieve log entries. Example: ``"my-project-1A"``. If present, these project identifiers are converted to resource name format and added to the list of resources in ``resource_names``. filter_ (str): Optional. A filter that chooses which log entries to return. See `Advanced Logs Filters <https://cloud.google.com/logging/docs/view/advanced_filters>`__. Only log entries that match the filter are returned. An empty filter matches all log entries in the resources listed in ``resource_names``. Referencing a parent resource that is not listed in ``resource_names`` will cause the filter to return no results. The maximum length of the filter is 20000 characters. order_by (str): Optional. How the results should be sorted. Presently, the only permitted values are ``"timestamp asc"`` (default) and ``"timestamp desc"``. The first option returns entries in order of increasing values of ``LogEntry.timestamp`` (oldest first), and the second option returns entries in order of decreasing timestamps (newest first). Entries with equal timestamps are returned in order of their ``insert_id`` values. 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.logging_v2.types.LogEntry` 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_log_entries" not in self._inner_api_calls: self._inner_api_calls[ "list_log_entries" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_log_entries, default_retry=self._method_configs["ListLogEntries"].retry, default_timeout=self._method_configs["ListLogEntries"].timeout, client_info=self._client_info, ) request = logging_pb2.ListLogEntriesRequest( resource_names=resource_names, project_ids=project_ids, filter=filter_, order_by=order_by, page_size=page_size, ) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_log_entries"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="entries", request_token_field="page_token", response_token_field="next_page_token", ) return iterator
python
def list_log_entries( self, resource_names, project_ids=None, filter_=None, order_by=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists log entries. Use this method to retrieve log entries from Logging. For ways to export log entries, see `Exporting Logs <https://cloud.google.com/logging/docs/export>`__. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> # TODO: Initialize `resource_names`: >>> resource_names = [] >>> >>> # Iterate over all results >>> for element in client.list_log_entries(resource_names): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_log_entries(resource_names).pages: ... for element in page: ... # process element ... pass Args: resource_names (list[str]): Required. Names of one or more parent resources from which to retrieve log entries: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Projects listed in the ``project_ids`` field are added to this list. project_ids (list[str]): Deprecated. Use ``resource_names`` instead. One or more project identifiers or project numbers from which to retrieve log entries. Example: ``"my-project-1A"``. If present, these project identifiers are converted to resource name format and added to the list of resources in ``resource_names``. filter_ (str): Optional. A filter that chooses which log entries to return. See `Advanced Logs Filters <https://cloud.google.com/logging/docs/view/advanced_filters>`__. Only log entries that match the filter are returned. An empty filter matches all log entries in the resources listed in ``resource_names``. Referencing a parent resource that is not listed in ``resource_names`` will cause the filter to return no results. The maximum length of the filter is 20000 characters. order_by (str): Optional. How the results should be sorted. Presently, the only permitted values are ``"timestamp asc"`` (default) and ``"timestamp desc"``. The first option returns entries in order of increasing values of ``LogEntry.timestamp`` (oldest first), and the second option returns entries in order of decreasing timestamps (newest first). Entries with equal timestamps are returned in order of their ``insert_id`` values. 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.logging_v2.types.LogEntry` 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_log_entries" not in self._inner_api_calls: self._inner_api_calls[ "list_log_entries" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_log_entries, default_retry=self._method_configs["ListLogEntries"].retry, default_timeout=self._method_configs["ListLogEntries"].timeout, client_info=self._client_info, ) request = logging_pb2.ListLogEntriesRequest( resource_names=resource_names, project_ids=project_ids, filter=filter_, order_by=order_by, page_size=page_size, ) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_log_entries"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="entries", request_token_field="page_token", response_token_field="next_page_token", ) return iterator
[ "def", "list_log_entries", "(", "self", ",", "resource_names", ",", "project_ids", "=", "None", ",", "filter_", "=", "None", ",", "order_by", "=", "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_log_entries\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"list_log_entries\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "list_log_entries", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"ListLogEntries\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"ListLogEntries\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "logging_pb2", ".", "ListLogEntriesRequest", "(", "resource_names", "=", "resource_names", ",", "project_ids", "=", "project_ids", ",", "filter", "=", "filter_", ",", "order_by", "=", "order_by", ",", "page_size", "=", "page_size", ",", ")", "iterator", "=", "google", ".", "api_core", ".", "page_iterator", ".", "GRPCIterator", "(", "client", "=", "None", ",", "method", "=", "functools", ".", "partial", "(", "self", ".", "_inner_api_calls", "[", "\"list_log_entries\"", "]", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ",", ")", ",", "request", "=", "request", ",", "items_field", "=", "\"entries\"", ",", "request_token_field", "=", "\"page_token\"", ",", "response_token_field", "=", "\"next_page_token\"", ",", ")", "return", "iterator" ]
Lists log entries. Use this method to retrieve log entries from Logging. For ways to export log entries, see `Exporting Logs <https://cloud.google.com/logging/docs/export>`__. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> # TODO: Initialize `resource_names`: >>> resource_names = [] >>> >>> # Iterate over all results >>> for element in client.list_log_entries(resource_names): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_log_entries(resource_names).pages: ... for element in page: ... # process element ... pass Args: resource_names (list[str]): Required. Names of one or more parent resources from which to retrieve log entries: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Projects listed in the ``project_ids`` field are added to this list. project_ids (list[str]): Deprecated. Use ``resource_names`` instead. One or more project identifiers or project numbers from which to retrieve log entries. Example: ``"my-project-1A"``. If present, these project identifiers are converted to resource name format and added to the list of resources in ``resource_names``. filter_ (str): Optional. A filter that chooses which log entries to return. See `Advanced Logs Filters <https://cloud.google.com/logging/docs/view/advanced_filters>`__. Only log entries that match the filter are returned. An empty filter matches all log entries in the resources listed in ``resource_names``. Referencing a parent resource that is not listed in ``resource_names`` will cause the filter to return no results. The maximum length of the filter is 20000 characters. order_by (str): Optional. How the results should be sorted. Presently, the only permitted values are ``"timestamp asc"`` (default) and ``"timestamp desc"``. The first option returns entries in order of increasing values of ``LogEntry.timestamp`` (oldest first), and the second option returns entries in order of decreasing timestamps (newest first). Entries with equal timestamps are returned in order of their ``insert_id`` values. 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.logging_v2.types.LogEntry` 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", "log", "entries", ".", "Use", "this", "method", "to", "retrieve", "log", "entries", "from", "Logging", ".", "For", "ways", "to", "export", "log", "entries", "see", "Exporting", "Logs", "<https", ":", "//", "cloud", ".", "google", ".", "com", "/", "logging", "/", "docs", "/", "export", ">", "__", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py#L416-L544
train
googleapis/google-cloud-python
api_core/google/api_core/path_template.py
_expand_variable_match
def _expand_variable_match(positional_vars, named_vars, match): """Expand a matched variable with its value. Args: positional_vars (list): A list of positonal variables. This list will be modified. named_vars (dict): A dictionary of named variables. match (re.Match): A regular expression match. Returns: str: The expanded variable to replace the match. Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered. """ positional = match.group("positional") name = match.group("name") if name is not None: try: return six.text_type(named_vars[name]) except KeyError: raise ValueError( "Named variable '{}' not specified and needed by template " "`{}` at position {}".format(name, match.string, match.start()) ) elif positional is not None: try: return six.text_type(positional_vars.pop(0)) except IndexError: raise ValueError( "Positional variable not specified and needed by template " "`{}` at position {}".format(match.string, match.start()) ) else: raise ValueError("Unknown template expression {}".format(match.group(0)))
python
def _expand_variable_match(positional_vars, named_vars, match): """Expand a matched variable with its value. Args: positional_vars (list): A list of positonal variables. This list will be modified. named_vars (dict): A dictionary of named variables. match (re.Match): A regular expression match. Returns: str: The expanded variable to replace the match. Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered. """ positional = match.group("positional") name = match.group("name") if name is not None: try: return six.text_type(named_vars[name]) except KeyError: raise ValueError( "Named variable '{}' not specified and needed by template " "`{}` at position {}".format(name, match.string, match.start()) ) elif positional is not None: try: return six.text_type(positional_vars.pop(0)) except IndexError: raise ValueError( "Positional variable not specified and needed by template " "`{}` at position {}".format(match.string, match.start()) ) else: raise ValueError("Unknown template expression {}".format(match.group(0)))
[ "def", "_expand_variable_match", "(", "positional_vars", ",", "named_vars", ",", "match", ")", ":", "positional", "=", "match", ".", "group", "(", "\"positional\"", ")", "name", "=", "match", ".", "group", "(", "\"name\"", ")", "if", "name", "is", "not", "None", ":", "try", ":", "return", "six", ".", "text_type", "(", "named_vars", "[", "name", "]", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "\"Named variable '{}' not specified and needed by template \"", "\"`{}` at position {}\"", ".", "format", "(", "name", ",", "match", ".", "string", ",", "match", ".", "start", "(", ")", ")", ")", "elif", "positional", "is", "not", "None", ":", "try", ":", "return", "six", ".", "text_type", "(", "positional_vars", ".", "pop", "(", "0", ")", ")", "except", "IndexError", ":", "raise", "ValueError", "(", "\"Positional variable not specified and needed by template \"", "\"`{}` at position {}\"", ".", "format", "(", "match", ".", "string", ",", "match", ".", "start", "(", ")", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown template expression {}\"", ".", "format", "(", "match", ".", "group", "(", "0", ")", ")", ")" ]
Expand a matched variable with its value. Args: positional_vars (list): A list of positonal variables. This list will be modified. named_vars (dict): A dictionary of named variables. match (re.Match): A regular expression match. Returns: str: The expanded variable to replace the match. Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered.
[ "Expand", "a", "matched", "variable", "with", "its", "value", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/path_template.py#L65-L101
train
googleapis/google-cloud-python
api_core/google/api_core/path_template.py
expand
def expand(tmpl, *args, **kwargs): """Expand a path template with the given variables. ..code-block:: python >>> expand('users/*/messages/*', 'me', '123') users/me/messages/123 >>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3') /v1/shelves/1/books/3 Args: tmpl (str): The path template. args: The positional variables for the path. kwargs: The named variables for the path. Returns: str: The expanded path Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered. """ replacer = functools.partial(_expand_variable_match, list(args), kwargs) return _VARIABLE_RE.sub(replacer, tmpl)
python
def expand(tmpl, *args, **kwargs): """Expand a path template with the given variables. ..code-block:: python >>> expand('users/*/messages/*', 'me', '123') users/me/messages/123 >>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3') /v1/shelves/1/books/3 Args: tmpl (str): The path template. args: The positional variables for the path. kwargs: The named variables for the path. Returns: str: The expanded path Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered. """ replacer = functools.partial(_expand_variable_match, list(args), kwargs) return _VARIABLE_RE.sub(replacer, tmpl)
[ "def", "expand", "(", "tmpl", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "replacer", "=", "functools", ".", "partial", "(", "_expand_variable_match", ",", "list", "(", "args", ")", ",", "kwargs", ")", "return", "_VARIABLE_RE", ".", "sub", "(", "replacer", ",", "tmpl", ")" ]
Expand a path template with the given variables. ..code-block:: python >>> expand('users/*/messages/*', 'me', '123') users/me/messages/123 >>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3') /v1/shelves/1/books/3 Args: tmpl (str): The path template. args: The positional variables for the path. kwargs: The named variables for the path. Returns: str: The expanded path Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered.
[ "Expand", "a", "path", "template", "with", "the", "given", "variables", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/path_template.py#L104-L128
train
googleapis/google-cloud-python
api_core/google/api_core/path_template.py
_replace_variable_with_pattern
def _replace_variable_with_pattern(match): """Replace a variable match with a pattern that can be used to validate it. Args: match (re.Match): A regular expression match Returns: str: A regular expression pattern that can be used to validate the variable in an expanded path. Raises: ValueError: If an unexpected template expression is encountered. """ positional = match.group("positional") name = match.group("name") template = match.group("template") if name is not None: if not template: return _SINGLE_SEGMENT_PATTERN.format(name) elif template == "**": return _MULTI_SEGMENT_PATTERN.format(name) else: return _generate_pattern_for_template(template) elif positional == "*": return _SINGLE_SEGMENT_PATTERN elif positional == "**": return _MULTI_SEGMENT_PATTERN else: raise ValueError("Unknown template expression {}".format(match.group(0)))
python
def _replace_variable_with_pattern(match): """Replace a variable match with a pattern that can be used to validate it. Args: match (re.Match): A regular expression match Returns: str: A regular expression pattern that can be used to validate the variable in an expanded path. Raises: ValueError: If an unexpected template expression is encountered. """ positional = match.group("positional") name = match.group("name") template = match.group("template") if name is not None: if not template: return _SINGLE_SEGMENT_PATTERN.format(name) elif template == "**": return _MULTI_SEGMENT_PATTERN.format(name) else: return _generate_pattern_for_template(template) elif positional == "*": return _SINGLE_SEGMENT_PATTERN elif positional == "**": return _MULTI_SEGMENT_PATTERN else: raise ValueError("Unknown template expression {}".format(match.group(0)))
[ "def", "_replace_variable_with_pattern", "(", "match", ")", ":", "positional", "=", "match", ".", "group", "(", "\"positional\"", ")", "name", "=", "match", ".", "group", "(", "\"name\"", ")", "template", "=", "match", ".", "group", "(", "\"template\"", ")", "if", "name", "is", "not", "None", ":", "if", "not", "template", ":", "return", "_SINGLE_SEGMENT_PATTERN", ".", "format", "(", "name", ")", "elif", "template", "==", "\"**\"", ":", "return", "_MULTI_SEGMENT_PATTERN", ".", "format", "(", "name", ")", "else", ":", "return", "_generate_pattern_for_template", "(", "template", ")", "elif", "positional", "==", "\"*\"", ":", "return", "_SINGLE_SEGMENT_PATTERN", "elif", "positional", "==", "\"**\"", ":", "return", "_MULTI_SEGMENT_PATTERN", "else", ":", "raise", "ValueError", "(", "\"Unknown template expression {}\"", ".", "format", "(", "match", ".", "group", "(", "0", ")", ")", ")" ]
Replace a variable match with a pattern that can be used to validate it. Args: match (re.Match): A regular expression match Returns: str: A regular expression pattern that can be used to validate the variable in an expanded path. Raises: ValueError: If an unexpected template expression is encountered.
[ "Replace", "a", "variable", "match", "with", "a", "pattern", "that", "can", "be", "used", "to", "validate", "it", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/path_template.py#L131-L159
train
googleapis/google-cloud-python
api_core/google/api_core/path_template.py
validate
def validate(tmpl, path): """Validate a path against the path template. .. code-block:: python >>> validate('users/*/messages/*', 'users/me/messages/123') True >>> validate('users/*/messages/*', 'users/me/drafts/123') False >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/books/3) True >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/tapes/3) False Args: tmpl (str): The path template. path (str): The expanded path. Returns: bool: True if the path matches. """ pattern = _generate_pattern_for_template(tmpl) + "$" return True if re.match(pattern, path) is not None else False
python
def validate(tmpl, path): """Validate a path against the path template. .. code-block:: python >>> validate('users/*/messages/*', 'users/me/messages/123') True >>> validate('users/*/messages/*', 'users/me/drafts/123') False >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/books/3) True >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/tapes/3) False Args: tmpl (str): The path template. path (str): The expanded path. Returns: bool: True if the path matches. """ pattern = _generate_pattern_for_template(tmpl) + "$" return True if re.match(pattern, path) is not None else False
[ "def", "validate", "(", "tmpl", ",", "path", ")", ":", "pattern", "=", "_generate_pattern_for_template", "(", "tmpl", ")", "+", "\"$\"", "return", "True", "if", "re", ".", "match", "(", "pattern", ",", "path", ")", "is", "not", "None", "else", "False" ]
Validate a path against the path template. .. code-block:: python >>> validate('users/*/messages/*', 'users/me/messages/123') True >>> validate('users/*/messages/*', 'users/me/drafts/123') False >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/books/3) True >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/tapes/3) False Args: tmpl (str): The path template. path (str): The expanded path. Returns: bool: True if the path matches.
[ "Validate", "a", "path", "against", "the", "path", "template", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/path_template.py#L175-L197
train
googleapis/google-cloud-python
storage/noxfile.py
default
def default(session): """Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of Python corresponding to the ``nox`` binary the ``PATH`` can run the tests. """ # Install all test dependencies, then install local packages in-place. session.install('mock', 'pytest', 'pytest-cov') for local_dep in LOCAL_DEPS: session.install('-e', local_dep) session.install('-e', '.') # Run py.test against the unit tests. session.run( 'py.test', '--quiet', '--cov=google.cloud.storage', '--cov=tests.unit', '--cov-append', '--cov-config=.coveragerc', '--cov-report=', '--cov-fail-under=97', 'tests/unit', *session.posargs )
python
def default(session): """Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of Python corresponding to the ``nox`` binary the ``PATH`` can run the tests. """ # Install all test dependencies, then install local packages in-place. session.install('mock', 'pytest', 'pytest-cov') for local_dep in LOCAL_DEPS: session.install('-e', local_dep) session.install('-e', '.') # Run py.test against the unit tests. session.run( 'py.test', '--quiet', '--cov=google.cloud.storage', '--cov=tests.unit', '--cov-append', '--cov-config=.coveragerc', '--cov-report=', '--cov-fail-under=97', 'tests/unit', *session.posargs )
[ "def", "default", "(", "session", ")", ":", "# Install all test dependencies, then install local packages in-place.", "session", ".", "install", "(", "'mock'", ",", "'pytest'", ",", "'pytest-cov'", ")", "for", "local_dep", "in", "LOCAL_DEPS", ":", "session", ".", "install", "(", "'-e'", ",", "local_dep", ")", "session", ".", "install", "(", "'-e'", ",", "'.'", ")", "# Run py.test against the unit tests.", "session", ".", "run", "(", "'py.test'", ",", "'--quiet'", ",", "'--cov=google.cloud.storage'", ",", "'--cov=tests.unit'", ",", "'--cov-append'", ",", "'--cov-config=.coveragerc'", ",", "'--cov-report='", ",", "'--cov-fail-under=97'", ",", "'tests/unit'", ",", "*", "session", ".", "posargs", ")" ]
Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of Python corresponding to the ``nox`` binary the ``PATH`` can run the tests.
[ "Default", "unit", "test", "session", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/noxfile.py#L29-L55
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/transports/firestore_grpc_transport.py
FirestoreGrpcTransport.create_channel
def create_channel(cls, address="firestore.googleapis.com:443", credentials=None): """Create and return a gRPC channel object. Args: address (str): The host for the channel to use. credentials (~.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. Returns: grpc.Channel: A gRPC channel object. """ return google.api_core.grpc_helpers.create_channel( address, credentials=credentials, scopes=cls._OAUTH_SCOPES )
python
def create_channel(cls, address="firestore.googleapis.com:443", credentials=None): """Create and return a gRPC channel object. Args: address (str): The host for the channel to use. credentials (~.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. Returns: grpc.Channel: A gRPC channel object. """ return google.api_core.grpc_helpers.create_channel( address, credentials=credentials, scopes=cls._OAUTH_SCOPES )
[ "def", "create_channel", "(", "cls", ",", "address", "=", "\"firestore.googleapis.com:443\"", ",", "credentials", "=", "None", ")", ":", "return", "google", ".", "api_core", ".", "grpc_helpers", ".", "create_channel", "(", "address", ",", "credentials", "=", "credentials", ",", "scopes", "=", "cls", ".", "_OAUTH_SCOPES", ")" ]
Create and return a gRPC channel object. Args: address (str): The host for the channel to use. credentials (~.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. Returns: grpc.Channel: A gRPC channel object.
[ "Create", "and", "return", "a", "gRPC", "channel", "object", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/transports/firestore_grpc_transport.py#L72-L88
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.name
def name(self): """AppProfile name used in requests. .. note:: This property will not change if ``app_profile_id`` does not, but the return value is not cached. The AppProfile name is of the form ``"projects/../instances/../app_profile/{app_profile_id}"`` :rtype: str :returns: The AppProfile name. """ return self.instance_admin_client.app_profile_path( self._instance._client.project, self._instance.instance_id, self.app_profile_id, )
python
def name(self): """AppProfile name used in requests. .. note:: This property will not change if ``app_profile_id`` does not, but the return value is not cached. The AppProfile name is of the form ``"projects/../instances/../app_profile/{app_profile_id}"`` :rtype: str :returns: The AppProfile name. """ return self.instance_admin_client.app_profile_path( self._instance._client.project, self._instance.instance_id, self.app_profile_id, )
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "instance_admin_client", ".", "app_profile_path", "(", "self", ".", "_instance", ".", "_client", ".", "project", ",", "self", ".", "_instance", ".", "instance_id", ",", "self", ".", "app_profile_id", ",", ")" ]
AppProfile name used in requests. .. note:: This property will not change if ``app_profile_id`` does not, but the return value is not cached. The AppProfile name is of the form ``"projects/../instances/../app_profile/{app_profile_id}"`` :rtype: str :returns: The AppProfile name.
[ "AppProfile", "name", "used", "in", "requests", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L85-L103
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.from_pb
def from_pb(cls, app_profile_pb, instance): """Creates an instance app_profile from a protobuf. :type app_profile_pb: :class:`instance_pb2.app_profile_pb` :param app_profile_pb: An instance protobuf object. :type instance: :class:`google.cloud.bigtable.instance.Instance` :param instance: The instance that owns the cluster. :rtype: :class:`AppProfile` :returns: The AppProfile parsed from the protobuf response. :raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile name does not match ``projects/{project}/instances/{instance_id}/appProfiles/{app_profile_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_app_profile_name = _APP_PROFILE_NAME_RE.match(app_profile_pb.name) if match_app_profile_name is None: raise ValueError( "AppProfile protobuf name was not in the " "expected format.", app_profile_pb.name, ) if match_app_profile_name.group("instance") != instance.instance_id: raise ValueError( "Instance ID on app_profile does not match the " "instance ID on the client" ) if match_app_profile_name.group("project") != instance._client.project: raise ValueError( "Project ID on app_profile does not match the " "project ID on the client" ) app_profile_id = match_app_profile_name.group("app_profile_id") result = cls(app_profile_id, instance) result._update_from_pb(app_profile_pb) return result
python
def from_pb(cls, app_profile_pb, instance): """Creates an instance app_profile from a protobuf. :type app_profile_pb: :class:`instance_pb2.app_profile_pb` :param app_profile_pb: An instance protobuf object. :type instance: :class:`google.cloud.bigtable.instance.Instance` :param instance: The instance that owns the cluster. :rtype: :class:`AppProfile` :returns: The AppProfile parsed from the protobuf response. :raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile name does not match ``projects/{project}/instances/{instance_id}/appProfiles/{app_profile_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_app_profile_name = _APP_PROFILE_NAME_RE.match(app_profile_pb.name) if match_app_profile_name is None: raise ValueError( "AppProfile protobuf name was not in the " "expected format.", app_profile_pb.name, ) if match_app_profile_name.group("instance") != instance.instance_id: raise ValueError( "Instance ID on app_profile does not match the " "instance ID on the client" ) if match_app_profile_name.group("project") != instance._client.project: raise ValueError( "Project ID on app_profile does not match the " "project ID on the client" ) app_profile_id = match_app_profile_name.group("app_profile_id") result = cls(app_profile_id, instance) result._update_from_pb(app_profile_pb) return result
[ "def", "from_pb", "(", "cls", ",", "app_profile_pb", ",", "instance", ")", ":", "match_app_profile_name", "=", "_APP_PROFILE_NAME_RE", ".", "match", "(", "app_profile_pb", ".", "name", ")", "if", "match_app_profile_name", "is", "None", ":", "raise", "ValueError", "(", "\"AppProfile protobuf name was not in the \"", "\"expected format.\"", ",", "app_profile_pb", ".", "name", ",", ")", "if", "match_app_profile_name", ".", "group", "(", "\"instance\"", ")", "!=", "instance", ".", "instance_id", ":", "raise", "ValueError", "(", "\"Instance ID on app_profile does not match the \"", "\"instance ID on the client\"", ")", "if", "match_app_profile_name", ".", "group", "(", "\"project\"", ")", "!=", "instance", ".", "_client", ".", "project", ":", "raise", "ValueError", "(", "\"Project ID on app_profile does not match the \"", "\"project ID on the client\"", ")", "app_profile_id", "=", "match_app_profile_name", ".", "group", "(", "\"app_profile_id\"", ")", "result", "=", "cls", "(", "app_profile_id", ",", "instance", ")", "result", ".", "_update_from_pb", "(", "app_profile_pb", ")", "return", "result" ]
Creates an instance app_profile from a protobuf. :type app_profile_pb: :class:`instance_pb2.app_profile_pb` :param app_profile_pb: An instance protobuf object. :type instance: :class:`google.cloud.bigtable.instance.Instance` :param instance: The instance that owns the cluster. :rtype: :class:`AppProfile` :returns: The AppProfile parsed from the protobuf response. :raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile name does not match ``projects/{project}/instances/{instance_id}/appProfiles/{app_profile_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", "instance", "app_profile", "from", "a", "protobuf", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L131-L171
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile._update_from_pb
def _update_from_pb(self, app_profile_pb): """Refresh self from the server-provided protobuf. Helper for :meth:`from_pb` and :meth:`reload`. """ self.routing_policy_type = None self.allow_transactional_writes = None self.cluster_id = None self.description = app_profile_pb.description routing_policy_type = None if app_profile_pb.HasField("multi_cluster_routing_use_any"): routing_policy_type = RoutingPolicyType.ANY self.allow_transactional_writes = False else: routing_policy_type = RoutingPolicyType.SINGLE self.cluster_id = app_profile_pb.single_cluster_routing.cluster_id self.allow_transactional_writes = ( app_profile_pb.single_cluster_routing.allow_transactional_writes ) self.routing_policy_type = routing_policy_type
python
def _update_from_pb(self, app_profile_pb): """Refresh self from the server-provided protobuf. Helper for :meth:`from_pb` and :meth:`reload`. """ self.routing_policy_type = None self.allow_transactional_writes = None self.cluster_id = None self.description = app_profile_pb.description routing_policy_type = None if app_profile_pb.HasField("multi_cluster_routing_use_any"): routing_policy_type = RoutingPolicyType.ANY self.allow_transactional_writes = False else: routing_policy_type = RoutingPolicyType.SINGLE self.cluster_id = app_profile_pb.single_cluster_routing.cluster_id self.allow_transactional_writes = ( app_profile_pb.single_cluster_routing.allow_transactional_writes ) self.routing_policy_type = routing_policy_type
[ "def", "_update_from_pb", "(", "self", ",", "app_profile_pb", ")", ":", "self", ".", "routing_policy_type", "=", "None", "self", ".", "allow_transactional_writes", "=", "None", "self", ".", "cluster_id", "=", "None", "self", ".", "description", "=", "app_profile_pb", ".", "description", "routing_policy_type", "=", "None", "if", "app_profile_pb", ".", "HasField", "(", "\"multi_cluster_routing_use_any\"", ")", ":", "routing_policy_type", "=", "RoutingPolicyType", ".", "ANY", "self", ".", "allow_transactional_writes", "=", "False", "else", ":", "routing_policy_type", "=", "RoutingPolicyType", ".", "SINGLE", "self", ".", "cluster_id", "=", "app_profile_pb", ".", "single_cluster_routing", ".", "cluster_id", "self", ".", "allow_transactional_writes", "=", "(", "app_profile_pb", ".", "single_cluster_routing", ".", "allow_transactional_writes", ")", "self", ".", "routing_policy_type", "=", "routing_policy_type" ]
Refresh self from the server-provided protobuf. Helper for :meth:`from_pb` and :meth:`reload`.
[ "Refresh", "self", "from", "the", "server", "-", "provided", "protobuf", ".", "Helper", "for", ":", "meth", ":", "from_pb", "and", ":", "meth", ":", "reload", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L173-L193
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile._to_pb
def _to_pb(self): """Create an AppProfile proto buff message for API calls :rtype: :class:`.instance_pb2.AppProfile` :returns: The converted current object. :raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile routing_policy_type is not set """ if not self.routing_policy_type: raise ValueError("AppProfile required routing policy.") single_cluster_routing = None multi_cluster_routing_use_any = None if self.routing_policy_type == RoutingPolicyType.ANY: multi_cluster_routing_use_any = ( instance_pb2.AppProfile.MultiClusterRoutingUseAny() ) else: single_cluster_routing = instance_pb2.AppProfile.SingleClusterRouting( cluster_id=self.cluster_id, allow_transactional_writes=self.allow_transactional_writes, ) app_profile_pb = instance_pb2.AppProfile( name=self.name, description=self.description, multi_cluster_routing_use_any=multi_cluster_routing_use_any, single_cluster_routing=single_cluster_routing, ) return app_profile_pb
python
def _to_pb(self): """Create an AppProfile proto buff message for API calls :rtype: :class:`.instance_pb2.AppProfile` :returns: The converted current object. :raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile routing_policy_type is not set """ if not self.routing_policy_type: raise ValueError("AppProfile required routing policy.") single_cluster_routing = None multi_cluster_routing_use_any = None if self.routing_policy_type == RoutingPolicyType.ANY: multi_cluster_routing_use_any = ( instance_pb2.AppProfile.MultiClusterRoutingUseAny() ) else: single_cluster_routing = instance_pb2.AppProfile.SingleClusterRouting( cluster_id=self.cluster_id, allow_transactional_writes=self.allow_transactional_writes, ) app_profile_pb = instance_pb2.AppProfile( name=self.name, description=self.description, multi_cluster_routing_use_any=multi_cluster_routing_use_any, single_cluster_routing=single_cluster_routing, ) return app_profile_pb
[ "def", "_to_pb", "(", "self", ")", ":", "if", "not", "self", ".", "routing_policy_type", ":", "raise", "ValueError", "(", "\"AppProfile required routing policy.\"", ")", "single_cluster_routing", "=", "None", "multi_cluster_routing_use_any", "=", "None", "if", "self", ".", "routing_policy_type", "==", "RoutingPolicyType", ".", "ANY", ":", "multi_cluster_routing_use_any", "=", "(", "instance_pb2", ".", "AppProfile", ".", "MultiClusterRoutingUseAny", "(", ")", ")", "else", ":", "single_cluster_routing", "=", "instance_pb2", ".", "AppProfile", ".", "SingleClusterRouting", "(", "cluster_id", "=", "self", ".", "cluster_id", ",", "allow_transactional_writes", "=", "self", ".", "allow_transactional_writes", ",", ")", "app_profile_pb", "=", "instance_pb2", ".", "AppProfile", "(", "name", "=", "self", ".", "name", ",", "description", "=", "self", ".", "description", ",", "multi_cluster_routing_use_any", "=", "multi_cluster_routing_use_any", ",", "single_cluster_routing", "=", "single_cluster_routing", ",", ")", "return", "app_profile_pb" ]
Create an AppProfile proto buff message for API calls :rtype: :class:`.instance_pb2.AppProfile` :returns: The converted current object. :raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile routing_policy_type is not set
[ "Create", "an", "AppProfile", "proto", "buff", "message", "for", "API", "calls", ":", "rtype", ":", ":", "class", ":", ".", "instance_pb2", ".", "AppProfile", ":", "returns", ":", "The", "converted", "current", "object", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L195-L225
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.reload
def reload(self): """Reload the metadata for this cluster""" app_profile_pb = self.instance_admin_client.get_app_profile(self.name) # NOTE: _update_from_pb does not check that the project and # app_profile ID on the response match the request. self._update_from_pb(app_profile_pb)
python
def reload(self): """Reload the metadata for this cluster""" app_profile_pb = self.instance_admin_client.get_app_profile(self.name) # NOTE: _update_from_pb does not check that the project and # app_profile ID on the response match the request. self._update_from_pb(app_profile_pb)
[ "def", "reload", "(", "self", ")", ":", "app_profile_pb", "=", "self", ".", "instance_admin_client", ".", "get_app_profile", "(", "self", ".", "name", ")", "# NOTE: _update_from_pb does not check that the project and", "# app_profile ID on the response match the request.", "self", ".", "_update_from_pb", "(", "app_profile_pb", ")" ]
Reload the metadata for this cluster
[ "Reload", "the", "metadata", "for", "this", "cluster" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L227-L234
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.exists
def exists(self): """Check whether the AppProfile already exists. :rtype: bool :returns: True if the AppProfile exists, else False. """ try: self.instance_admin_client.get_app_profile(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 AppProfile already exists. :rtype: bool :returns: True if the AppProfile exists, else False. """ try: self.instance_admin_client.get_app_profile(self.name) return True # NOTE: There could be other exceptions that are returned to the user. except NotFound: return False
[ "def", "exists", "(", "self", ")", ":", "try", ":", "self", ".", "instance_admin_client", ".", "get_app_profile", "(", "self", ".", "name", ")", "return", "True", "# NOTE: There could be other exceptions that are returned to the user.", "except", "NotFound", ":", "return", "False" ]
Check whether the AppProfile already exists. :rtype: bool :returns: True if the AppProfile exists, else False.
[ "Check", "whether", "the", "AppProfile", "already", "exists", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L236-L247
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.create
def create(self, ignore_warnings=None): """Create this AppProfile. .. note:: Uses the ``instance`` and ``app_profile_id`` on the current :class:`AppProfile` in addition to the ``routing_policy_type``, ``description``, ``cluster_id`` and ``allow_transactional_writes``. To change them before creating, reset the values via .. code:: python app_profile.app_profile_id = 'i-changed-my-mind' app_profile.routing_policy_type = ( google.cloud.bigtable.enums.RoutingPolicyType.SINGLE ) app_profile.description = 'new-description' app-profile.cluster_id = 'other-cluster-id' app-profile.allow_transactional_writes = True before calling :meth:`create`. :type: ignore_warnings: bool :param: ignore_warnings: (Optional) If true, ignore safety checks when creating the AppProfile. """ return self.from_pb( self.instance_admin_client.create_app_profile( parent=self._instance.name, app_profile_id=self.app_profile_id, app_profile=self._to_pb(), ignore_warnings=ignore_warnings, ), self._instance, )
python
def create(self, ignore_warnings=None): """Create this AppProfile. .. note:: Uses the ``instance`` and ``app_profile_id`` on the current :class:`AppProfile` in addition to the ``routing_policy_type``, ``description``, ``cluster_id`` and ``allow_transactional_writes``. To change them before creating, reset the values via .. code:: python app_profile.app_profile_id = 'i-changed-my-mind' app_profile.routing_policy_type = ( google.cloud.bigtable.enums.RoutingPolicyType.SINGLE ) app_profile.description = 'new-description' app-profile.cluster_id = 'other-cluster-id' app-profile.allow_transactional_writes = True before calling :meth:`create`. :type: ignore_warnings: bool :param: ignore_warnings: (Optional) If true, ignore safety checks when creating the AppProfile. """ return self.from_pb( self.instance_admin_client.create_app_profile( parent=self._instance.name, app_profile_id=self.app_profile_id, app_profile=self._to_pb(), ignore_warnings=ignore_warnings, ), self._instance, )
[ "def", "create", "(", "self", ",", "ignore_warnings", "=", "None", ")", ":", "return", "self", ".", "from_pb", "(", "self", ".", "instance_admin_client", ".", "create_app_profile", "(", "parent", "=", "self", ".", "_instance", ".", "name", ",", "app_profile_id", "=", "self", ".", "app_profile_id", ",", "app_profile", "=", "self", ".", "_to_pb", "(", ")", ",", "ignore_warnings", "=", "ignore_warnings", ",", ")", ",", "self", ".", "_instance", ",", ")" ]
Create this AppProfile. .. note:: Uses the ``instance`` and ``app_profile_id`` on the current :class:`AppProfile` in addition to the ``routing_policy_type``, ``description``, ``cluster_id`` and ``allow_transactional_writes``. To change them before creating, reset the values via .. code:: python app_profile.app_profile_id = 'i-changed-my-mind' app_profile.routing_policy_type = ( google.cloud.bigtable.enums.RoutingPolicyType.SINGLE ) app_profile.description = 'new-description' app-profile.cluster_id = 'other-cluster-id' app-profile.allow_transactional_writes = True before calling :meth:`create`. :type: ignore_warnings: bool :param: ignore_warnings: (Optional) If true, ignore safety checks when creating the AppProfile.
[ "Create", "this", "AppProfile", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L249-L283
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.update
def update(self, ignore_warnings=None): """Update this app_profile. .. note:: Update any or all of the following values: ``routing_policy_type`` ``description`` ``cluster_id`` ``allow_transactional_writes`` """ update_mask_pb = field_mask_pb2.FieldMask() if self.description is not None: update_mask_pb.paths.append("description") if self.routing_policy_type == RoutingPolicyType.ANY: update_mask_pb.paths.append("multi_cluster_routing_use_any") else: update_mask_pb.paths.append("single_cluster_routing") return self.instance_admin_client.update_app_profile( app_profile=self._to_pb(), update_mask=update_mask_pb, ignore_warnings=ignore_warnings, )
python
def update(self, ignore_warnings=None): """Update this app_profile. .. note:: Update any or all of the following values: ``routing_policy_type`` ``description`` ``cluster_id`` ``allow_transactional_writes`` """ update_mask_pb = field_mask_pb2.FieldMask() if self.description is not None: update_mask_pb.paths.append("description") if self.routing_policy_type == RoutingPolicyType.ANY: update_mask_pb.paths.append("multi_cluster_routing_use_any") else: update_mask_pb.paths.append("single_cluster_routing") return self.instance_admin_client.update_app_profile( app_profile=self._to_pb(), update_mask=update_mask_pb, ignore_warnings=ignore_warnings, )
[ "def", "update", "(", "self", ",", "ignore_warnings", "=", "None", ")", ":", "update_mask_pb", "=", "field_mask_pb2", ".", "FieldMask", "(", ")", "if", "self", ".", "description", "is", "not", "None", ":", "update_mask_pb", ".", "paths", ".", "append", "(", "\"description\"", ")", "if", "self", ".", "routing_policy_type", "==", "RoutingPolicyType", ".", "ANY", ":", "update_mask_pb", ".", "paths", ".", "append", "(", "\"multi_cluster_routing_use_any\"", ")", "else", ":", "update_mask_pb", ".", "paths", ".", "append", "(", "\"single_cluster_routing\"", ")", "return", "self", ".", "instance_admin_client", ".", "update_app_profile", "(", "app_profile", "=", "self", ".", "_to_pb", "(", ")", ",", "update_mask", "=", "update_mask_pb", ",", "ignore_warnings", "=", "ignore_warnings", ",", ")" ]
Update this app_profile. .. note:: Update any or all of the following values: ``routing_policy_type`` ``description`` ``cluster_id`` ``allow_transactional_writes``
[ "Update", "this", "app_profile", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L285-L311
train
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/config_service_v2_client.py
ConfigServiceV2Client.sink_path
def sink_path(cls, project, sink): """Return a fully-qualified sink string.""" return google.api_core.path_template.expand( "projects/{project}/sinks/{sink}", project=project, sink=sink )
python
def sink_path(cls, project, sink): """Return a fully-qualified sink string.""" return google.api_core.path_template.expand( "projects/{project}/sinks/{sink}", project=project, sink=sink )
[ "def", "sink_path", "(", "cls", ",", "project", ",", "sink", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/sinks/{sink}\"", ",", "project", "=", "project", ",", "sink", "=", "sink", ")" ]
Return a fully-qualified sink string.
[ "Return", "a", "fully", "-", "qualified", "sink", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/config_service_v2_client.py#L88-L92
train
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/config_service_v2_client.py
ConfigServiceV2Client.exclusion_path
def exclusion_path(cls, project, exclusion): """Return a fully-qualified exclusion string.""" return google.api_core.path_template.expand( "projects/{project}/exclusions/{exclusion}", project=project, exclusion=exclusion, )
python
def exclusion_path(cls, project, exclusion): """Return a fully-qualified exclusion string.""" return google.api_core.path_template.expand( "projects/{project}/exclusions/{exclusion}", project=project, exclusion=exclusion, )
[ "def", "exclusion_path", "(", "cls", ",", "project", ",", "exclusion", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/exclusions/{exclusion}\"", ",", "project", "=", "project", ",", "exclusion", "=", "exclusion", ",", ")" ]
Return a fully-qualified exclusion string.
[ "Return", "a", "fully", "-", "qualified", "exclusion", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/config_service_v2_client.py#L95-L101
train
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/config_service_v2_client.py
ConfigServiceV2Client.create_sink
def create_sink( self, parent, sink, unique_writer_identity=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `sink`: >>> sink = {} >>> >>> response = client.create_sink(parent, sink) Args: parent (str): Required. The resource in which to create the sink: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. sink (Union[dict, ~google.cloud.logging_v2.types.LogSink]): Required. The new sink, whose ``name`` parameter is a sink identifier that is not already in use. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogSink` unique_writer_identity (bool): Optional. Determines the kind of IAM identity returned as ``writer_identity`` in the new sink. If this value is omitted or set to false, and if the sink's parent is a project, then the value returned as ``writer_identity`` is the same group or service account used by Logging before the addition of writer identities to this API. The sink's destination must be in the same project as the sink itself. If this field is set to true, or if the sink is owned by a non-project resource such as an organization, then the value of ``writer_identity`` will be a unique service account used only for exports from the new sink. For more information, see ``writer_identity`` in ``LogSink``. 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.logging_v2.types.LogSink` 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_sink" not in self._inner_api_calls: self._inner_api_calls[ "create_sink" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_sink, default_retry=self._method_configs["CreateSink"].retry, default_timeout=self._method_configs["CreateSink"].timeout, client_info=self._client_info, ) request = logging_config_pb2.CreateSinkRequest( parent=parent, sink=sink, unique_writer_identity=unique_writer_identity ) 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_sink"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_sink( self, parent, sink, unique_writer_identity=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `sink`: >>> sink = {} >>> >>> response = client.create_sink(parent, sink) Args: parent (str): Required. The resource in which to create the sink: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. sink (Union[dict, ~google.cloud.logging_v2.types.LogSink]): Required. The new sink, whose ``name`` parameter is a sink identifier that is not already in use. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogSink` unique_writer_identity (bool): Optional. Determines the kind of IAM identity returned as ``writer_identity`` in the new sink. If this value is omitted or set to false, and if the sink's parent is a project, then the value returned as ``writer_identity`` is the same group or service account used by Logging before the addition of writer identities to this API. The sink's destination must be in the same project as the sink itself. If this field is set to true, or if the sink is owned by a non-project resource such as an organization, then the value of ``writer_identity`` will be a unique service account used only for exports from the new sink. For more information, see ``writer_identity`` in ``LogSink``. 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.logging_v2.types.LogSink` 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_sink" not in self._inner_api_calls: self._inner_api_calls[ "create_sink" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_sink, default_retry=self._method_configs["CreateSink"].retry, default_timeout=self._method_configs["CreateSink"].timeout, client_info=self._client_info, ) request = logging_config_pb2.CreateSinkRequest( parent=parent, sink=sink, unique_writer_identity=unique_writer_identity ) 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_sink"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_sink", "(", "self", ",", "parent", ",", "sink", ",", "unique_writer_identity", "=", "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_sink\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_sink\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_sink", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateSink\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateSink\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "logging_config_pb2", ".", "CreateSinkRequest", "(", "parent", "=", "parent", ",", "sink", "=", "sink", ",", "unique_writer_identity", "=", "unique_writer_identity", ")", "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_sink\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `sink`: >>> sink = {} >>> >>> response = client.create_sink(parent, sink) Args: parent (str): Required. The resource in which to create the sink: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. sink (Union[dict, ~google.cloud.logging_v2.types.LogSink]): Required. The new sink, whose ``name`` parameter is a sink identifier that is not already in use. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogSink` unique_writer_identity (bool): Optional. Determines the kind of IAM identity returned as ``writer_identity`` in the new sink. If this value is omitted or set to false, and if the sink's parent is a project, then the value returned as ``writer_identity`` is the same group or service account used by Logging before the addition of writer identities to this API. The sink's destination must be in the same project as the sink itself. If this field is set to true, or if the sink is owned by a non-project resource such as an organization, then the value of ``writer_identity`` will be a unique service account used only for exports from the new sink. For more information, see ``writer_identity`` in ``LogSink``. 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.logging_v2.types.LogSink` 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", "sink", "that", "exports", "specified", "log", "entries", "to", "a", "destination", ".", "The", "export", "of", "newly", "-", "ingested", "log", "entries", "begins", "immediately", "unless", "the", "sink", "s", "writer_identity", "is", "not", "permitted", "to", "write", "to", "the", "destination", ".", "A", "sink", "can", "export", "log", "entries", "only", "from", "the", "resource", "owning", "the", "sink", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/config_service_v2_client.py#L390-L493
train
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/config_service_v2_client.py
ConfigServiceV2Client.update_sink
def update_sink( self, sink_name, sink, unique_writer_identity=None, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. The updated sink might also have a new ``writer_identity``; see the ``unique_writer_identity`` field. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> sink_name = client.sink_path('[PROJECT]', '[SINK]') >>> >>> # TODO: Initialize `sink`: >>> sink = {} >>> >>> response = client.update_sink(sink_name, sink) Args: sink_name (str): Required. The full resource name of the sink to update, including the parent resource and the sink identifier: :: "projects/[PROJECT_ID]/sinks/[SINK_ID]" "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: ``"projects/my-project-id/sinks/my-sink-id"``. sink (Union[dict, ~google.cloud.logging_v2.types.LogSink]): Required. The updated sink, whose name is the same identifier that appears as part of ``sink_name``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogSink` unique_writer_identity (bool): Optional. See `sinks.create <https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create>`__ for a description of this field. When updating a sink, the effect of this field on the value of ``writer_identity`` in the updated sink depends on both the old and new values of this field: - If the old and new values of this field are both false or both true, then there is no change to the sink's ``writer_identity``. - If the old value is false and the new value is true, then ``writer_identity`` is changed to a unique service account. - It is an error if the old value is true and the new value is set to false or defaulted to false. update_mask (Union[dict, ~google.cloud.logging_v2.types.FieldMask]): Optional. Field mask that specifies the fields in ``sink`` that need an update. A sink field will be overwritten if, and only if, it is in the update mask. ``name`` and output only fields cannot be updated. An empty updateMask is temporarily treated as using the following mask for backwards compatibility purposes: destination,filter,includeChildren At some point in the future, behavior will be removed and specifying an empty updateMask will be an error. For a detailed ``FieldMask`` definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask Example: ``updateMask=filter``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.FieldMask` 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.logging_v2.types.LogSink` 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_sink" not in self._inner_api_calls: self._inner_api_calls[ "update_sink" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_sink, default_retry=self._method_configs["UpdateSink"].retry, default_timeout=self._method_configs["UpdateSink"].timeout, client_info=self._client_info, ) request = logging_config_pb2.UpdateSinkRequest( sink_name=sink_name, sink=sink, unique_writer_identity=unique_writer_identity, update_mask=update_mask, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("sink_name", sink_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_sink"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def update_sink( self, sink_name, sink, unique_writer_identity=None, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. The updated sink might also have a new ``writer_identity``; see the ``unique_writer_identity`` field. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> sink_name = client.sink_path('[PROJECT]', '[SINK]') >>> >>> # TODO: Initialize `sink`: >>> sink = {} >>> >>> response = client.update_sink(sink_name, sink) Args: sink_name (str): Required. The full resource name of the sink to update, including the parent resource and the sink identifier: :: "projects/[PROJECT_ID]/sinks/[SINK_ID]" "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: ``"projects/my-project-id/sinks/my-sink-id"``. sink (Union[dict, ~google.cloud.logging_v2.types.LogSink]): Required. The updated sink, whose name is the same identifier that appears as part of ``sink_name``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogSink` unique_writer_identity (bool): Optional. See `sinks.create <https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create>`__ for a description of this field. When updating a sink, the effect of this field on the value of ``writer_identity`` in the updated sink depends on both the old and new values of this field: - If the old and new values of this field are both false or both true, then there is no change to the sink's ``writer_identity``. - If the old value is false and the new value is true, then ``writer_identity`` is changed to a unique service account. - It is an error if the old value is true and the new value is set to false or defaulted to false. update_mask (Union[dict, ~google.cloud.logging_v2.types.FieldMask]): Optional. Field mask that specifies the fields in ``sink`` that need an update. A sink field will be overwritten if, and only if, it is in the update mask. ``name`` and output only fields cannot be updated. An empty updateMask is temporarily treated as using the following mask for backwards compatibility purposes: destination,filter,includeChildren At some point in the future, behavior will be removed and specifying an empty updateMask will be an error. For a detailed ``FieldMask`` definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask Example: ``updateMask=filter``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.FieldMask` 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.logging_v2.types.LogSink` 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_sink" not in self._inner_api_calls: self._inner_api_calls[ "update_sink" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_sink, default_retry=self._method_configs["UpdateSink"].retry, default_timeout=self._method_configs["UpdateSink"].timeout, client_info=self._client_info, ) request = logging_config_pb2.UpdateSinkRequest( sink_name=sink_name, sink=sink, unique_writer_identity=unique_writer_identity, update_mask=update_mask, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("sink_name", sink_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_sink"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "update_sink", "(", "self", ",", "sink_name", ",", "sink", ",", "unique_writer_identity", "=", "None", ",", "update_mask", "=", "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_sink\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"update_sink\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "update_sink", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"UpdateSink\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"UpdateSink\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "logging_config_pb2", ".", "UpdateSinkRequest", "(", "sink_name", "=", "sink_name", ",", "sink", "=", "sink", ",", "unique_writer_identity", "=", "unique_writer_identity", ",", "update_mask", "=", "update_mask", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"sink_name\"", ",", "sink_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_sink\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. The updated sink might also have a new ``writer_identity``; see the ``unique_writer_identity`` field. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> sink_name = client.sink_path('[PROJECT]', '[SINK]') >>> >>> # TODO: Initialize `sink`: >>> sink = {} >>> >>> response = client.update_sink(sink_name, sink) Args: sink_name (str): Required. The full resource name of the sink to update, including the parent resource and the sink identifier: :: "projects/[PROJECT_ID]/sinks/[SINK_ID]" "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: ``"projects/my-project-id/sinks/my-sink-id"``. sink (Union[dict, ~google.cloud.logging_v2.types.LogSink]): Required. The updated sink, whose name is the same identifier that appears as part of ``sink_name``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogSink` unique_writer_identity (bool): Optional. See `sinks.create <https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create>`__ for a description of this field. When updating a sink, the effect of this field on the value of ``writer_identity`` in the updated sink depends on both the old and new values of this field: - If the old and new values of this field are both false or both true, then there is no change to the sink's ``writer_identity``. - If the old value is false and the new value is true, then ``writer_identity`` is changed to a unique service account. - It is an error if the old value is true and the new value is set to false or defaulted to false. update_mask (Union[dict, ~google.cloud.logging_v2.types.FieldMask]): Optional. Field mask that specifies the fields in ``sink`` that need an update. A sink field will be overwritten if, and only if, it is in the update mask. ``name`` and output only fields cannot be updated. An empty updateMask is temporarily treated as using the following mask for backwards compatibility purposes: destination,filter,includeChildren At some point in the future, behavior will be removed and specifying an empty updateMask will be an error. For a detailed ``FieldMask`` definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask Example: ``updateMask=filter``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.FieldMask` 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.logging_v2.types.LogSink` 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", "sink", ".", "This", "method", "replaces", "the", "following", "fields", "in", "the", "existing", "sink", "with", "values", "from", "the", "new", "sink", ":", "destination", "and", "filter", ".", "The", "updated", "sink", "might", "also", "have", "a", "new", "writer_identity", ";", "see", "the", "unique_writer_identity", "field", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/config_service_v2_client.py#L495-L619
train
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/config_service_v2_client.py
ConfigServiceV2Client.create_exclusion
def create_exclusion( self, parent, exclusion, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new exclusion in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `exclusion`: >>> exclusion = {} >>> >>> response = client.create_exclusion(parent, exclusion) Args: parent (str): Required. The parent resource in which to create the exclusion: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. exclusion (Union[dict, ~google.cloud.logging_v2.types.LogExclusion]): Required. The new exclusion, whose ``name`` parameter is an exclusion name that is not already used in the parent resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogExclusion` 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.logging_v2.types.LogExclusion` 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_exclusion" not in self._inner_api_calls: self._inner_api_calls[ "create_exclusion" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_exclusion, default_retry=self._method_configs["CreateExclusion"].retry, default_timeout=self._method_configs["CreateExclusion"].timeout, client_info=self._client_info, ) request = logging_config_pb2.CreateExclusionRequest( parent=parent, exclusion=exclusion ) 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_exclusion"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_exclusion( self, parent, exclusion, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new exclusion in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `exclusion`: >>> exclusion = {} >>> >>> response = client.create_exclusion(parent, exclusion) Args: parent (str): Required. The parent resource in which to create the exclusion: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. exclusion (Union[dict, ~google.cloud.logging_v2.types.LogExclusion]): Required. The new exclusion, whose ``name`` parameter is an exclusion name that is not already used in the parent resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogExclusion` 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.logging_v2.types.LogExclusion` 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_exclusion" not in self._inner_api_calls: self._inner_api_calls[ "create_exclusion" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_exclusion, default_retry=self._method_configs["CreateExclusion"].retry, default_timeout=self._method_configs["CreateExclusion"].timeout, client_info=self._client_info, ) request = logging_config_pb2.CreateExclusionRequest( parent=parent, exclusion=exclusion ) 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_exclusion"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_exclusion", "(", "self", ",", "parent", ",", "exclusion", ",", "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_exclusion\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_exclusion\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_exclusion", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateExclusion\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateExclusion\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "logging_config_pb2", ".", "CreateExclusionRequest", "(", "parent", "=", "parent", ",", "exclusion", "=", "exclusion", ")", "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_exclusion\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a new exclusion in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `exclusion`: >>> exclusion = {} >>> >>> response = client.create_exclusion(parent, exclusion) Args: parent (str): Required. The parent resource in which to create the exclusion: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. exclusion (Union[dict, ~google.cloud.logging_v2.types.LogExclusion]): Required. The new exclusion, whose ``name`` parameter is an exclusion name that is not already used in the parent resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogExclusion` 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.logging_v2.types.LogExclusion` 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", "exclusion", "in", "a", "specified", "parent", "resource", ".", "Only", "log", "entries", "belonging", "to", "that", "resource", "can", "be", "excluded", ".", "You", "can", "have", "up", "to", "10", "exclusions", "in", "a", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/config_service_v2_client.py#L886-L976
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/_helpers.py
_make_value_pb
def _make_value_pb(value): """Helper for :func:`_make_list_value_pbs`. :type value: scalar value :param value: value to convert :rtype: :class:`~google.protobuf.struct_pb2.Value` :returns: value protobufs :raises ValueError: if value is not of a known scalar type. """ if value is None: return Value(null_value="NULL_VALUE") if isinstance(value, (list, tuple)): return Value(list_value=_make_list_value_pb(value)) if isinstance(value, bool): return Value(bool_value=value) if isinstance(value, six.integer_types): return Value(string_value=str(value)) if isinstance(value, float): if math.isnan(value): return Value(string_value="NaN") if math.isinf(value): if value > 0: return Value(string_value="Infinity") else: return Value(string_value="-Infinity") return Value(number_value=value) if isinstance(value, datetime_helpers.DatetimeWithNanoseconds): return Value(string_value=value.rfc3339()) if isinstance(value, datetime.datetime): return Value(string_value=_datetime_to_rfc3339(value)) if isinstance(value, datetime.date): return Value(string_value=value.isoformat()) if isinstance(value, six.binary_type): value = _try_to_coerce_bytes(value) return Value(string_value=value) if isinstance(value, six.text_type): return Value(string_value=value) if isinstance(value, ListValue): return Value(list_value=value) raise ValueError("Unknown type: %s" % (value,))
python
def _make_value_pb(value): """Helper for :func:`_make_list_value_pbs`. :type value: scalar value :param value: value to convert :rtype: :class:`~google.protobuf.struct_pb2.Value` :returns: value protobufs :raises ValueError: if value is not of a known scalar type. """ if value is None: return Value(null_value="NULL_VALUE") if isinstance(value, (list, tuple)): return Value(list_value=_make_list_value_pb(value)) if isinstance(value, bool): return Value(bool_value=value) if isinstance(value, six.integer_types): return Value(string_value=str(value)) if isinstance(value, float): if math.isnan(value): return Value(string_value="NaN") if math.isinf(value): if value > 0: return Value(string_value="Infinity") else: return Value(string_value="-Infinity") return Value(number_value=value) if isinstance(value, datetime_helpers.DatetimeWithNanoseconds): return Value(string_value=value.rfc3339()) if isinstance(value, datetime.datetime): return Value(string_value=_datetime_to_rfc3339(value)) if isinstance(value, datetime.date): return Value(string_value=value.isoformat()) if isinstance(value, six.binary_type): value = _try_to_coerce_bytes(value) return Value(string_value=value) if isinstance(value, six.text_type): return Value(string_value=value) if isinstance(value, ListValue): return Value(list_value=value) raise ValueError("Unknown type: %s" % (value,))
[ "def", "_make_value_pb", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "Value", "(", "null_value", "=", "\"NULL_VALUE\"", ")", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "Value", "(", "list_value", "=", "_make_list_value_pb", "(", "value", ")", ")", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "Value", "(", "bool_value", "=", "value", ")", "if", "isinstance", "(", "value", ",", "six", ".", "integer_types", ")", ":", "return", "Value", "(", "string_value", "=", "str", "(", "value", ")", ")", "if", "isinstance", "(", "value", ",", "float", ")", ":", "if", "math", ".", "isnan", "(", "value", ")", ":", "return", "Value", "(", "string_value", "=", "\"NaN\"", ")", "if", "math", ".", "isinf", "(", "value", ")", ":", "if", "value", ">", "0", ":", "return", "Value", "(", "string_value", "=", "\"Infinity\"", ")", "else", ":", "return", "Value", "(", "string_value", "=", "\"-Infinity\"", ")", "return", "Value", "(", "number_value", "=", "value", ")", "if", "isinstance", "(", "value", ",", "datetime_helpers", ".", "DatetimeWithNanoseconds", ")", ":", "return", "Value", "(", "string_value", "=", "value", ".", "rfc3339", "(", ")", ")", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "Value", "(", "string_value", "=", "_datetime_to_rfc3339", "(", "value", ")", ")", "if", "isinstance", "(", "value", ",", "datetime", ".", "date", ")", ":", "return", "Value", "(", "string_value", "=", "value", ".", "isoformat", "(", ")", ")", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "_try_to_coerce_bytes", "(", "value", ")", "return", "Value", "(", "string_value", "=", "value", ")", "if", "isinstance", "(", "value", ",", "six", ".", "text_type", ")", ":", "return", "Value", "(", "string_value", "=", "value", ")", "if", "isinstance", "(", "value", ",", "ListValue", ")", ":", "return", "Value", "(", "list_value", "=", "value", ")", "raise", "ValueError", "(", "\"Unknown type: %s\"", "%", "(", "value", ",", ")", ")" ]
Helper for :func:`_make_list_value_pbs`. :type value: scalar value :param value: value to convert :rtype: :class:`~google.protobuf.struct_pb2.Value` :returns: value protobufs :raises ValueError: if value is not of a known scalar type.
[ "Helper", "for", ":", "func", ":", "_make_list_value_pbs", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/_helpers.py#L51-L91
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/_helpers.py
_parse_value_pb
def _parse_value_pb(value_pb, field_type): """Convert a Value protobuf to cell data. :type value_pb: :class:`~google.protobuf.struct_pb2.Value` :param value_pb: protobuf to convert :type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type` :param field_type: type code for the value :rtype: varies on field_type :returns: value extracted from value_pb :raises ValueError: if unknown type is passed """ if value_pb.HasField("null_value"): return None if field_type.code == type_pb2.STRING: result = value_pb.string_value elif field_type.code == type_pb2.BYTES: result = value_pb.string_value.encode("utf8") elif field_type.code == type_pb2.BOOL: result = value_pb.bool_value elif field_type.code == type_pb2.INT64: result = int(value_pb.string_value) elif field_type.code == type_pb2.FLOAT64: if value_pb.HasField("string_value"): result = float(value_pb.string_value) else: result = value_pb.number_value elif field_type.code == type_pb2.DATE: result = _date_from_iso8601_date(value_pb.string_value) elif field_type.code == type_pb2.TIMESTAMP: DatetimeWithNanoseconds = datetime_helpers.DatetimeWithNanoseconds result = DatetimeWithNanoseconds.from_rfc3339(value_pb.string_value) elif field_type.code == type_pb2.ARRAY: result = [ _parse_value_pb(item_pb, field_type.array_element_type) for item_pb in value_pb.list_value.values ] elif field_type.code == type_pb2.STRUCT: result = [ _parse_value_pb(item_pb, field_type.struct_type.fields[i].type) for (i, item_pb) in enumerate(value_pb.list_value.values) ] else: raise ValueError("Unknown type: %s" % (field_type,)) return result
python
def _parse_value_pb(value_pb, field_type): """Convert a Value protobuf to cell data. :type value_pb: :class:`~google.protobuf.struct_pb2.Value` :param value_pb: protobuf to convert :type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type` :param field_type: type code for the value :rtype: varies on field_type :returns: value extracted from value_pb :raises ValueError: if unknown type is passed """ if value_pb.HasField("null_value"): return None if field_type.code == type_pb2.STRING: result = value_pb.string_value elif field_type.code == type_pb2.BYTES: result = value_pb.string_value.encode("utf8") elif field_type.code == type_pb2.BOOL: result = value_pb.bool_value elif field_type.code == type_pb2.INT64: result = int(value_pb.string_value) elif field_type.code == type_pb2.FLOAT64: if value_pb.HasField("string_value"): result = float(value_pb.string_value) else: result = value_pb.number_value elif field_type.code == type_pb2.DATE: result = _date_from_iso8601_date(value_pb.string_value) elif field_type.code == type_pb2.TIMESTAMP: DatetimeWithNanoseconds = datetime_helpers.DatetimeWithNanoseconds result = DatetimeWithNanoseconds.from_rfc3339(value_pb.string_value) elif field_type.code == type_pb2.ARRAY: result = [ _parse_value_pb(item_pb, field_type.array_element_type) for item_pb in value_pb.list_value.values ] elif field_type.code == type_pb2.STRUCT: result = [ _parse_value_pb(item_pb, field_type.struct_type.fields[i].type) for (i, item_pb) in enumerate(value_pb.list_value.values) ] else: raise ValueError("Unknown type: %s" % (field_type,)) return result
[ "def", "_parse_value_pb", "(", "value_pb", ",", "field_type", ")", ":", "if", "value_pb", ".", "HasField", "(", "\"null_value\"", ")", ":", "return", "None", "if", "field_type", ".", "code", "==", "type_pb2", ".", "STRING", ":", "result", "=", "value_pb", ".", "string_value", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "BYTES", ":", "result", "=", "value_pb", ".", "string_value", ".", "encode", "(", "\"utf8\"", ")", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "BOOL", ":", "result", "=", "value_pb", ".", "bool_value", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "INT64", ":", "result", "=", "int", "(", "value_pb", ".", "string_value", ")", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "FLOAT64", ":", "if", "value_pb", ".", "HasField", "(", "\"string_value\"", ")", ":", "result", "=", "float", "(", "value_pb", ".", "string_value", ")", "else", ":", "result", "=", "value_pb", ".", "number_value", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "DATE", ":", "result", "=", "_date_from_iso8601_date", "(", "value_pb", ".", "string_value", ")", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "TIMESTAMP", ":", "DatetimeWithNanoseconds", "=", "datetime_helpers", ".", "DatetimeWithNanoseconds", "result", "=", "DatetimeWithNanoseconds", ".", "from_rfc3339", "(", "value_pb", ".", "string_value", ")", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "ARRAY", ":", "result", "=", "[", "_parse_value_pb", "(", "item_pb", ",", "field_type", ".", "array_element_type", ")", "for", "item_pb", "in", "value_pb", ".", "list_value", ".", "values", "]", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "STRUCT", ":", "result", "=", "[", "_parse_value_pb", "(", "item_pb", ",", "field_type", ".", "struct_type", ".", "fields", "[", "i", "]", ".", "type", ")", "for", "(", "i", ",", "item_pb", ")", "in", "enumerate", "(", "value_pb", ".", "list_value", ".", "values", ")", "]", "else", ":", "raise", "ValueError", "(", "\"Unknown type: %s\"", "%", "(", "field_type", ",", ")", ")", "return", "result" ]
Convert a Value protobuf to cell data. :type value_pb: :class:`~google.protobuf.struct_pb2.Value` :param value_pb: protobuf to convert :type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type` :param field_type: type code for the value :rtype: varies on field_type :returns: value extracted from value_pb :raises ValueError: if unknown type is passed
[ "Convert", "a", "Value", "protobuf", "to", "cell", "data", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/_helpers.py#L122-L167
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/_helpers.py
_parse_list_value_pbs
def _parse_list_value_pbs(rows, row_type): """Convert a list of ListValue protobufs into a list of list of cell data. :type rows: list of :class:`~google.protobuf.struct_pb2.ListValue` :param rows: row data returned from a read/query :type row_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.StructType` :param row_type: row schema specification :rtype: list of list of cell data :returns: data for the rows, coerced into appropriate types """ result = [] for row in rows: row_data = [] for value_pb, field in zip(row.values, row_type.fields): row_data.append(_parse_value_pb(value_pb, field.type)) result.append(row_data) return result
python
def _parse_list_value_pbs(rows, row_type): """Convert a list of ListValue protobufs into a list of list of cell data. :type rows: list of :class:`~google.protobuf.struct_pb2.ListValue` :param rows: row data returned from a read/query :type row_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.StructType` :param row_type: row schema specification :rtype: list of list of cell data :returns: data for the rows, coerced into appropriate types """ result = [] for row in rows: row_data = [] for value_pb, field in zip(row.values, row_type.fields): row_data.append(_parse_value_pb(value_pb, field.type)) result.append(row_data) return result
[ "def", "_parse_list_value_pbs", "(", "rows", ",", "row_type", ")", ":", "result", "=", "[", "]", "for", "row", "in", "rows", ":", "row_data", "=", "[", "]", "for", "value_pb", ",", "field", "in", "zip", "(", "row", ".", "values", ",", "row_type", ".", "fields", ")", ":", "row_data", ".", "append", "(", "_parse_value_pb", "(", "value_pb", ",", "field", ".", "type", ")", ")", "result", ".", "append", "(", "row_data", ")", "return", "result" ]
Convert a list of ListValue protobufs into a list of list of cell data. :type rows: list of :class:`~google.protobuf.struct_pb2.ListValue` :param rows: row data returned from a read/query :type row_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.StructType` :param row_type: row schema specification :rtype: list of list of cell data :returns: data for the rows, coerced into appropriate types
[ "Convert", "a", "list", "of", "ListValue", "protobufs", "into", "a", "list", "of", "list", "of", "cell", "data", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/_helpers.py#L173-L191
train
googleapis/google-cloud-python
asset/google/cloud/asset_v1/gapic/asset_service_client.py
AssetServiceClient.export_assets
def export_assets( self, parent, output_config, read_time=None, asset_types=None, content_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Exports assets with time and resource types to a given Cloud Storage location. The output format is newline-delimited JSON. This API implements the ``google.longrunning.Operation`` API allowing you to keep track of the export. Example: >>> from google.cloud import asset_v1 >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.export_assets(parent, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The relative name of the root asset. This can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id"), or a project number (such as "projects/12345"), or a folder number (such as "folders/123"). output_config (Union[dict, ~google.cloud.asset_v1.types.OutputConfig]): Required. Output configuration indicating where the results will be output to. All results will be in newline delimited JSON format. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.OutputConfig` read_time (Union[dict, ~google.cloud.asset_v1.types.Timestamp]): Timestamp to take an asset snapshot. This can only be set to a timestamp between 2018-10-02 UTC (inclusive) and the current time. If not specified, the current time will be used. Due to delays in resource data collection and indexing, there is a volatile window during which running the same query may get different results. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.Timestamp` asset_types (list[str]): A list of asset types of which to take a snapshot for. For example: "compute.googleapis.com/Disk". If specified, only matching assets will be returned. See `Introduction to Cloud Asset Inventory <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/overview>`__ for all supported asset types. content_type (~google.cloud.asset_v1.types.ContentType): Asset content type. If not specified, no content but the asset name will be returned. 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.asset_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 "export_assets" not in self._inner_api_calls: self._inner_api_calls[ "export_assets" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.export_assets, default_retry=self._method_configs["ExportAssets"].retry, default_timeout=self._method_configs["ExportAssets"].timeout, client_info=self._client_info, ) request = asset_service_pb2.ExportAssetsRequest( parent=parent, output_config=output_config, read_time=read_time, asset_types=asset_types, content_type=content_type, ) operation = self._inner_api_calls["export_assets"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, asset_service_pb2.ExportAssetsResponse, metadata_type=asset_service_pb2.ExportAssetsRequest, )
python
def export_assets( self, parent, output_config, read_time=None, asset_types=None, content_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Exports assets with time and resource types to a given Cloud Storage location. The output format is newline-delimited JSON. This API implements the ``google.longrunning.Operation`` API allowing you to keep track of the export. Example: >>> from google.cloud import asset_v1 >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.export_assets(parent, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The relative name of the root asset. This can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id"), or a project number (such as "projects/12345"), or a folder number (such as "folders/123"). output_config (Union[dict, ~google.cloud.asset_v1.types.OutputConfig]): Required. Output configuration indicating where the results will be output to. All results will be in newline delimited JSON format. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.OutputConfig` read_time (Union[dict, ~google.cloud.asset_v1.types.Timestamp]): Timestamp to take an asset snapshot. This can only be set to a timestamp between 2018-10-02 UTC (inclusive) and the current time. If not specified, the current time will be used. Due to delays in resource data collection and indexing, there is a volatile window during which running the same query may get different results. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.Timestamp` asset_types (list[str]): A list of asset types of which to take a snapshot for. For example: "compute.googleapis.com/Disk". If specified, only matching assets will be returned. See `Introduction to Cloud Asset Inventory <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/overview>`__ for all supported asset types. content_type (~google.cloud.asset_v1.types.ContentType): Asset content type. If not specified, no content but the asset name will be returned. 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.asset_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 "export_assets" not in self._inner_api_calls: self._inner_api_calls[ "export_assets" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.export_assets, default_retry=self._method_configs["ExportAssets"].retry, default_timeout=self._method_configs["ExportAssets"].timeout, client_info=self._client_info, ) request = asset_service_pb2.ExportAssetsRequest( parent=parent, output_config=output_config, read_time=read_time, asset_types=asset_types, content_type=content_type, ) operation = self._inner_api_calls["export_assets"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, asset_service_pb2.ExportAssetsResponse, metadata_type=asset_service_pb2.ExportAssetsRequest, )
[ "def", "export_assets", "(", "self", ",", "parent", ",", "output_config", ",", "read_time", "=", "None", ",", "asset_types", "=", "None", ",", "content_type", "=", "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", "\"export_assets\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"export_assets\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "export_assets", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"ExportAssets\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"ExportAssets\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "asset_service_pb2", ".", "ExportAssetsRequest", "(", "parent", "=", "parent", ",", "output_config", "=", "output_config", ",", "read_time", "=", "read_time", ",", "asset_types", "=", "asset_types", ",", "content_type", "=", "content_type", ",", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"export_assets\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "asset_service_pb2", ".", "ExportAssetsResponse", ",", "metadata_type", "=", "asset_service_pb2", ".", "ExportAssetsRequest", ",", ")" ]
Exports assets with time and resource types to a given Cloud Storage location. The output format is newline-delimited JSON. This API implements the ``google.longrunning.Operation`` API allowing you to keep track of the export. Example: >>> from google.cloud import asset_v1 >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.export_assets(parent, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The relative name of the root asset. This can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id"), or a project number (such as "projects/12345"), or a folder number (such as "folders/123"). output_config (Union[dict, ~google.cloud.asset_v1.types.OutputConfig]): Required. Output configuration indicating where the results will be output to. All results will be in newline delimited JSON format. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.OutputConfig` read_time (Union[dict, ~google.cloud.asset_v1.types.Timestamp]): Timestamp to take an asset snapshot. This can only be set to a timestamp between 2018-10-02 UTC (inclusive) and the current time. If not specified, the current time will be used. Due to delays in resource data collection and indexing, there is a volatile window during which running the same query may get different results. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.Timestamp` asset_types (list[str]): A list of asset types of which to take a snapshot for. For example: "compute.googleapis.com/Disk". If specified, only matching assets will be returned. See `Introduction to Cloud Asset Inventory <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/overview>`__ for all supported asset types. content_type (~google.cloud.asset_v1.types.ContentType): Asset content type. If not specified, no content but the asset name will be returned. 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.asset_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.
[ "Exports", "assets", "with", "time", "and", "resource", "types", "to", "a", "given", "Cloud", "Storage", "location", ".", "The", "output", "format", "is", "newline", "-", "delimited", "JSON", ".", "This", "API", "implements", "the", "google", ".", "longrunning", ".", "Operation", "API", "allowing", "you", "to", "keep", "track", "of", "the", "export", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/asset/google/cloud/asset_v1/gapic/asset_service_client.py#L179-L288
train
googleapis/google-cloud-python
asset/google/cloud/asset_v1/gapic/asset_service_client.py
AssetServiceClient.batch_get_assets_history
def batch_get_assets_history( self, parent, content_type, read_time_window, asset_names=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Batch gets the update history of assets that overlap a time window. For RESOURCE content, this API outputs history with asset in both non-delete or deleted status. For IAM\_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can create gaps in the output history. If a specified asset does not exist, this API returns an INVALID\_ARGUMENT error. Example: >>> from google.cloud import asset_v1 >>> from google.cloud.asset_v1 import enums >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `content_type`: >>> content_type = enums.ContentType.CONTENT_TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `read_time_window`: >>> read_time_window = {} >>> >>> response = client.batch_get_assets_history(parent, content_type, read_time_window) Args: parent (str): Required. The relative name of the root asset. It can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id")", or a project number (such as "projects/12345"). content_type (~google.cloud.asset_v1.types.ContentType): Required. The content type. read_time_window (Union[dict, ~google.cloud.asset_v1.types.TimeWindow]): Optional. The time window for the asset history. Both start\_time and end\_time are optional and if set, it must be after 2018-10-02 UTC. If end\_time is not set, it is default to current timestamp. If start\_time is not set, the snapshot of the assets at end\_time will be returned. The returned results contain all temporal assets whose time window overlap with read\_time\_window. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.TimeWindow` asset_names (list[str]): A list of the full names of the assets. For example: ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. See `Resource Names <https://cloud.google.com/apis/design/resource_names#full_resource_name>`__ and `Resource Name Format <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/resource-name-format>`__ for more info. The request becomes a no-op if the asset name list is empty, and the max size of the asset name list is 100 in one request. 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.asset_v1.types.BatchGetAssetsHistoryResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "batch_get_assets_history" not in self._inner_api_calls: self._inner_api_calls[ "batch_get_assets_history" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_get_assets_history, default_retry=self._method_configs["BatchGetAssetsHistory"].retry, default_timeout=self._method_configs["BatchGetAssetsHistory"].timeout, client_info=self._client_info, ) request = asset_service_pb2.BatchGetAssetsHistoryRequest( parent=parent, content_type=content_type, read_time_window=read_time_window, asset_names=asset_names, ) return self._inner_api_calls["batch_get_assets_history"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def batch_get_assets_history( self, parent, content_type, read_time_window, asset_names=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Batch gets the update history of assets that overlap a time window. For RESOURCE content, this API outputs history with asset in both non-delete or deleted status. For IAM\_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can create gaps in the output history. If a specified asset does not exist, this API returns an INVALID\_ARGUMENT error. Example: >>> from google.cloud import asset_v1 >>> from google.cloud.asset_v1 import enums >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `content_type`: >>> content_type = enums.ContentType.CONTENT_TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `read_time_window`: >>> read_time_window = {} >>> >>> response = client.batch_get_assets_history(parent, content_type, read_time_window) Args: parent (str): Required. The relative name of the root asset. It can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id")", or a project number (such as "projects/12345"). content_type (~google.cloud.asset_v1.types.ContentType): Required. The content type. read_time_window (Union[dict, ~google.cloud.asset_v1.types.TimeWindow]): Optional. The time window for the asset history. Both start\_time and end\_time are optional and if set, it must be after 2018-10-02 UTC. If end\_time is not set, it is default to current timestamp. If start\_time is not set, the snapshot of the assets at end\_time will be returned. The returned results contain all temporal assets whose time window overlap with read\_time\_window. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.TimeWindow` asset_names (list[str]): A list of the full names of the assets. For example: ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. See `Resource Names <https://cloud.google.com/apis/design/resource_names#full_resource_name>`__ and `Resource Name Format <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/resource-name-format>`__ for more info. The request becomes a no-op if the asset name list is empty, and the max size of the asset name list is 100 in one request. 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.asset_v1.types.BatchGetAssetsHistoryResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "batch_get_assets_history" not in self._inner_api_calls: self._inner_api_calls[ "batch_get_assets_history" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_get_assets_history, default_retry=self._method_configs["BatchGetAssetsHistory"].retry, default_timeout=self._method_configs["BatchGetAssetsHistory"].timeout, client_info=self._client_info, ) request = asset_service_pb2.BatchGetAssetsHistoryRequest( parent=parent, content_type=content_type, read_time_window=read_time_window, asset_names=asset_names, ) return self._inner_api_calls["batch_get_assets_history"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "batch_get_assets_history", "(", "self", ",", "parent", ",", "content_type", ",", "read_time_window", ",", "asset_names", "=", "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", "\"batch_get_assets_history\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"batch_get_assets_history\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "batch_get_assets_history", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"BatchGetAssetsHistory\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"BatchGetAssetsHistory\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "asset_service_pb2", ".", "BatchGetAssetsHistoryRequest", "(", "parent", "=", "parent", ",", "content_type", "=", "content_type", ",", "read_time_window", "=", "read_time_window", ",", "asset_names", "=", "asset_names", ",", ")", "return", "self", ".", "_inner_api_calls", "[", "\"batch_get_assets_history\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Batch gets the update history of assets that overlap a time window. For RESOURCE content, this API outputs history with asset in both non-delete or deleted status. For IAM\_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can create gaps in the output history. If a specified asset does not exist, this API returns an INVALID\_ARGUMENT error. Example: >>> from google.cloud import asset_v1 >>> from google.cloud.asset_v1 import enums >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `content_type`: >>> content_type = enums.ContentType.CONTENT_TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `read_time_window`: >>> read_time_window = {} >>> >>> response = client.batch_get_assets_history(parent, content_type, read_time_window) Args: parent (str): Required. The relative name of the root asset. It can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id")", or a project number (such as "projects/12345"). content_type (~google.cloud.asset_v1.types.ContentType): Required. The content type. read_time_window (Union[dict, ~google.cloud.asset_v1.types.TimeWindow]): Optional. The time window for the asset history. Both start\_time and end\_time are optional and if set, it must be after 2018-10-02 UTC. If end\_time is not set, it is default to current timestamp. If start\_time is not set, the snapshot of the assets at end\_time will be returned. The returned results contain all temporal assets whose time window overlap with read\_time\_window. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.TimeWindow` asset_names (list[str]): A list of the full names of the assets. For example: ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. See `Resource Names <https://cloud.google.com/apis/design/resource_names#full_resource_name>`__ and `Resource Name Format <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/resource-name-format>`__ for more info. The request becomes a no-op if the asset name list is empty, and the max size of the asset name list is 100 in one request. 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.asset_v1.types.BatchGetAssetsHistoryResponse` 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.
[ "Batch", "gets", "the", "update", "history", "of", "assets", "that", "overlap", "a", "time", "window", ".", "For", "RESOURCE", "content", "this", "API", "outputs", "history", "with", "asset", "in", "both", "non", "-", "delete", "or", "deleted", "status", ".", "For", "IAM", "\\", "_POLICY", "content", "this", "API", "outputs", "history", "when", "the", "asset", "and", "its", "attached", "IAM", "POLICY", "both", "exist", ".", "This", "can", "create", "gaps", "in", "the", "output", "history", ".", "If", "a", "specified", "asset", "does", "not", "exist", "this", "API", "returns", "an", "INVALID", "\\", "_ARGUMENT", "error", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/asset/google/cloud/asset_v1/gapic/asset_service_client.py#L290-L387
train
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
_avro_schema
def _avro_schema(read_session): """Extract and parse Avro schema from a read session. Args: read_session ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \ ): The read session associated with this read rows stream. This contains the schema, which is required to parse the data blocks. Returns: Tuple[fastavro.schema, Tuple[str]]: A parsed Avro schema, using :func:`fastavro.schema.parse_schema` and the column names for a read session. """ json_schema = json.loads(read_session.avro_schema.schema) column_names = tuple((field["name"] for field in json_schema["fields"])) return fastavro.parse_schema(json_schema), column_names
python
def _avro_schema(read_session): """Extract and parse Avro schema from a read session. Args: read_session ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \ ): The read session associated with this read rows stream. This contains the schema, which is required to parse the data blocks. Returns: Tuple[fastavro.schema, Tuple[str]]: A parsed Avro schema, using :func:`fastavro.schema.parse_schema` and the column names for a read session. """ json_schema = json.loads(read_session.avro_schema.schema) column_names = tuple((field["name"] for field in json_schema["fields"])) return fastavro.parse_schema(json_schema), column_names
[ "def", "_avro_schema", "(", "read_session", ")", ":", "json_schema", "=", "json", ".", "loads", "(", "read_session", ".", "avro_schema", ".", "schema", ")", "column_names", "=", "tuple", "(", "(", "field", "[", "\"name\"", "]", "for", "field", "in", "json_schema", "[", "\"fields\"", "]", ")", ")", "return", "fastavro", ".", "parse_schema", "(", "json_schema", ")", ",", "column_names" ]
Extract and parse Avro schema from a read session. Args: read_session ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \ ): The read session associated with this read rows stream. This contains the schema, which is required to parse the data blocks. Returns: Tuple[fastavro.schema, Tuple[str]]: A parsed Avro schema, using :func:`fastavro.schema.parse_schema` and the column names for a read session.
[ "Extract", "and", "parse", "Avro", "schema", "from", "a", "read", "session", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L375-L393
train
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
_avro_rows
def _avro_rows(block, avro_schema): """Parse all rows in a stream block. Args: block ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \ ): A block containing Avro bytes to parse into rows. avro_schema (fastavro.schema): A parsed Avro schema, used to deserialized the bytes in the block. Returns: Iterable[Mapping]: A sequence of rows, represented as dictionaries. """ blockio = six.BytesIO(block.avro_rows.serialized_binary_rows) while True: # Loop in a while loop because schemaless_reader can only read # a single record. try: # TODO: Parse DATETIME into datetime.datetime (no timezone), # instead of as a string. yield fastavro.schemaless_reader(blockio, avro_schema) except StopIteration: break
python
def _avro_rows(block, avro_schema): """Parse all rows in a stream block. Args: block ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \ ): A block containing Avro bytes to parse into rows. avro_schema (fastavro.schema): A parsed Avro schema, used to deserialized the bytes in the block. Returns: Iterable[Mapping]: A sequence of rows, represented as dictionaries. """ blockio = six.BytesIO(block.avro_rows.serialized_binary_rows) while True: # Loop in a while loop because schemaless_reader can only read # a single record. try: # TODO: Parse DATETIME into datetime.datetime (no timezone), # instead of as a string. yield fastavro.schemaless_reader(blockio, avro_schema) except StopIteration: break
[ "def", "_avro_rows", "(", "block", ",", "avro_schema", ")", ":", "blockio", "=", "six", ".", "BytesIO", "(", "block", ".", "avro_rows", ".", "serialized_binary_rows", ")", "while", "True", ":", "# Loop in a while loop because schemaless_reader can only read", "# a single record.", "try", ":", "# TODO: Parse DATETIME into datetime.datetime (no timezone),", "# instead of as a string.", "yield", "fastavro", ".", "schemaless_reader", "(", "blockio", ",", "avro_schema", ")", "except", "StopIteration", ":", "break" ]
Parse all rows in a stream block. Args: block ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \ ): A block containing Avro bytes to parse into rows. avro_schema (fastavro.schema): A parsed Avro schema, used to deserialized the bytes in the block. Returns: Iterable[Mapping]: A sequence of rows, represented as dictionaries.
[ "Parse", "all", "rows", "in", "a", "stream", "block", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L396-L421
train
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
_copy_stream_position
def _copy_stream_position(position): """Copy a StreamPosition. Args: position (Union[ \ dict, \ ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \ ]): StreamPostion (or dictionary in StreamPosition format) to copy. Returns: ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition: A copy of the input StreamPostion. """ if isinstance(position, types.StreamPosition): output = types.StreamPosition() output.CopyFrom(position) return output return types.StreamPosition(**position)
python
def _copy_stream_position(position): """Copy a StreamPosition. Args: position (Union[ \ dict, \ ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \ ]): StreamPostion (or dictionary in StreamPosition format) to copy. Returns: ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition: A copy of the input StreamPostion. """ if isinstance(position, types.StreamPosition): output = types.StreamPosition() output.CopyFrom(position) return output return types.StreamPosition(**position)
[ "def", "_copy_stream_position", "(", "position", ")", ":", "if", "isinstance", "(", "position", ",", "types", ".", "StreamPosition", ")", ":", "output", "=", "types", ".", "StreamPosition", "(", ")", "output", ".", "CopyFrom", "(", "position", ")", "return", "output", "return", "types", ".", "StreamPosition", "(", "*", "*", "position", ")" ]
Copy a StreamPosition. Args: position (Union[ \ dict, \ ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \ ]): StreamPostion (or dictionary in StreamPosition format) to copy. Returns: ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition: A copy of the input StreamPostion.
[ "Copy", "a", "StreamPosition", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L424-L443
train
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
ReadRowsStream._reconnect
def _reconnect(self): """Reconnect to the ReadRows stream using the most recent offset.""" self._wrapped = self._client.read_rows( _copy_stream_position(self._position), **self._read_rows_kwargs )
python
def _reconnect(self): """Reconnect to the ReadRows stream using the most recent offset.""" self._wrapped = self._client.read_rows( _copy_stream_position(self._position), **self._read_rows_kwargs )
[ "def", "_reconnect", "(", "self", ")", ":", "self", ".", "_wrapped", "=", "self", ".", "_client", ".", "read_rows", "(", "_copy_stream_position", "(", "self", ".", "_position", ")", ",", "*", "*", "self", ".", "_read_rows_kwargs", ")" ]
Reconnect to the ReadRows stream using the most recent offset.
[ "Reconnect", "to", "the", "ReadRows", "stream", "using", "the", "most", "recent", "offset", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L128-L132
train
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
ReadRowsStream.to_dataframe
def to_dataframe(self, read_session, dtypes=None): """Create a :class:`pandas.DataFrame` of all rows in the stream. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavro library. Args: read_session ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \ ): The read session associated with this read rows stream. This contains the schema, which is required to parse the data blocks. dtypes ( \ Map[str, Union[str, pandas.Series.dtype]] \ ): Optional. A dictionary of column names pandas ``dtype``s. The provided ``dtype`` is used when constructing the series for the column specified. Otherwise, the default pandas behavior is used. Returns: pandas.DataFrame: A data frame of all rows in the stream. """ if fastavro is None: raise ImportError(_FASTAVRO_REQUIRED) if pandas is None: raise ImportError(_PANDAS_REQUIRED) return self.rows(read_session).to_dataframe(dtypes=dtypes)
python
def to_dataframe(self, read_session, dtypes=None): """Create a :class:`pandas.DataFrame` of all rows in the stream. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavro library. Args: read_session ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \ ): The read session associated with this read rows stream. This contains the schema, which is required to parse the data blocks. dtypes ( \ Map[str, Union[str, pandas.Series.dtype]] \ ): Optional. A dictionary of column names pandas ``dtype``s. The provided ``dtype`` is used when constructing the series for the column specified. Otherwise, the default pandas behavior is used. Returns: pandas.DataFrame: A data frame of all rows in the stream. """ if fastavro is None: raise ImportError(_FASTAVRO_REQUIRED) if pandas is None: raise ImportError(_PANDAS_REQUIRED) return self.rows(read_session).to_dataframe(dtypes=dtypes)
[ "def", "to_dataframe", "(", "self", ",", "read_session", ",", "dtypes", "=", "None", ")", ":", "if", "fastavro", "is", "None", ":", "raise", "ImportError", "(", "_FASTAVRO_REQUIRED", ")", "if", "pandas", "is", "None", ":", "raise", "ImportError", "(", "_PANDAS_REQUIRED", ")", "return", "self", ".", "rows", "(", "read_session", ")", ".", "to_dataframe", "(", "dtypes", "=", "dtypes", ")" ]
Create a :class:`pandas.DataFrame` of all rows in the stream. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavro library. Args: read_session ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \ ): The read session associated with this read rows stream. This contains the schema, which is required to parse the data blocks. dtypes ( \ Map[str, Union[str, pandas.Series.dtype]] \ ): Optional. A dictionary of column names pandas ``dtype``s. The provided ``dtype`` is used when constructing the series for the column specified. Otherwise, the default pandas behavior is used. Returns: pandas.DataFrame: A data frame of all rows in the stream.
[ "Create", "a", ":", "class", ":", "pandas", ".", "DataFrame", "of", "all", "rows", "in", "the", "stream", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L161-L195
train
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
ReadRowsIterable.pages
def pages(self): """A generator of all pages in the stream. Returns: types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]: A generator of pages. """ # Each page is an iterator of rows. But also has num_items, remaining, # and to_dataframe. avro_schema, column_names = _avro_schema(self._read_session) for block in self._reader: self._status = block.status yield ReadRowsPage(avro_schema, column_names, block)
python
def pages(self): """A generator of all pages in the stream. Returns: types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]: A generator of pages. """ # Each page is an iterator of rows. But also has num_items, remaining, # and to_dataframe. avro_schema, column_names = _avro_schema(self._read_session) for block in self._reader: self._status = block.status yield ReadRowsPage(avro_schema, column_names, block)
[ "def", "pages", "(", "self", ")", ":", "# Each page is an iterator of rows. But also has num_items, remaining,", "# and to_dataframe.", "avro_schema", ",", "column_names", "=", "_avro_schema", "(", "self", ".", "_read_session", ")", "for", "block", "in", "self", ".", "_reader", ":", "self", ".", "_status", "=", "block", ".", "status", "yield", "ReadRowsPage", "(", "avro_schema", ",", "column_names", ",", "block", ")" ]
A generator of all pages in the stream. Returns: types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]: A generator of pages.
[ "A", "generator", "of", "all", "pages", "in", "the", "stream", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L226-L238
train
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
ReadRowsIterable.to_dataframe
def to_dataframe(self, dtypes=None): """Create a :class:`pandas.DataFrame` of all rows in the stream. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavro library. Args: dtypes ( \ Map[str, Union[str, pandas.Series.dtype]] \ ): Optional. A dictionary of column names pandas ``dtype``s. The provided ``dtype`` is used when constructing the series for the column specified. Otherwise, the default pandas behavior is used. Returns: pandas.DataFrame: A data frame of all rows in the stream. """ if pandas is None: raise ImportError(_PANDAS_REQUIRED) frames = [] for page in self.pages: frames.append(page.to_dataframe(dtypes=dtypes)) return pandas.concat(frames)
python
def to_dataframe(self, dtypes=None): """Create a :class:`pandas.DataFrame` of all rows in the stream. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavro library. Args: dtypes ( \ Map[str, Union[str, pandas.Series.dtype]] \ ): Optional. A dictionary of column names pandas ``dtype``s. The provided ``dtype`` is used when constructing the series for the column specified. Otherwise, the default pandas behavior is used. Returns: pandas.DataFrame: A data frame of all rows in the stream. """ if pandas is None: raise ImportError(_PANDAS_REQUIRED) frames = [] for page in self.pages: frames.append(page.to_dataframe(dtypes=dtypes)) return pandas.concat(frames)
[ "def", "to_dataframe", "(", "self", ",", "dtypes", "=", "None", ")", ":", "if", "pandas", "is", "None", ":", "raise", "ImportError", "(", "_PANDAS_REQUIRED", ")", "frames", "=", "[", "]", "for", "page", "in", "self", ".", "pages", ":", "frames", ".", "append", "(", "page", ".", "to_dataframe", "(", "dtypes", "=", "dtypes", ")", ")", "return", "pandas", ".", "concat", "(", "frames", ")" ]
Create a :class:`pandas.DataFrame` of all rows in the stream. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavro library. Args: dtypes ( \ Map[str, Union[str, pandas.Series.dtype]] \ ): Optional. A dictionary of column names pandas ``dtype``s. The provided ``dtype`` is used when constructing the series for the column specified. Otherwise, the default pandas behavior is used. Returns: pandas.DataFrame: A data frame of all rows in the stream.
[ "Create", "a", ":", "class", ":", "pandas", ".", "DataFrame", "of", "all", "rows", "in", "the", "stream", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L246-L275
train
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
ReadRowsPage._parse_block
def _parse_block(self): """Parse metadata and rows from the block only once.""" if self._iter_rows is not None: return rows = _avro_rows(self._block, self._avro_schema) self._num_items = self._block.avro_rows.row_count self._remaining = self._block.avro_rows.row_count self._iter_rows = iter(rows)
python
def _parse_block(self): """Parse metadata and rows from the block only once.""" if self._iter_rows is not None: return rows = _avro_rows(self._block, self._avro_schema) self._num_items = self._block.avro_rows.row_count self._remaining = self._block.avro_rows.row_count self._iter_rows = iter(rows)
[ "def", "_parse_block", "(", "self", ")", ":", "if", "self", ".", "_iter_rows", "is", "not", "None", ":", "return", "rows", "=", "_avro_rows", "(", "self", ".", "_block", ",", "self", ".", "_avro_schema", ")", "self", ".", "_num_items", "=", "self", ".", "_block", ".", "avro_rows", ".", "row_count", "self", ".", "_remaining", "=", "self", ".", "_block", ".", "avro_rows", ".", "row_count", "self", ".", "_iter_rows", "=", "iter", "(", "rows", ")" ]
Parse metadata and rows from the block only once.
[ "Parse", "metadata", "and", "rows", "from", "the", "block", "only", "once", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L301-L309
train
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
ReadRowsPage.next
def next(self): """Get the next row in the page.""" self._parse_block() if self._remaining > 0: self._remaining -= 1 return six.next(self._iter_rows)
python
def next(self): """Get the next row in the page.""" self._parse_block() if self._remaining > 0: self._remaining -= 1 return six.next(self._iter_rows)
[ "def", "next", "(", "self", ")", ":", "self", ".", "_parse_block", "(", ")", "if", "self", ".", "_remaining", ">", "0", ":", "self", ".", "_remaining", "-=", "1", "return", "six", ".", "next", "(", "self", ".", "_iter_rows", ")" ]
Get the next row in the page.
[ "Get", "the", "next", "row", "in", "the", "page", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L327-L332
train
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
ReadRowsPage.to_dataframe
def to_dataframe(self, dtypes=None): """Create a :class:`pandas.DataFrame` of rows in the page. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavro library. Args: dtypes ( \ Map[str, Union[str, pandas.Series.dtype]] \ ): Optional. A dictionary of column names pandas ``dtype``s. The provided ``dtype`` is used when constructing the series for the column specified. Otherwise, the default pandas behavior is used. Returns: pandas.DataFrame: A data frame of all rows in the stream. """ if pandas is None: raise ImportError(_PANDAS_REQUIRED) if dtypes is None: dtypes = {} columns = collections.defaultdict(list) for row in self: for column in row: columns[column].append(row[column]) for column in dtypes: columns[column] = pandas.Series(columns[column], dtype=dtypes[column]) return pandas.DataFrame(columns, columns=self._column_names)
python
def to_dataframe(self, dtypes=None): """Create a :class:`pandas.DataFrame` of rows in the page. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavro library. Args: dtypes ( \ Map[str, Union[str, pandas.Series.dtype]] \ ): Optional. A dictionary of column names pandas ``dtype``s. The provided ``dtype`` is used when constructing the series for the column specified. Otherwise, the default pandas behavior is used. Returns: pandas.DataFrame: A data frame of all rows in the stream. """ if pandas is None: raise ImportError(_PANDAS_REQUIRED) if dtypes is None: dtypes = {} columns = collections.defaultdict(list) for row in self: for column in row: columns[column].append(row[column]) for column in dtypes: columns[column] = pandas.Series(columns[column], dtype=dtypes[column]) return pandas.DataFrame(columns, columns=self._column_names)
[ "def", "to_dataframe", "(", "self", ",", "dtypes", "=", "None", ")", ":", "if", "pandas", "is", "None", ":", "raise", "ImportError", "(", "_PANDAS_REQUIRED", ")", "if", "dtypes", "is", "None", ":", "dtypes", "=", "{", "}", "columns", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "row", "in", "self", ":", "for", "column", "in", "row", ":", "columns", "[", "column", "]", ".", "append", "(", "row", "[", "column", "]", ")", "for", "column", "in", "dtypes", ":", "columns", "[", "column", "]", "=", "pandas", ".", "Series", "(", "columns", "[", "column", "]", ",", "dtype", "=", "dtypes", "[", "column", "]", ")", "return", "pandas", ".", "DataFrame", "(", "columns", ",", "columns", "=", "self", ".", "_column_names", ")" ]
Create a :class:`pandas.DataFrame` of rows in the page. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavro library. Args: dtypes ( \ Map[str, Union[str, pandas.Series.dtype]] \ ): Optional. A dictionary of column names pandas ``dtype``s. The provided ``dtype`` is used when constructing the series for the column specified. Otherwise, the default pandas behavior is used. Returns: pandas.DataFrame: A data frame of all rows in the stream.
[ "Create", "a", ":", "class", ":", "pandas", ".", "DataFrame", "of", "rows", "in", "the", "page", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L337-L372
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py
InstanceAdminClient.instance_config_path
def instance_config_path(cls, project, instance_config): """Return a fully-qualified instance_config string.""" return google.api_core.path_template.expand( "projects/{project}/instanceConfigs/{instance_config}", project=project, instance_config=instance_config, )
python
def instance_config_path(cls, project, instance_config): """Return a fully-qualified instance_config string.""" return google.api_core.path_template.expand( "projects/{project}/instanceConfigs/{instance_config}", project=project, instance_config=instance_config, )
[ "def", "instance_config_path", "(", "cls", ",", "project", ",", "instance_config", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/instanceConfigs/{instance_config}\"", ",", "project", "=", "project", ",", "instance_config", "=", "instance_config", ",", ")" ]
Return a fully-qualified instance_config string.
[ "Return", "a", "fully", "-", "qualified", "instance_config", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py#L110-L116
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py
InstanceAdminClient.create_instance
def create_instance( self, parent, instance_id, instance, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an instance and begins preparing it to begin serving. The returned ``long-running operation`` can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, ``CreateInstance`` returns ``ALREADY_EXISTS``. Immediately upon completion of this request: - The instance is readable via the API, with all requested attributes but no allocated resources. Its state is ``CREATING``. Until completion of the returned operation: - Cancelling the operation renders the instance immediately unreadable via the API. - The instance can be deleted. - All other attempts to modify the instance are rejected. Upon completion of the returned operation: - Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). - Databases can be created in the instance. - The instance's allocated resource levels are readable via the API. - The instance's state becomes ``READY``. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track creation of the instance. The ``metadata`` field type is ``CreateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instance_id`: >>> instance_id = '' >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> response = client.create_instance(parent, instance_id, instance) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the project in which to create the instance. Values are of the form ``projects/<project>``. instance_id (str): Required. The ID of the instance to create. Valid identifiers are of the form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be between 6 and 30 characters in length. instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to create. The name may be omitted, but if specified must be ``<parent>/instances/<instance_id>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.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.spanner_admin_instance_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 "create_instance" not in self._inner_api_calls: self._inner_api_calls[ "create_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_instance, default_retry=self._method_configs["CreateInstance"].retry, default_timeout=self._method_configs["CreateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.CreateInstanceRequest( parent=parent, instance_id=instance_id, instance=instance ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["create_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.CreateInstanceMetadata, )
python
def create_instance( self, parent, instance_id, instance, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an instance and begins preparing it to begin serving. The returned ``long-running operation`` can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, ``CreateInstance`` returns ``ALREADY_EXISTS``. Immediately upon completion of this request: - The instance is readable via the API, with all requested attributes but no allocated resources. Its state is ``CREATING``. Until completion of the returned operation: - Cancelling the operation renders the instance immediately unreadable via the API. - The instance can be deleted. - All other attempts to modify the instance are rejected. Upon completion of the returned operation: - Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). - Databases can be created in the instance. - The instance's allocated resource levels are readable via the API. - The instance's state becomes ``READY``. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track creation of the instance. The ``metadata`` field type is ``CreateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instance_id`: >>> instance_id = '' >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> response = client.create_instance(parent, instance_id, instance) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the project in which to create the instance. Values are of the form ``projects/<project>``. instance_id (str): Required. The ID of the instance to create. Valid identifiers are of the form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be between 6 and 30 characters in length. instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to create. The name may be omitted, but if specified must be ``<parent>/instances/<instance_id>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.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.spanner_admin_instance_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 "create_instance" not in self._inner_api_calls: self._inner_api_calls[ "create_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_instance, default_retry=self._method_configs["CreateInstance"].retry, default_timeout=self._method_configs["CreateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.CreateInstanceRequest( parent=parent, instance_id=instance_id, instance=instance ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["create_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.CreateInstanceMetadata, )
[ "def", "create_instance", "(", "self", ",", "parent", ",", "instance_id", ",", "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", "\"create_instance\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_instance\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_instance", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateInstance\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateInstance\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "spanner_instance_admin_pb2", ".", "CreateInstanceRequest", "(", "parent", "=", "parent", ",", "instance_id", "=", "instance_id", ",", "instance", "=", "instance", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"parent\"", ",", "parent", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"create_instance\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "spanner_instance_admin_pb2", ".", "Instance", ",", "metadata_type", "=", "spanner_instance_admin_pb2", ".", "CreateInstanceMetadata", ",", ")" ]
Creates an instance and begins preparing it to begin serving. The returned ``long-running operation`` can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, ``CreateInstance`` returns ``ALREADY_EXISTS``. Immediately upon completion of this request: - The instance is readable via the API, with all requested attributes but no allocated resources. Its state is ``CREATING``. Until completion of the returned operation: - Cancelling the operation renders the instance immediately unreadable via the API. - The instance can be deleted. - All other attempts to modify the instance are rejected. Upon completion of the returned operation: - Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). - Databases can be created in the instance. - The instance's allocated resource levels are readable via the API. - The instance's state becomes ``READY``. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track creation of the instance. The ``metadata`` field type is ``CreateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instance_id`: >>> instance_id = '' >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> response = client.create_instance(parent, instance_id, instance) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the project in which to create the instance. Values are of the form ``projects/<project>``. instance_id (str): Required. The ID of the instance to create. Valid identifiers are of the form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be between 6 and 30 characters in length. instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to create. The name may be omitted, but if specified must be ``<parent>/instances/<instance_id>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.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.spanner_admin_instance_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.
[ "Creates", "an", "instance", "and", "begins", "preparing", "it", "to", "begin", "serving", ".", "The", "returned", "long", "-", "running", "operation", "can", "be", "used", "to", "track", "the", "progress", "of", "preparing", "the", "new", "instance", ".", "The", "instance", "name", "is", "assigned", "by", "the", "caller", ".", "If", "the", "named", "instance", "already", "exists", "CreateInstance", "returns", "ALREADY_EXISTS", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py#L594-L725
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py
InstanceAdminClient.update_instance
def update_instance( self, instance, field_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an instance, and begins allocating or releasing resources as requested. The returned ``long-running operation`` can be used to track the progress of updating the instance. If the named instance does not exist, returns ``NOT_FOUND``. Immediately upon completion of this request: - For resource types for which a decrease in the instance's allocation has been requested, billing is based on the newly-requested level. Until completion of the returned operation: - Cancelling the operation sets its metadata's ``cancel_time``, and begins restoring resources to their pre-request values. The operation is guaranteed to succeed at undoing all resource changes, after which point it terminates with a ``CANCELLED`` status. - All other attempts to modify the instance are rejected. - Reading the instance via the API continues to give the pre-request resource levels. Upon completion of the returned operation: - Billing begins for all successfully-allocated resources (some types may have lower than the requested levels). - All newly-reserved resources are available for serving the instance's tables. - The instance's new resource levels are readable via the API. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track the instance modification. The ``metadata`` field type is ``UpdateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Authorization requires ``spanner.instances.update`` permission on resource ``name``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `field_mask`: >>> field_mask = {} >>> >>> response = client.update_instance(instance, field_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to update, which must always include the instance name. Otherwise, only fields mentioned in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.field\_mask] need be included. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): Required. A mask specifying which fields in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.instance] should be updated. The field mask must always be specified; this prevents any future fields in [][google.spanner.admin.instance.v1.Instance] from being erased accidentally by clients that do not know about them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` 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.spanner_admin_instance_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 "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 = spanner_instance_admin_pb2.UpdateInstanceRequest( instance=instance, field_mask=field_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("instance.name", instance.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.UpdateInstanceMetadata, )
python
def update_instance( self, instance, field_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an instance, and begins allocating or releasing resources as requested. The returned ``long-running operation`` can be used to track the progress of updating the instance. If the named instance does not exist, returns ``NOT_FOUND``. Immediately upon completion of this request: - For resource types for which a decrease in the instance's allocation has been requested, billing is based on the newly-requested level. Until completion of the returned operation: - Cancelling the operation sets its metadata's ``cancel_time``, and begins restoring resources to their pre-request values. The operation is guaranteed to succeed at undoing all resource changes, after which point it terminates with a ``CANCELLED`` status. - All other attempts to modify the instance are rejected. - Reading the instance via the API continues to give the pre-request resource levels. Upon completion of the returned operation: - Billing begins for all successfully-allocated resources (some types may have lower than the requested levels). - All newly-reserved resources are available for serving the instance's tables. - The instance's new resource levels are readable via the API. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track the instance modification. The ``metadata`` field type is ``UpdateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Authorization requires ``spanner.instances.update`` permission on resource ``name``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `field_mask`: >>> field_mask = {} >>> >>> response = client.update_instance(instance, field_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to update, which must always include the instance name. Otherwise, only fields mentioned in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.field\_mask] need be included. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): Required. A mask specifying which fields in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.instance] should be updated. The field mask must always be specified; this prevents any future fields in [][google.spanner.admin.instance.v1.Instance] from being erased accidentally by clients that do not know about them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` 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.spanner_admin_instance_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 "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 = spanner_instance_admin_pb2.UpdateInstanceRequest( instance=instance, field_mask=field_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("instance.name", instance.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.UpdateInstanceMetadata, )
[ "def", "update_instance", "(", "self", ",", "instance", ",", "field_mask", ",", "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", "=", "spanner_instance_admin_pb2", ".", "UpdateInstanceRequest", "(", "instance", "=", "instance", ",", "field_mask", "=", "field_mask", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"instance.name\"", ",", "instance", ".", "name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"update_instance\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "spanner_instance_admin_pb2", ".", "Instance", ",", "metadata_type", "=", "spanner_instance_admin_pb2", ".", "UpdateInstanceMetadata", ",", ")" ]
Updates an instance, and begins allocating or releasing resources as requested. The returned ``long-running operation`` can be used to track the progress of updating the instance. If the named instance does not exist, returns ``NOT_FOUND``. Immediately upon completion of this request: - For resource types for which a decrease in the instance's allocation has been requested, billing is based on the newly-requested level. Until completion of the returned operation: - Cancelling the operation sets its metadata's ``cancel_time``, and begins restoring resources to their pre-request values. The operation is guaranteed to succeed at undoing all resource changes, after which point it terminates with a ``CANCELLED`` status. - All other attempts to modify the instance are rejected. - Reading the instance via the API continues to give the pre-request resource levels. Upon completion of the returned operation: - Billing begins for all successfully-allocated resources (some types may have lower than the requested levels). - All newly-reserved resources are available for serving the instance's tables. - The instance's new resource levels are readable via the API. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track the instance modification. The ``metadata`` field type is ``UpdateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Authorization requires ``spanner.instances.update`` permission on resource ``name``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `field_mask`: >>> field_mask = {} >>> >>> response = client.update_instance(instance, field_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to update, which must always include the instance name. Otherwise, only fields mentioned in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.field\_mask] need be included. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): Required. A mask specifying which fields in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.instance] should be updated. The field mask must always be specified; this prevents any future fields in [][google.spanner.admin.instance.v1.Instance] from being erased accidentally by clients that do not know about them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` 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.spanner_admin_instance_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.
[ "Updates", "an", "instance", "and", "begins", "allocating", "or", "releasing", "resources", "as", "requested", ".", "The", "returned", "long", "-", "running", "operation", "can", "be", "used", "to", "track", "the", "progress", "of", "updating", "the", "instance", ".", "If", "the", "named", "instance", "does", "not", "exist", "returns", "NOT_FOUND", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py#L727-L866
train
googleapis/google-cloud-python
websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py
WebSecurityScannerClient.finding_path
def finding_path(cls, project, scan_config, scan_run, finding): """Return a fully-qualified finding string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}", project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, )
python
def finding_path(cls, project, scan_config, scan_run, finding): """Return a fully-qualified finding string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}", project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, )
[ "def", "finding_path", "(", "cls", ",", "project", ",", "scan_config", ",", "scan_run", ",", "finding", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}\"", ",", "project", "=", "project", ",", "scan_config", "=", "scan_config", ",", "scan_run", "=", "scan_run", ",", "finding", "=", "finding", ",", ")" ]
Return a fully-qualified finding string.
[ "Return", "a", "fully", "-", "qualified", "finding", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py#L87-L95
train
googleapis/google-cloud-python
websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py
WebSecurityScannerClient.scan_config_path
def scan_config_path(cls, project, scan_config): """Return a fully-qualified scan_config string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}", project=project, scan_config=scan_config, )
python
def scan_config_path(cls, project, scan_config): """Return a fully-qualified scan_config string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}", project=project, scan_config=scan_config, )
[ "def", "scan_config_path", "(", "cls", ",", "project", ",", "scan_config", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/scanConfigs/{scan_config}\"", ",", "project", "=", "project", ",", "scan_config", "=", "scan_config", ",", ")" ]
Return a fully-qualified scan_config string.
[ "Return", "a", "fully", "-", "qualified", "scan_config", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py#L105-L111
train
googleapis/google-cloud-python
websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py
WebSecurityScannerClient.scan_run_path
def scan_run_path(cls, project, scan_config, scan_run): """Return a fully-qualified scan_run string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}", project=project, scan_config=scan_config, scan_run=scan_run, )
python
def scan_run_path(cls, project, scan_config, scan_run): """Return a fully-qualified scan_run string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}", project=project, scan_config=scan_config, scan_run=scan_run, )
[ "def", "scan_run_path", "(", "cls", ",", "project", ",", "scan_config", ",", "scan_run", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}\"", ",", "project", "=", "project", ",", "scan_config", "=", "scan_config", ",", "scan_run", "=", "scan_run", ",", ")" ]
Return a fully-qualified scan_run string.
[ "Return", "a", "fully", "-", "qualified", "scan_run", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py#L114-L121
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/client.py
Client.instance_admin_api
def instance_admin_api(self): """Helper for session-related API calls.""" if self._instance_admin_api is None: self._instance_admin_api = InstanceAdminClient( credentials=self.credentials, client_info=_CLIENT_INFO ) return self._instance_admin_api
python
def instance_admin_api(self): """Helper for session-related API calls.""" if self._instance_admin_api is None: self._instance_admin_api = InstanceAdminClient( credentials=self.credentials, client_info=_CLIENT_INFO ) return self._instance_admin_api
[ "def", "instance_admin_api", "(", "self", ")", ":", "if", "self", ".", "_instance_admin_api", "is", "None", ":", "self", ".", "_instance_admin_api", "=", "InstanceAdminClient", "(", "credentials", "=", "self", ".", "credentials", ",", "client_info", "=", "_CLIENT_INFO", ")", "return", "self", ".", "_instance_admin_api" ]
Helper for session-related API calls.
[ "Helper", "for", "session", "-", "related", "API", "calls", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/client.py#L152-L158
train