id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
28,200
googleapis/google-cloud-python
dataproc/google/cloud/dataproc_v1beta2/gapic/workflow_template_service_client.py
WorkflowTemplateServiceClient.get_workflow_template
def get_workflow_template( self, name, version=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Retrieves the latest workflow template. Can retrieve previously instantiated template by specifying optional version parameter. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.WorkflowTemplateServiceClient() >>> >>> name = client.workflow_template_path('[PROJECT]', '[REGION]', '[WORKFLOW_TEMPLATE]') >>> >>> response = client.get_workflow_template(name) Args: name (str): Required. The "resource name" of the workflow template, as described in https://cloud.google.com/apis/design/resource\_names of the form ``projects/{project_id}/regions/{region}/workflowTemplates/{template_id}`` version (int): Optional. The version of workflow template to retrieve. Only previously instatiated versions can be retrieved. If unspecified, retrieves the current version. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types.WorkflowTemplate` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_workflow_template" not in self._inner_api_calls: self._inner_api_calls[ "get_workflow_template" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_workflow_template, default_retry=self._method_configs["GetWorkflowTemplate"].retry, default_timeout=self._method_configs["GetWorkflowTemplate"].timeout, client_info=self._client_info, ) request = workflow_templates_pb2.GetWorkflowTemplateRequest( name=name, version=version ) return self._inner_api_calls["get_workflow_template"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def get_workflow_template( self, name, version=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Retrieves the latest workflow template. Can retrieve previously instantiated template by specifying optional version parameter. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.WorkflowTemplateServiceClient() >>> >>> name = client.workflow_template_path('[PROJECT]', '[REGION]', '[WORKFLOW_TEMPLATE]') >>> >>> response = client.get_workflow_template(name) Args: name (str): Required. The "resource name" of the workflow template, as described in https://cloud.google.com/apis/design/resource\_names of the form ``projects/{project_id}/regions/{region}/workflowTemplates/{template_id}`` version (int): Optional. The version of workflow template to retrieve. Only previously instatiated versions can be retrieved. If unspecified, retrieves the current version. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types.WorkflowTemplate` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_workflow_template" not in self._inner_api_calls: self._inner_api_calls[ "get_workflow_template" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_workflow_template, default_retry=self._method_configs["GetWorkflowTemplate"].retry, default_timeout=self._method_configs["GetWorkflowTemplate"].timeout, client_info=self._client_info, ) request = workflow_templates_pb2.GetWorkflowTemplateRequest( name=name, version=version ) return self._inner_api_calls["get_workflow_template"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "get_workflow_template", "(", "self", ",", "name", ",", "version", "=", "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_workflow_template\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"get_workflow_template\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "get_workflow_template", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"GetWorkflowTemplate\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"GetWorkflowTemplate\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "workflow_templates_pb2", ".", "GetWorkflowTemplateRequest", "(", "name", "=", "name", ",", "version", "=", "version", ")", "return", "self", ".", "_inner_api_calls", "[", "\"get_workflow_template\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Retrieves the latest workflow template. Can retrieve previously instantiated template by specifying optional version parameter. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.WorkflowTemplateServiceClient() >>> >>> name = client.workflow_template_path('[PROJECT]', '[REGION]', '[WORKFLOW_TEMPLATE]') >>> >>> response = client.get_workflow_template(name) Args: name (str): Required. The "resource name" of the workflow template, as described in https://cloud.google.com/apis/design/resource\_names of the form ``projects/{project_id}/regions/{region}/workflowTemplates/{template_id}`` version (int): Optional. The version of workflow template to retrieve. Only previously instatiated versions can be retrieved. If unspecified, retrieves the current version. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types.WorkflowTemplate` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Retrieves", "the", "latest", "workflow", "template", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/workflow_template_service_client.py#L270-L336
28,201
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/schema.py
_parse_schema_resource
def _parse_schema_resource(info): """Parse a resource fragment into a schema field. Args: info: (Mapping[str->dict]): should contain a "fields" key to be parsed Returns: (Union[Sequence[:class:`google.cloud.bigquery.schema.SchemaField`],None]) a list of parsed fields, or ``None`` if no "fields" key found. """ if "fields" not in info: return () schema = [] for r_field in info["fields"]: name = r_field["name"] field_type = r_field["type"] mode = r_field.get("mode", "NULLABLE") description = r_field.get("description") sub_fields = _parse_schema_resource(r_field) schema.append(SchemaField(name, field_type, mode, description, sub_fields)) return schema
python
def _parse_schema_resource(info): """Parse a resource fragment into a schema field. Args: info: (Mapping[str->dict]): should contain a "fields" key to be parsed Returns: (Union[Sequence[:class:`google.cloud.bigquery.schema.SchemaField`],None]) a list of parsed fields, or ``None`` if no "fields" key found. """ if "fields" not in info: return () schema = [] for r_field in info["fields"]: name = r_field["name"] field_type = r_field["type"] mode = r_field.get("mode", "NULLABLE") description = r_field.get("description") sub_fields = _parse_schema_resource(r_field) schema.append(SchemaField(name, field_type, mode, description, sub_fields)) return schema
[ "def", "_parse_schema_resource", "(", "info", ")", ":", "if", "\"fields\"", "not", "in", "info", ":", "return", "(", ")", "schema", "=", "[", "]", "for", "r_field", "in", "info", "[", "\"fields\"", "]", ":", "name", "=", "r_field", "[", "\"name\"", "]", "field_type", "=", "r_field", "[", "\"type\"", "]", "mode", "=", "r_field", ".", "get", "(", "\"mode\"", ",", "\"NULLABLE\"", ")", "description", "=", "r_field", ".", "get", "(", "\"description\"", ")", "sub_fields", "=", "_parse_schema_resource", "(", "r_field", ")", "schema", ".", "append", "(", "SchemaField", "(", "name", ",", "field_type", ",", "mode", ",", "description", ",", "sub_fields", ")", ")", "return", "schema" ]
Parse a resource fragment into a schema field. Args: info: (Mapping[str->dict]): should contain a "fields" key to be parsed Returns: (Union[Sequence[:class:`google.cloud.bigquery.schema.SchemaField`],None]) a list of parsed fields, or ``None`` if no "fields" key found.
[ "Parse", "a", "resource", "fragment", "into", "a", "schema", "field", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/schema.py#L164-L185
28,202
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/schema.py
SchemaField.from_api_repr
def from_api_repr(cls, api_repr): """Return a ``SchemaField`` object deserialized from a dictionary. Args: api_repr (Mapping[str, str]): The serialized representation of the SchemaField, such as what is output by :meth:`to_api_repr`. Returns: google.cloud.biquery.schema.SchemaField: The ``SchemaField`` object. """ # Handle optional properties with default values mode = api_repr.get("mode", "NULLABLE") description = api_repr.get("description") fields = api_repr.get("fields", ()) return cls( field_type=api_repr["type"].upper(), fields=[cls.from_api_repr(f) for f in fields], mode=mode.upper(), description=description, name=api_repr["name"], )
python
def from_api_repr(cls, api_repr): """Return a ``SchemaField`` object deserialized from a dictionary. Args: api_repr (Mapping[str, str]): The serialized representation of the SchemaField, such as what is output by :meth:`to_api_repr`. Returns: google.cloud.biquery.schema.SchemaField: The ``SchemaField`` object. """ # Handle optional properties with default values mode = api_repr.get("mode", "NULLABLE") description = api_repr.get("description") fields = api_repr.get("fields", ()) return cls( field_type=api_repr["type"].upper(), fields=[cls.from_api_repr(f) for f in fields], mode=mode.upper(), description=description, name=api_repr["name"], )
[ "def", "from_api_repr", "(", "cls", ",", "api_repr", ")", ":", "# Handle optional properties with default values", "mode", "=", "api_repr", ".", "get", "(", "\"mode\"", ",", "\"NULLABLE\"", ")", "description", "=", "api_repr", ".", "get", "(", "\"description\"", ")", "fields", "=", "api_repr", ".", "get", "(", "\"fields\"", ",", "(", ")", ")", "return", "cls", "(", "field_type", "=", "api_repr", "[", "\"type\"", "]", ".", "upper", "(", ")", ",", "fields", "=", "[", "cls", ".", "from_api_repr", "(", "f", ")", "for", "f", "in", "fields", "]", ",", "mode", "=", "mode", ".", "upper", "(", ")", ",", "description", "=", "description", ",", "name", "=", "api_repr", "[", "\"name\"", "]", ",", ")" ]
Return a ``SchemaField`` object deserialized from a dictionary. Args: api_repr (Mapping[str, str]): The serialized representation of the SchemaField, such as what is output by :meth:`to_api_repr`. Returns: google.cloud.biquery.schema.SchemaField: The ``SchemaField`` object.
[ "Return", "a", "SchemaField", "object", "deserialized", "from", "a", "dictionary", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/schema.py#L44-L66
28,203
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/schema.py
SchemaField.to_api_repr
def to_api_repr(self): """Return a dictionary representing this schema field. Returns: dict: A dictionary representing the SchemaField in a serialized form. """ # Put together the basic representation. See http://bit.ly/2hOAT5u. answer = { "mode": self.mode.upper(), "name": self.name, "type": self.field_type.upper(), "description": self.description, } # If this is a RECORD type, then sub-fields are also included, # add this to the serialized representation. if self.field_type.upper() == "RECORD": answer["fields"] = [f.to_api_repr() for f in self.fields] # Done; return the serialized dictionary. return answer
python
def to_api_repr(self): """Return a dictionary representing this schema field. Returns: dict: A dictionary representing the SchemaField in a serialized form. """ # Put together the basic representation. See http://bit.ly/2hOAT5u. answer = { "mode": self.mode.upper(), "name": self.name, "type": self.field_type.upper(), "description": self.description, } # If this is a RECORD type, then sub-fields are also included, # add this to the serialized representation. if self.field_type.upper() == "RECORD": answer["fields"] = [f.to_api_repr() for f in self.fields] # Done; return the serialized dictionary. return answer
[ "def", "to_api_repr", "(", "self", ")", ":", "# Put together the basic representation. See http://bit.ly/2hOAT5u.", "answer", "=", "{", "\"mode\"", ":", "self", ".", "mode", ".", "upper", "(", ")", ",", "\"name\"", ":", "self", ".", "name", ",", "\"type\"", ":", "self", ".", "field_type", ".", "upper", "(", ")", ",", "\"description\"", ":", "self", ".", "description", ",", "}", "# If this is a RECORD type, then sub-fields are also included,", "# add this to the serialized representation.", "if", "self", ".", "field_type", ".", "upper", "(", ")", "==", "\"RECORD\"", ":", "answer", "[", "\"fields\"", "]", "=", "[", "f", ".", "to_api_repr", "(", ")", "for", "f", "in", "self", ".", "fields", "]", "# Done; return the serialized dictionary.", "return", "answer" ]
Return a dictionary representing this schema field. Returns: dict: A dictionary representing the SchemaField in a serialized form.
[ "Return", "a", "dictionary", "representing", "this", "schema", "field", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/schema.py#L109-L130
28,204
googleapis/google-cloud-python
spanner/benchmark/ycsb.py
parse_options
def parse_options(): """Parses options.""" parser = argparse.ArgumentParser() parser.add_argument('command', help='The YCSB command.') parser.add_argument('benchmark', help='The YCSB benchmark.') parser.add_argument('-P', '--workload', action='store', dest='workload', default='', help='The path to a YCSB workload file.') parser.add_argument('-p', '--parameter', action='append', dest='parameters', default=[], help='The key=value pair of parameter.') parser.add_argument('-b', '--num_bucket', action='store', type=int, dest='num_bucket', default=1000, help='The number of buckets in output.') args = parser.parse_args() parameters = {} parameters['command'] = args.command parameters['num_bucket'] = args.num_bucket for parameter in args.parameters: parts = parameter.strip().split('=') parameters[parts[0]] = parts[1] with open(args.workload, 'r') as f: for line in f.readlines(): parts = line.split('=') key = parts[0].strip() if key in OPERATIONS: parameters[key] = parts[1].strip() return parameters
python
def parse_options(): """Parses options.""" parser = argparse.ArgumentParser() parser.add_argument('command', help='The YCSB command.') parser.add_argument('benchmark', help='The YCSB benchmark.') parser.add_argument('-P', '--workload', action='store', dest='workload', default='', help='The path to a YCSB workload file.') parser.add_argument('-p', '--parameter', action='append', dest='parameters', default=[], help='The key=value pair of parameter.') parser.add_argument('-b', '--num_bucket', action='store', type=int, dest='num_bucket', default=1000, help='The number of buckets in output.') args = parser.parse_args() parameters = {} parameters['command'] = args.command parameters['num_bucket'] = args.num_bucket for parameter in args.parameters: parts = parameter.strip().split('=') parameters[parts[0]] = parts[1] with open(args.workload, 'r') as f: for line in f.readlines(): parts = line.split('=') key = parts[0].strip() if key in OPERATIONS: parameters[key] = parts[1].strip() return parameters
[ "def", "parse_options", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'command'", ",", "help", "=", "'The YCSB command.'", ")", "parser", ".", "add_argument", "(", "'benchmark'", ",", "help", "=", "'The YCSB benchmark.'", ")", "parser", ".", "add_argument", "(", "'-P'", ",", "'--workload'", ",", "action", "=", "'store'", ",", "dest", "=", "'workload'", ",", "default", "=", "''", ",", "help", "=", "'The path to a YCSB workload file.'", ")", "parser", ".", "add_argument", "(", "'-p'", ",", "'--parameter'", ",", "action", "=", "'append'", ",", "dest", "=", "'parameters'", ",", "default", "=", "[", "]", ",", "help", "=", "'The key=value pair of parameter.'", ")", "parser", ".", "add_argument", "(", "'-b'", ",", "'--num_bucket'", ",", "action", "=", "'store'", ",", "type", "=", "int", ",", "dest", "=", "'num_bucket'", ",", "default", "=", "1000", ",", "help", "=", "'The number of buckets in output.'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "parameters", "=", "{", "}", "parameters", "[", "'command'", "]", "=", "args", ".", "command", "parameters", "[", "'num_bucket'", "]", "=", "args", ".", "num_bucket", "for", "parameter", "in", "args", ".", "parameters", ":", "parts", "=", "parameter", ".", "strip", "(", ")", ".", "split", "(", "'='", ")", "parameters", "[", "parts", "[", "0", "]", "]", "=", "parts", "[", "1", "]", "with", "open", "(", "args", ".", "workload", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "parts", "=", "line", ".", "split", "(", "'='", ")", "key", "=", "parts", "[", "0", "]", ".", "strip", "(", ")", "if", "key", "in", "OPERATIONS", ":", "parameters", "[", "key", "]", "=", "parts", "[", "1", "]", ".", "strip", "(", ")", "return", "parameters" ]
Parses options.
[ "Parses", "options", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/benchmark/ycsb.py#L51-L81
28,205
googleapis/google-cloud-python
spanner/benchmark/ycsb.py
load_keys
def load_keys(database, parameters): """Loads keys from database.""" keys = [] with database.snapshot() as snapshot: results = snapshot.execute_sql( 'SELECT u.id FROM %s u' % parameters['table']) for row in results: keys.append(row[0]) return keys
python
def load_keys(database, parameters): """Loads keys from database.""" keys = [] with database.snapshot() as snapshot: results = snapshot.execute_sql( 'SELECT u.id FROM %s u' % parameters['table']) for row in results: keys.append(row[0]) return keys
[ "def", "load_keys", "(", "database", ",", "parameters", ")", ":", "keys", "=", "[", "]", "with", "database", ".", "snapshot", "(", ")", "as", "snapshot", ":", "results", "=", "snapshot", ".", "execute_sql", "(", "'SELECT u.id FROM %s u'", "%", "parameters", "[", "'table'", "]", ")", "for", "row", "in", "results", ":", "keys", ".", "append", "(", "row", "[", "0", "]", ")", "return", "keys" ]
Loads keys from database.
[ "Loads", "keys", "from", "database", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/benchmark/ycsb.py#L96-L106
28,206
googleapis/google-cloud-python
spanner/benchmark/ycsb.py
read
def read(database, table, key): """Does a single read operation.""" with database.snapshot() as snapshot: result = snapshot.execute_sql('SELECT u.* FROM %s u WHERE u.id="%s"' % (table, key)) for row in result: key = row[0] for i in range(NUM_FIELD): field = row[i + 1]
python
def read(database, table, key): """Does a single read operation.""" with database.snapshot() as snapshot: result = snapshot.execute_sql('SELECT u.* FROM %s u WHERE u.id="%s"' % (table, key)) for row in result: key = row[0] for i in range(NUM_FIELD): field = row[i + 1]
[ "def", "read", "(", "database", ",", "table", ",", "key", ")", ":", "with", "database", ".", "snapshot", "(", ")", "as", "snapshot", ":", "result", "=", "snapshot", ".", "execute_sql", "(", "'SELECT u.* FROM %s u WHERE u.id=\"%s\"'", "%", "(", "table", ",", "key", ")", ")", "for", "row", "in", "result", ":", "key", "=", "row", "[", "0", "]", "for", "i", "in", "range", "(", "NUM_FIELD", ")", ":", "field", "=", "row", "[", "i", "+", "1", "]" ]
Does a single read operation.
[ "Does", "a", "single", "read", "operation", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/benchmark/ycsb.py#L109-L117
28,207
googleapis/google-cloud-python
spanner/benchmark/ycsb.py
update
def update(database, table, key): """Does a single update operation.""" field = random.randrange(10) value = ''.join(random.choice(string.printable) for i in range(100)) with database.batch() as batch: batch.update(table=table, columns=('id', 'field%d' % field), values=[(key, value)])
python
def update(database, table, key): """Does a single update operation.""" field = random.randrange(10) value = ''.join(random.choice(string.printable) for i in range(100)) with database.batch() as batch: batch.update(table=table, columns=('id', 'field%d' % field), values=[(key, value)])
[ "def", "update", "(", "database", ",", "table", ",", "key", ")", ":", "field", "=", "random", ".", "randrange", "(", "10", ")", "value", "=", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "printable", ")", "for", "i", "in", "range", "(", "100", ")", ")", "with", "database", ".", "batch", "(", ")", "as", "batch", ":", "batch", ".", "update", "(", "table", "=", "table", ",", "columns", "=", "(", "'id'", ",", "'field%d'", "%", "field", ")", ",", "values", "=", "[", "(", "key", ",", "value", ")", "]", ")" ]
Does a single update operation.
[ "Does", "a", "single", "update", "operation", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/benchmark/ycsb.py#L120-L126
28,208
googleapis/google-cloud-python
spanner/benchmark/ycsb.py
do_operation
def do_operation(database, keys, table, operation, latencies_ms): """Does a single operation and records latency.""" key = random.choice(keys) start = timeit.default_timer() if operation == 'read': read(database, table, key) elif operation == 'update': update(database, table, key) else: raise ValueError('Unknown operation: %s' % operation) end = timeit.default_timer() latencies_ms[operation].append((end - start) * 1000)
python
def do_operation(database, keys, table, operation, latencies_ms): """Does a single operation and records latency.""" key = random.choice(keys) start = timeit.default_timer() if operation == 'read': read(database, table, key) elif operation == 'update': update(database, table, key) else: raise ValueError('Unknown operation: %s' % operation) end = timeit.default_timer() latencies_ms[operation].append((end - start) * 1000)
[ "def", "do_operation", "(", "database", ",", "keys", ",", "table", ",", "operation", ",", "latencies_ms", ")", ":", "key", "=", "random", ".", "choice", "(", "keys", ")", "start", "=", "timeit", ".", "default_timer", "(", ")", "if", "operation", "==", "'read'", ":", "read", "(", "database", ",", "table", ",", "key", ")", "elif", "operation", "==", "'update'", ":", "update", "(", "database", ",", "table", ",", "key", ")", "else", ":", "raise", "ValueError", "(", "'Unknown operation: %s'", "%", "operation", ")", "end", "=", "timeit", ".", "default_timer", "(", ")", "latencies_ms", "[", "operation", "]", ".", "append", "(", "(", "end", "-", "start", ")", "*", "1000", ")" ]
Does a single operation and records latency.
[ "Does", "a", "single", "operation", "and", "records", "latency", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/benchmark/ycsb.py#L129-L140
28,209
googleapis/google-cloud-python
spanner/benchmark/ycsb.py
aggregate_metrics
def aggregate_metrics(latencies_ms, duration_ms, num_bucket): """Aggregates metrics.""" overall_op_count = 0 op_counts = {operation : len(latency) for operation, latency in latencies_ms.iteritems()} overall_op_count = sum([op_count for op_count in op_counts.itervalues()]) print('[OVERALL], RunTime(ms), %f' % duration_ms) print('[OVERALL], Throughput(ops/sec), %f' % (float(overall_op_count) / duration_ms * 1000.0)) for operation in op_counts.keys(): operation_upper = operation.upper() print('[%s], Operations, %d' % (operation_upper, op_counts[operation])) print('[%s], AverageLatency(us), %f' % ( operation_upper, numpy.average(latencies_ms[operation]) * 1000.0)) print('[%s], LatencyVariance(us), %f' % ( operation_upper, numpy.var(latencies_ms[operation]) * 1000.0)) print('[%s], MinLatency(us), %f' % ( operation_upper, min(latencies_ms[operation]) * 1000.0)) print('[%s], MaxLatency(us), %f' % ( operation_upper, max(latencies_ms[operation]) * 1000.0)) print('[%s], 95thPercentileLatency(us), %f' % ( operation_upper, numpy.percentile(latencies_ms[operation], 95.0) * 1000.0)) print('[%s], 99thPercentileLatency(us), %f' % ( operation_upper, numpy.percentile(latencies_ms[operation], 99.0) * 1000.0)) print('[%s], 99.9thPercentileLatency(us), %f' % ( operation_upper, numpy.percentile(latencies_ms[operation], 99.9) * 1000.0)) print('[%s], Return=OK, %d' % (operation_upper, op_counts[operation])) latency_array = numpy.array(latencies_ms[operation]) for j in range(num_bucket): print('[%s], %d, %d' % ( operation_upper, j, ((j <= latency_array) & (latency_array < (j + 1))).sum())) print('[%s], >%d, %d' % (operation_upper, num_bucket, (num_bucket <= latency_array).sum()))
python
def aggregate_metrics(latencies_ms, duration_ms, num_bucket): """Aggregates metrics.""" overall_op_count = 0 op_counts = {operation : len(latency) for operation, latency in latencies_ms.iteritems()} overall_op_count = sum([op_count for op_count in op_counts.itervalues()]) print('[OVERALL], RunTime(ms), %f' % duration_ms) print('[OVERALL], Throughput(ops/sec), %f' % (float(overall_op_count) / duration_ms * 1000.0)) for operation in op_counts.keys(): operation_upper = operation.upper() print('[%s], Operations, %d' % (operation_upper, op_counts[operation])) print('[%s], AverageLatency(us), %f' % ( operation_upper, numpy.average(latencies_ms[operation]) * 1000.0)) print('[%s], LatencyVariance(us), %f' % ( operation_upper, numpy.var(latencies_ms[operation]) * 1000.0)) print('[%s], MinLatency(us), %f' % ( operation_upper, min(latencies_ms[operation]) * 1000.0)) print('[%s], MaxLatency(us), %f' % ( operation_upper, max(latencies_ms[operation]) * 1000.0)) print('[%s], 95thPercentileLatency(us), %f' % ( operation_upper, numpy.percentile(latencies_ms[operation], 95.0) * 1000.0)) print('[%s], 99thPercentileLatency(us), %f' % ( operation_upper, numpy.percentile(latencies_ms[operation], 99.0) * 1000.0)) print('[%s], 99.9thPercentileLatency(us), %f' % ( operation_upper, numpy.percentile(latencies_ms[operation], 99.9) * 1000.0)) print('[%s], Return=OK, %d' % (operation_upper, op_counts[operation])) latency_array = numpy.array(latencies_ms[operation]) for j in range(num_bucket): print('[%s], %d, %d' % ( operation_upper, j, ((j <= latency_array) & (latency_array < (j + 1))).sum())) print('[%s], >%d, %d' % (operation_upper, num_bucket, (num_bucket <= latency_array).sum()))
[ "def", "aggregate_metrics", "(", "latencies_ms", ",", "duration_ms", ",", "num_bucket", ")", ":", "overall_op_count", "=", "0", "op_counts", "=", "{", "operation", ":", "len", "(", "latency", ")", "for", "operation", ",", "latency", "in", "latencies_ms", ".", "iteritems", "(", ")", "}", "overall_op_count", "=", "sum", "(", "[", "op_count", "for", "op_count", "in", "op_counts", ".", "itervalues", "(", ")", "]", ")", "print", "(", "'[OVERALL], RunTime(ms), %f'", "%", "duration_ms", ")", "print", "(", "'[OVERALL], Throughput(ops/sec), %f'", "%", "(", "float", "(", "overall_op_count", ")", "/", "duration_ms", "*", "1000.0", ")", ")", "for", "operation", "in", "op_counts", ".", "keys", "(", ")", ":", "operation_upper", "=", "operation", ".", "upper", "(", ")", "print", "(", "'[%s], Operations, %d'", "%", "(", "operation_upper", ",", "op_counts", "[", "operation", "]", ")", ")", "print", "(", "'[%s], AverageLatency(us), %f'", "%", "(", "operation_upper", ",", "numpy", ".", "average", "(", "latencies_ms", "[", "operation", "]", ")", "*", "1000.0", ")", ")", "print", "(", "'[%s], LatencyVariance(us), %f'", "%", "(", "operation_upper", ",", "numpy", ".", "var", "(", "latencies_ms", "[", "operation", "]", ")", "*", "1000.0", ")", ")", "print", "(", "'[%s], MinLatency(us), %f'", "%", "(", "operation_upper", ",", "min", "(", "latencies_ms", "[", "operation", "]", ")", "*", "1000.0", ")", ")", "print", "(", "'[%s], MaxLatency(us), %f'", "%", "(", "operation_upper", ",", "max", "(", "latencies_ms", "[", "operation", "]", ")", "*", "1000.0", ")", ")", "print", "(", "'[%s], 95thPercentileLatency(us), %f'", "%", "(", "operation_upper", ",", "numpy", ".", "percentile", "(", "latencies_ms", "[", "operation", "]", ",", "95.0", ")", "*", "1000.0", ")", ")", "print", "(", "'[%s], 99thPercentileLatency(us), %f'", "%", "(", "operation_upper", ",", "numpy", ".", "percentile", "(", "latencies_ms", "[", "operation", "]", ",", "99.0", ")", "*", "1000.0", ")", ")", "print", "(", "'[%s], 99.9thPercentileLatency(us), %f'", "%", "(", "operation_upper", ",", "numpy", ".", "percentile", "(", "latencies_ms", "[", "operation", "]", ",", "99.9", ")", "*", "1000.0", ")", ")", "print", "(", "'[%s], Return=OK, %d'", "%", "(", "operation_upper", ",", "op_counts", "[", "operation", "]", ")", ")", "latency_array", "=", "numpy", ".", "array", "(", "latencies_ms", "[", "operation", "]", ")", "for", "j", "in", "range", "(", "num_bucket", ")", ":", "print", "(", "'[%s], %d, %d'", "%", "(", "operation_upper", ",", "j", ",", "(", "(", "j", "<=", "latency_array", ")", "&", "(", "latency_array", "<", "(", "j", "+", "1", ")", ")", ")", ".", "sum", "(", ")", ")", ")", "print", "(", "'[%s], >%d, %d'", "%", "(", "operation_upper", ",", "num_bucket", ",", "(", "num_bucket", "<=", "latency_array", ")", ".", "sum", "(", ")", ")", ")" ]
Aggregates metrics.
[ "Aggregates", "metrics", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/benchmark/ycsb.py#L143-L181
28,210
googleapis/google-cloud-python
spanner/benchmark/ycsb.py
run_workload
def run_workload(database, keys, parameters): """Runs workload against the database.""" total_weight = 0.0 weights = [] operations = [] latencies_ms = {} for operation in OPERATIONS: weight = float(parameters[operation]) if weight <= 0.0: continue total_weight += weight op_code = operation.split('proportion')[0] operations.append(op_code) weights.append(total_weight) latencies_ms[op_code] = [] threads = [] start = timeit.default_timer() for i in range(int(parameters['num_worker'])): thread = WorkloadThread(database, keys, parameters, total_weight, weights, operations) thread.start() threads.append(thread) for thread in threads: thread.join() end = timeit.default_timer() for thread in threads: thread_latencies_ms = thread.latencies_ms() for key in latencies_ms.keys(): latencies_ms[key].extend(thread_latencies_ms[key]) aggregate_metrics(latencies_ms, (end - start) * 1000.0, parameters['num_bucket'])
python
def run_workload(database, keys, parameters): """Runs workload against the database.""" total_weight = 0.0 weights = [] operations = [] latencies_ms = {} for operation in OPERATIONS: weight = float(parameters[operation]) if weight <= 0.0: continue total_weight += weight op_code = operation.split('proportion')[0] operations.append(op_code) weights.append(total_weight) latencies_ms[op_code] = [] threads = [] start = timeit.default_timer() for i in range(int(parameters['num_worker'])): thread = WorkloadThread(database, keys, parameters, total_weight, weights, operations) thread.start() threads.append(thread) for thread in threads: thread.join() end = timeit.default_timer() for thread in threads: thread_latencies_ms = thread.latencies_ms() for key in latencies_ms.keys(): latencies_ms[key].extend(thread_latencies_ms[key]) aggregate_metrics(latencies_ms, (end - start) * 1000.0, parameters['num_bucket'])
[ "def", "run_workload", "(", "database", ",", "keys", ",", "parameters", ")", ":", "total_weight", "=", "0.0", "weights", "=", "[", "]", "operations", "=", "[", "]", "latencies_ms", "=", "{", "}", "for", "operation", "in", "OPERATIONS", ":", "weight", "=", "float", "(", "parameters", "[", "operation", "]", ")", "if", "weight", "<=", "0.0", ":", "continue", "total_weight", "+=", "weight", "op_code", "=", "operation", ".", "split", "(", "'proportion'", ")", "[", "0", "]", "operations", ".", "append", "(", "op_code", ")", "weights", ".", "append", "(", "total_weight", ")", "latencies_ms", "[", "op_code", "]", "=", "[", "]", "threads", "=", "[", "]", "start", "=", "timeit", ".", "default_timer", "(", ")", "for", "i", "in", "range", "(", "int", "(", "parameters", "[", "'num_worker'", "]", ")", ")", ":", "thread", "=", "WorkloadThread", "(", "database", ",", "keys", ",", "parameters", ",", "total_weight", ",", "weights", ",", "operations", ")", "thread", ".", "start", "(", ")", "threads", ".", "append", "(", "thread", ")", "for", "thread", "in", "threads", ":", "thread", ".", "join", "(", ")", "end", "=", "timeit", ".", "default_timer", "(", ")", "for", "thread", "in", "threads", ":", "thread_latencies_ms", "=", "thread", ".", "latencies_ms", "(", ")", "for", "key", "in", "latencies_ms", ".", "keys", "(", ")", ":", "latencies_ms", "[", "key", "]", ".", "extend", "(", "thread_latencies_ms", "[", "key", "]", ")", "aggregate_metrics", "(", "latencies_ms", ",", "(", "end", "-", "start", ")", "*", "1000.0", ",", "parameters", "[", "'num_bucket'", "]", ")" ]
Runs workload against the database.
[ "Runs", "workload", "against", "the", "database", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/benchmark/ycsb.py#L219-L253
28,211
googleapis/google-cloud-python
spanner/benchmark/ycsb.py
WorkloadThread.run
def run(self): """Run a single thread of the workload.""" i = 0 operation_count = int(self._parameters['operationcount']) while i < operation_count: i += 1 weight = random.uniform(0, self._total_weight) for j in range(len(self._weights)): if weight <= self._weights[j]: do_operation(self._database, self._keys, self._parameters['table'], self._operations[j], self._latencies_ms) break
python
def run(self): """Run a single thread of the workload.""" i = 0 operation_count = int(self._parameters['operationcount']) while i < operation_count: i += 1 weight = random.uniform(0, self._total_weight) for j in range(len(self._weights)): if weight <= self._weights[j]: do_operation(self._database, self._keys, self._parameters['table'], self._operations[j], self._latencies_ms) break
[ "def", "run", "(", "self", ")", ":", "i", "=", "0", "operation_count", "=", "int", "(", "self", ".", "_parameters", "[", "'operationcount'", "]", ")", "while", "i", "<", "operation_count", ":", "i", "+=", "1", "weight", "=", "random", ".", "uniform", "(", "0", ",", "self", ".", "_total_weight", ")", "for", "j", "in", "range", "(", "len", "(", "self", ".", "_weights", ")", ")", ":", "if", "weight", "<=", "self", ".", "_weights", "[", "j", "]", ":", "do_operation", "(", "self", ".", "_database", ",", "self", ".", "_keys", ",", "self", ".", "_parameters", "[", "'table'", "]", ",", "self", ".", "_operations", "[", "j", "]", ",", "self", ".", "_latencies_ms", ")", "break" ]
Run a single thread of the workload.
[ "Run", "a", "single", "thread", "of", "the", "workload", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/benchmark/ycsb.py#L200-L212
28,212
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/_gapic.py
add_methods
def add_methods(source_class, blacklist=()): """Add wrapped versions of the `api` member's methods to the class. Any methods passed in `blacklist` are not added. Additionally, any methods explicitly defined on the wrapped class are not added. """ def wrap(wrapped_fx): """Wrap a GAPIC method; preserve its name and docstring.""" # If this is a static or class method, then we need to *not* # send self as the first argument. # # Similarly, for instance methods, we need to send self.api rather # than self, since that is where the actual methods were declared. instance_method = True # If this is a bound method it's a classmethod. self = getattr(wrapped_fx, "__self__", None) if issubclass(type(self), type): instance_method = False # Okay, we have figured out what kind of method this is; send # down the correct wrapper function. if instance_method: fx = lambda self, *a, **kw: wrapped_fx(self.api, *a, **kw) # noqa return functools.wraps(wrapped_fx)(fx) fx = lambda *a, **kw: wrapped_fx(*a, **kw) # noqa return staticmethod(functools.wraps(wrapped_fx)(fx)) def actual_decorator(cls): # Reflectively iterate over most of the methods on the source class # (the GAPIC) and make wrapped versions available on this client. for name in dir(source_class): # Ignore all private and magic methods. if name.startswith("_"): continue # Ignore anything on our blacklist. if name in blacklist: continue # Retrieve the attribute, and ignore it if it is not callable. attr = getattr(source_class, name) if not callable(attr): continue # Add a wrapper method to this object. fx = wrap(getattr(source_class, name)) setattr(cls, name, fx) # Return the augmented class. return cls # Simply return the actual decorator; this is returned from this method # and actually used to decorate the class. return actual_decorator
python
def add_methods(source_class, blacklist=()): """Add wrapped versions of the `api` member's methods to the class. Any methods passed in `blacklist` are not added. Additionally, any methods explicitly defined on the wrapped class are not added. """ def wrap(wrapped_fx): """Wrap a GAPIC method; preserve its name and docstring.""" # If this is a static or class method, then we need to *not* # send self as the first argument. # # Similarly, for instance methods, we need to send self.api rather # than self, since that is where the actual methods were declared. instance_method = True # If this is a bound method it's a classmethod. self = getattr(wrapped_fx, "__self__", None) if issubclass(type(self), type): instance_method = False # Okay, we have figured out what kind of method this is; send # down the correct wrapper function. if instance_method: fx = lambda self, *a, **kw: wrapped_fx(self.api, *a, **kw) # noqa return functools.wraps(wrapped_fx)(fx) fx = lambda *a, **kw: wrapped_fx(*a, **kw) # noqa return staticmethod(functools.wraps(wrapped_fx)(fx)) def actual_decorator(cls): # Reflectively iterate over most of the methods on the source class # (the GAPIC) and make wrapped versions available on this client. for name in dir(source_class): # Ignore all private and magic methods. if name.startswith("_"): continue # Ignore anything on our blacklist. if name in blacklist: continue # Retrieve the attribute, and ignore it if it is not callable. attr = getattr(source_class, name) if not callable(attr): continue # Add a wrapper method to this object. fx = wrap(getattr(source_class, name)) setattr(cls, name, fx) # Return the augmented class. return cls # Simply return the actual decorator; this is returned from this method # and actually used to decorate the class. return actual_decorator
[ "def", "add_methods", "(", "source_class", ",", "blacklist", "=", "(", ")", ")", ":", "def", "wrap", "(", "wrapped_fx", ")", ":", "\"\"\"Wrap a GAPIC method; preserve its name and docstring.\"\"\"", "# If this is a static or class method, then we need to *not*", "# send self as the first argument.", "#", "# Similarly, for instance methods, we need to send self.api rather", "# than self, since that is where the actual methods were declared.", "instance_method", "=", "True", "# If this is a bound method it's a classmethod.", "self", "=", "getattr", "(", "wrapped_fx", ",", "\"__self__\"", ",", "None", ")", "if", "issubclass", "(", "type", "(", "self", ")", ",", "type", ")", ":", "instance_method", "=", "False", "# Okay, we have figured out what kind of method this is; send", "# down the correct wrapper function.", "if", "instance_method", ":", "fx", "=", "lambda", "self", ",", "*", "a", ",", "*", "*", "kw", ":", "wrapped_fx", "(", "self", ".", "api", ",", "*", "a", ",", "*", "*", "kw", ")", "# noqa", "return", "functools", ".", "wraps", "(", "wrapped_fx", ")", "(", "fx", ")", "fx", "=", "lambda", "*", "a", ",", "*", "*", "kw", ":", "wrapped_fx", "(", "*", "a", ",", "*", "*", "kw", ")", "# noqa", "return", "staticmethod", "(", "functools", ".", "wraps", "(", "wrapped_fx", ")", "(", "fx", ")", ")", "def", "actual_decorator", "(", "cls", ")", ":", "# Reflectively iterate over most of the methods on the source class", "# (the GAPIC) and make wrapped versions available on this client.", "for", "name", "in", "dir", "(", "source_class", ")", ":", "# Ignore all private and magic methods.", "if", "name", ".", "startswith", "(", "\"_\"", ")", ":", "continue", "# Ignore anything on our blacklist.", "if", "name", "in", "blacklist", ":", "continue", "# Retrieve the attribute, and ignore it if it is not callable.", "attr", "=", "getattr", "(", "source_class", ",", "name", ")", "if", "not", "callable", "(", "attr", ")", ":", "continue", "# Add a wrapper method to this object.", "fx", "=", "wrap", "(", "getattr", "(", "source_class", ",", "name", ")", ")", "setattr", "(", "cls", ",", "name", ",", "fx", ")", "# Return the augmented class.", "return", "cls", "# Simply return the actual decorator; this is returned from this method", "# and actually used to decorate the class.", "return", "actual_decorator" ]
Add wrapped versions of the `api` member's methods to the class. Any methods passed in `blacklist` are not added. Additionally, any methods explicitly defined on the wrapped class are not added.
[ "Add", "wrapped", "versions", "of", "the", "api", "member", "s", "methods", "to", "the", "class", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/_gapic.py#L20-L77
28,213
googleapis/google-cloud-python
vision/google/cloud/vision_v1/gapic/product_search_client.py
ProductSearchClient.create_product
def create_product( self, parent, product, product_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates and returns a new product resource. Possible errors: - Returns INVALID\_ARGUMENT if display\_name is missing or longer than 4096 characters. - Returns INVALID\_ARGUMENT if description is longer than 4096 characters. - Returns INVALID\_ARGUMENT if product\_category is missing or invalid. Example: >>> from google.cloud import vision_v1 >>> >>> client = vision_v1.ProductSearchClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> >>> # TODO: Initialize `product`: >>> product = {} >>> >>> response = client.create_product(parent, product) Args: parent (str): The project in which the Product should be created. Format is ``projects/PROJECT_ID/locations/LOC_ID``. product (Union[dict, ~google.cloud.vision_v1.types.Product]): The product to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1.types.Product` product_id (str): A user-supplied resource id for this Product. If set, the server will attempt to use this value as the resource id. If it is already in use, an error is returned with code ALREADY\_EXISTS. Must be at most 128 characters long. It cannot contain the character ``/``. 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.vision_v1.types.Product` 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_product" not in self._inner_api_calls: self._inner_api_calls[ "create_product" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_product, default_retry=self._method_configs["CreateProduct"].retry, default_timeout=self._method_configs["CreateProduct"].timeout, client_info=self._client_info, ) request = product_search_service_pb2.CreateProductRequest( parent=parent, product=product, product_id=product_id ) 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_product"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_product( self, parent, product, product_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates and returns a new product resource. Possible errors: - Returns INVALID\_ARGUMENT if display\_name is missing or longer than 4096 characters. - Returns INVALID\_ARGUMENT if description is longer than 4096 characters. - Returns INVALID\_ARGUMENT if product\_category is missing or invalid. Example: >>> from google.cloud import vision_v1 >>> >>> client = vision_v1.ProductSearchClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> >>> # TODO: Initialize `product`: >>> product = {} >>> >>> response = client.create_product(parent, product) Args: parent (str): The project in which the Product should be created. Format is ``projects/PROJECT_ID/locations/LOC_ID``. product (Union[dict, ~google.cloud.vision_v1.types.Product]): The product to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1.types.Product` product_id (str): A user-supplied resource id for this Product. If set, the server will attempt to use this value as the resource id. If it is already in use, an error is returned with code ALREADY\_EXISTS. Must be at most 128 characters long. It cannot contain the character ``/``. 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.vision_v1.types.Product` 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_product" not in self._inner_api_calls: self._inner_api_calls[ "create_product" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_product, default_retry=self._method_configs["CreateProduct"].retry, default_timeout=self._method_configs["CreateProduct"].timeout, client_info=self._client_info, ) request = product_search_service_pb2.CreateProductRequest( parent=parent, product=product, product_id=product_id ) 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_product"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_product", "(", "self", ",", "parent", ",", "product", ",", "product_id", "=", "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_product\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_product\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_product", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateProduct\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateProduct\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "product_search_service_pb2", ".", "CreateProductRequest", "(", "parent", "=", "parent", ",", "product", "=", "product", ",", "product_id", "=", "product_id", ")", "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_product\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates and returns a new product resource. Possible errors: - Returns INVALID\_ARGUMENT if display\_name is missing or longer than 4096 characters. - Returns INVALID\_ARGUMENT if description is longer than 4096 characters. - Returns INVALID\_ARGUMENT if product\_category is missing or invalid. Example: >>> from google.cloud import vision_v1 >>> >>> client = vision_v1.ProductSearchClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> >>> # TODO: Initialize `product`: >>> product = {} >>> >>> response = client.create_product(parent, product) Args: parent (str): The project in which the Product should be created. Format is ``projects/PROJECT_ID/locations/LOC_ID``. product (Union[dict, ~google.cloud.vision_v1.types.Product]): The product to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1.types.Product` product_id (str): A user-supplied resource id for this Product. If set, the server will attempt to use this value as the resource id. If it is already in use, an error is returned with code ALREADY\_EXISTS. Must be at most 128 characters long. It cannot contain the character ``/``. 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.vision_v1.types.Product` 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", "and", "returns", "a", "new", "product", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/vision/google/cloud/vision_v1/gapic/product_search_client.py#L230-L322
28,214
googleapis/google-cloud-python
vision/google/cloud/vision_v1/gapic/product_search_client.py
ProductSearchClient.update_product
def update_product( self, product, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Makes changes to a Product resource. Only the ``display_name``, ``description``, and ``labels`` fields can be updated right now. If labels are updated, the change will not be reflected in queries until the next index time. Possible errors: - Returns NOT\_FOUND if the Product does not exist. - Returns INVALID\_ARGUMENT if display\_name is present in update\_mask but is missing from the request or longer than 4096 characters. - Returns INVALID\_ARGUMENT if description is present in update\_mask but is longer than 4096 characters. - Returns INVALID\_ARGUMENT if product\_category is present in update\_mask. Example: >>> from google.cloud import vision_v1 >>> >>> client = vision_v1.ProductSearchClient() >>> >>> # TODO: Initialize `product`: >>> product = {} >>> >>> response = client.update_product(product) Args: product (Union[dict, ~google.cloud.vision_v1.types.Product]): The Product resource which replaces the one on the server. product.name is immutable. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1.types.Product` update_mask (Union[dict, ~google.cloud.vision_v1.types.FieldMask]): The ``FieldMask`` that specifies which fields to update. If update\_mask isn't specified, all mutable fields are to be updated. Valid mask paths include ``product_labels``, ``display_name``, and ``description``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_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.vision_v1.types.Product` 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_product" not in self._inner_api_calls: self._inner_api_calls[ "update_product" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_product, default_retry=self._method_configs["UpdateProduct"].retry, default_timeout=self._method_configs["UpdateProduct"].timeout, client_info=self._client_info, ) request = product_search_service_pb2.UpdateProductRequest( product=product, update_mask=update_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("product.name", product.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_product"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def update_product( self, product, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Makes changes to a Product resource. Only the ``display_name``, ``description``, and ``labels`` fields can be updated right now. If labels are updated, the change will not be reflected in queries until the next index time. Possible errors: - Returns NOT\_FOUND if the Product does not exist. - Returns INVALID\_ARGUMENT if display\_name is present in update\_mask but is missing from the request or longer than 4096 characters. - Returns INVALID\_ARGUMENT if description is present in update\_mask but is longer than 4096 characters. - Returns INVALID\_ARGUMENT if product\_category is present in update\_mask. Example: >>> from google.cloud import vision_v1 >>> >>> client = vision_v1.ProductSearchClient() >>> >>> # TODO: Initialize `product`: >>> product = {} >>> >>> response = client.update_product(product) Args: product (Union[dict, ~google.cloud.vision_v1.types.Product]): The Product resource which replaces the one on the server. product.name is immutable. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1.types.Product` update_mask (Union[dict, ~google.cloud.vision_v1.types.FieldMask]): The ``FieldMask`` that specifies which fields to update. If update\_mask isn't specified, all mutable fields are to be updated. Valid mask paths include ``product_labels``, ``display_name``, and ``description``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_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.vision_v1.types.Product` 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_product" not in self._inner_api_calls: self._inner_api_calls[ "update_product" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_product, default_retry=self._method_configs["UpdateProduct"].retry, default_timeout=self._method_configs["UpdateProduct"].timeout, client_info=self._client_info, ) request = product_search_service_pb2.UpdateProductRequest( product=product, update_mask=update_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("product.name", product.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_product"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "update_product", "(", "self", ",", "product", ",", "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_product\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"update_product\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "update_product", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"UpdateProduct\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"UpdateProduct\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "product_search_service_pb2", ".", "UpdateProductRequest", "(", "product", "=", "product", ",", "update_mask", "=", "update_mask", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"product.name\"", ",", "product", ".", "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_product\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Makes changes to a Product resource. Only the ``display_name``, ``description``, and ``labels`` fields can be updated right now. If labels are updated, the change will not be reflected in queries until the next index time. Possible errors: - Returns NOT\_FOUND if the Product does not exist. - Returns INVALID\_ARGUMENT if display\_name is present in update\_mask but is missing from the request or longer than 4096 characters. - Returns INVALID\_ARGUMENT if description is present in update\_mask but is longer than 4096 characters. - Returns INVALID\_ARGUMENT if product\_category is present in update\_mask. Example: >>> from google.cloud import vision_v1 >>> >>> client = vision_v1.ProductSearchClient() >>> >>> # TODO: Initialize `product`: >>> product = {} >>> >>> response = client.update_product(product) Args: product (Union[dict, ~google.cloud.vision_v1.types.Product]): The Product resource which replaces the one on the server. product.name is immutable. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1.types.Product` update_mask (Union[dict, ~google.cloud.vision_v1.types.FieldMask]): The ``FieldMask`` that specifies which fields to update. If update\_mask isn't specified, all mutable fields are to be updated. Valid mask paths include ``product_labels``, ``display_name``, and ``description``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_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.vision_v1.types.Product` 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.
[ "Makes", "changes", "to", "a", "Product", "resource", ".", "Only", "the", "display_name", "description", "and", "labels", "fields", "can", "be", "updated", "right", "now", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/vision/google/cloud/vision_v1/gapic/product_search_client.py#L509-L604
28,215
googleapis/google-cloud-python
datastore/google/cloud/datastore/batch.py
_assign_entity_to_pb
def _assign_entity_to_pb(entity_pb, entity): """Copy ``entity`` into ``entity_pb``. Helper method for ``Batch.put``. :type entity_pb: :class:`.entity_pb2.Entity` :param entity_pb: The entity owned by a mutation. :type entity: :class:`google.cloud.datastore.entity.Entity` :param entity: The entity being updated within the batch / transaction. """ bare_entity_pb = helpers.entity_to_protobuf(entity) bare_entity_pb.key.CopyFrom(bare_entity_pb.key) entity_pb.CopyFrom(bare_entity_pb)
python
def _assign_entity_to_pb(entity_pb, entity): """Copy ``entity`` into ``entity_pb``. Helper method for ``Batch.put``. :type entity_pb: :class:`.entity_pb2.Entity` :param entity_pb: The entity owned by a mutation. :type entity: :class:`google.cloud.datastore.entity.Entity` :param entity: The entity being updated within the batch / transaction. """ bare_entity_pb = helpers.entity_to_protobuf(entity) bare_entity_pb.key.CopyFrom(bare_entity_pb.key) entity_pb.CopyFrom(bare_entity_pb)
[ "def", "_assign_entity_to_pb", "(", "entity_pb", ",", "entity", ")", ":", "bare_entity_pb", "=", "helpers", ".", "entity_to_protobuf", "(", "entity", ")", "bare_entity_pb", ".", "key", ".", "CopyFrom", "(", "bare_entity_pb", ".", "key", ")", "entity_pb", ".", "CopyFrom", "(", "bare_entity_pb", ")" ]
Copy ``entity`` into ``entity_pb``. Helper method for ``Batch.put``. :type entity_pb: :class:`.entity_pb2.Entity` :param entity_pb: The entity owned by a mutation. :type entity: :class:`google.cloud.datastore.entity.Entity` :param entity: The entity being updated within the batch / transaction.
[ "Copy", "entity", "into", "entity_pb", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/batch.py#L309-L322
28,216
googleapis/google-cloud-python
datastore/google/cloud/datastore/batch.py
_parse_commit_response
def _parse_commit_response(commit_response_pb): """Extract response data from a commit response. :type commit_response_pb: :class:`.datastore_pb2.CommitResponse` :param commit_response_pb: The protobuf response from a commit request. :rtype: tuple :returns: The pair of the number of index updates and a list of :class:`.entity_pb2.Key` for each incomplete key that was completed in the commit. """ mut_results = commit_response_pb.mutation_results index_updates = commit_response_pb.index_updates completed_keys = [ mut_result.key for mut_result in mut_results if mut_result.HasField("key") ] # Message field (Key) return index_updates, completed_keys
python
def _parse_commit_response(commit_response_pb): """Extract response data from a commit response. :type commit_response_pb: :class:`.datastore_pb2.CommitResponse` :param commit_response_pb: The protobuf response from a commit request. :rtype: tuple :returns: The pair of the number of index updates and a list of :class:`.entity_pb2.Key` for each incomplete key that was completed in the commit. """ mut_results = commit_response_pb.mutation_results index_updates = commit_response_pb.index_updates completed_keys = [ mut_result.key for mut_result in mut_results if mut_result.HasField("key") ] # Message field (Key) return index_updates, completed_keys
[ "def", "_parse_commit_response", "(", "commit_response_pb", ")", ":", "mut_results", "=", "commit_response_pb", ".", "mutation_results", "index_updates", "=", "commit_response_pb", ".", "index_updates", "completed_keys", "=", "[", "mut_result", ".", "key", "for", "mut_result", "in", "mut_results", "if", "mut_result", ".", "HasField", "(", "\"key\"", ")", "]", "# Message field (Key)", "return", "index_updates", ",", "completed_keys" ]
Extract response data from a commit response. :type commit_response_pb: :class:`.datastore_pb2.CommitResponse` :param commit_response_pb: The protobuf response from a commit request. :rtype: tuple :returns: The pair of the number of index updates and a list of :class:`.entity_pb2.Key` for each incomplete key that was completed in the commit.
[ "Extract", "response", "data", "from", "a", "commit", "response", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/batch.py#L325-L341
28,217
googleapis/google-cloud-python
datastore/google/cloud/datastore/batch.py
Batch._add_partial_key_entity_pb
def _add_partial_key_entity_pb(self): """Adds a new mutation for an entity with a partial key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created entity protobuf that will be updated and sent with a commit. """ new_mutation = _datastore_pb2.Mutation() self._mutations.append(new_mutation) return new_mutation.insert
python
def _add_partial_key_entity_pb(self): """Adds a new mutation for an entity with a partial key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created entity protobuf that will be updated and sent with a commit. """ new_mutation = _datastore_pb2.Mutation() self._mutations.append(new_mutation) return new_mutation.insert
[ "def", "_add_partial_key_entity_pb", "(", "self", ")", ":", "new_mutation", "=", "_datastore_pb2", ".", "Mutation", "(", ")", "self", ".", "_mutations", ".", "append", "(", "new_mutation", ")", "return", "new_mutation", ".", "insert" ]
Adds a new mutation for an entity with a partial key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created entity protobuf that will be updated and sent with a commit.
[ "Adds", "a", "new", "mutation", "for", "an", "entity", "with", "a", "partial", "key", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/batch.py#L107-L116
28,218
googleapis/google-cloud-python
datastore/google/cloud/datastore/batch.py
Batch._add_complete_key_entity_pb
def _add_complete_key_entity_pb(self): """Adds a new mutation for an entity with a completed key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created entity protobuf that will be updated and sent with a commit. """ # We use ``upsert`` for entities with completed keys, rather than # ``insert`` or ``update``, in order not to create race conditions # based on prior existence / removal of the entity. new_mutation = _datastore_pb2.Mutation() self._mutations.append(new_mutation) return new_mutation.upsert
python
def _add_complete_key_entity_pb(self): """Adds a new mutation for an entity with a completed key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created entity protobuf that will be updated and sent with a commit. """ # We use ``upsert`` for entities with completed keys, rather than # ``insert`` or ``update``, in order not to create race conditions # based on prior existence / removal of the entity. new_mutation = _datastore_pb2.Mutation() self._mutations.append(new_mutation) return new_mutation.upsert
[ "def", "_add_complete_key_entity_pb", "(", "self", ")", ":", "# We use ``upsert`` for entities with completed keys, rather than", "# ``insert`` or ``update``, in order not to create race conditions", "# based on prior existence / removal of the entity.", "new_mutation", "=", "_datastore_pb2", ".", "Mutation", "(", ")", "self", ".", "_mutations", ".", "append", "(", "new_mutation", ")", "return", "new_mutation", ".", "upsert" ]
Adds a new mutation for an entity with a completed key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created entity protobuf that will be updated and sent with a commit.
[ "Adds", "a", "new", "mutation", "for", "an", "entity", "with", "a", "completed", "key", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/batch.py#L118-L130
28,219
googleapis/google-cloud-python
datastore/google/cloud/datastore/batch.py
Batch._add_delete_key_pb
def _add_delete_key_pb(self): """Adds a new mutation for a key to be deleted. :rtype: :class:`.entity_pb2.Key` :returns: The newly created key protobuf that will be deleted when sent with a commit. """ new_mutation = _datastore_pb2.Mutation() self._mutations.append(new_mutation) return new_mutation.delete
python
def _add_delete_key_pb(self): """Adds a new mutation for a key to be deleted. :rtype: :class:`.entity_pb2.Key` :returns: The newly created key protobuf that will be deleted when sent with a commit. """ new_mutation = _datastore_pb2.Mutation() self._mutations.append(new_mutation) return new_mutation.delete
[ "def", "_add_delete_key_pb", "(", "self", ")", ":", "new_mutation", "=", "_datastore_pb2", ".", "Mutation", "(", ")", "self", ".", "_mutations", ".", "append", "(", "new_mutation", ")", "return", "new_mutation", ".", "delete" ]
Adds a new mutation for a key to be deleted. :rtype: :class:`.entity_pb2.Key` :returns: The newly created key protobuf that will be deleted when sent with a commit.
[ "Adds", "a", "new", "mutation", "for", "a", "key", "to", "be", "deleted", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/batch.py#L132-L141
28,220
googleapis/google-cloud-python
datastore/google/cloud/datastore/batch.py
Batch.rollback
def rollback(self): """Rolls back the current batch. Marks the batch as aborted (can't be used again). Overridden by :class:`google.cloud.datastore.transaction.Transaction`. :raises: :class:`~exceptions.ValueError` if the batch is not in progress. """ if self._status != self._IN_PROGRESS: raise ValueError("Batch must be in progress to rollback()") self._status = self._ABORTED
python
def rollback(self): """Rolls back the current batch. Marks the batch as aborted (can't be used again). Overridden by :class:`google.cloud.datastore.transaction.Transaction`. :raises: :class:`~exceptions.ValueError` if the batch is not in progress. """ if self._status != self._IN_PROGRESS: raise ValueError("Batch must be in progress to rollback()") self._status = self._ABORTED
[ "def", "rollback", "(", "self", ")", ":", "if", "self", ".", "_status", "!=", "self", ".", "_IN_PROGRESS", ":", "raise", "ValueError", "(", "\"Batch must be in progress to rollback()\"", ")", "self", ".", "_status", "=", "self", ".", "_ABORTED" ]
Rolls back the current batch. Marks the batch as aborted (can't be used again). Overridden by :class:`google.cloud.datastore.transaction.Transaction`. :raises: :class:`~exceptions.ValueError` if the batch is not in progress.
[ "Rolls", "back", "the", "current", "batch", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/batch.py#L278-L291
28,221
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_table_admin_client.py
BigtableTableAdminClient.create_table
def create_table( self, parent, table_id, table, initial_splits=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new table in the specified instance. The table can be created with a full set of initial column families, specified in the request. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableTableAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `table_id`: >>> table_id = '' >>> >>> # TODO: Initialize `table`: >>> table = {} >>> >>> response = client.create_table(parent, table_id, table) Args: parent (str): The unique name of the instance in which to create the table. Values are of the form ``projects/<project>/instances/<instance>``. table_id (str): The name by which the new table should be referred to within the parent instance, e.g., ``foobar`` rather than ``<parent>/tables/foobar``. table (Union[dict, ~google.cloud.bigtable_admin_v2.types.Table]): The Table to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Table` initial_splits (list[Union[dict, ~google.cloud.bigtable_admin_v2.types.Split]]): The optional list of row keys that will be used to initially split the table into several tablets (tablets are similar to HBase regions). Given two split keys, ``s1`` and ``s2``, three tablets will be created, spanning the key ranges: ``[, s1), [s1, s2), [s2, )``. Example: - Row keys := ``["a", "apple", "custom", "customer_1", "customer_2",`` ``"other", "zz"]`` - initial\_split\_keys := ``["apple", "customer_1", "customer_2", "other"]`` - Key assignment: - Tablet 1 ``[, apple) => {"a"}.`` - Tablet 2 ``[apple, customer_1) => {"apple", "custom"}.`` - Tablet 3 ``[customer_1, customer_2) => {"customer_1"}.`` - Tablet 4 ``[customer_2, other) => {"customer_2"}.`` - Tablet 5 ``[other, ) => {"other", "zz"}.`` If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Split` 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.bigtable_admin_v2.types.Table` 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_table" not in self._inner_api_calls: self._inner_api_calls[ "create_table" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_table, default_retry=self._method_configs["CreateTable"].retry, default_timeout=self._method_configs["CreateTable"].timeout, client_info=self._client_info, ) request = bigtable_table_admin_pb2.CreateTableRequest( parent=parent, table_id=table_id, table=table, initial_splits=initial_splits ) 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_table"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_table( self, parent, table_id, table, initial_splits=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new table in the specified instance. The table can be created with a full set of initial column families, specified in the request. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableTableAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `table_id`: >>> table_id = '' >>> >>> # TODO: Initialize `table`: >>> table = {} >>> >>> response = client.create_table(parent, table_id, table) Args: parent (str): The unique name of the instance in which to create the table. Values are of the form ``projects/<project>/instances/<instance>``. table_id (str): The name by which the new table should be referred to within the parent instance, e.g., ``foobar`` rather than ``<parent>/tables/foobar``. table (Union[dict, ~google.cloud.bigtable_admin_v2.types.Table]): The Table to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Table` initial_splits (list[Union[dict, ~google.cloud.bigtable_admin_v2.types.Split]]): The optional list of row keys that will be used to initially split the table into several tablets (tablets are similar to HBase regions). Given two split keys, ``s1`` and ``s2``, three tablets will be created, spanning the key ranges: ``[, s1), [s1, s2), [s2, )``. Example: - Row keys := ``["a", "apple", "custom", "customer_1", "customer_2",`` ``"other", "zz"]`` - initial\_split\_keys := ``["apple", "customer_1", "customer_2", "other"]`` - Key assignment: - Tablet 1 ``[, apple) => {"a"}.`` - Tablet 2 ``[apple, customer_1) => {"apple", "custom"}.`` - Tablet 3 ``[customer_1, customer_2) => {"customer_1"}.`` - Tablet 4 ``[customer_2, other) => {"customer_2"}.`` - Tablet 5 ``[other, ) => {"other", "zz"}.`` If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Split` 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.bigtable_admin_v2.types.Table` 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_table" not in self._inner_api_calls: self._inner_api_calls[ "create_table" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_table, default_retry=self._method_configs["CreateTable"].retry, default_timeout=self._method_configs["CreateTable"].timeout, client_info=self._client_info, ) request = bigtable_table_admin_pb2.CreateTableRequest( parent=parent, table_id=table_id, table=table, initial_splits=initial_splits ) 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_table"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_table", "(", "self", ",", "parent", ",", "table_id", ",", "table", ",", "initial_splits", "=", "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_table\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_table\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_table", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateTable\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateTable\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "bigtable_table_admin_pb2", ".", "CreateTableRequest", "(", "parent", "=", "parent", ",", "table_id", "=", "table_id", ",", "table", "=", "table", ",", "initial_splits", "=", "initial_splits", ")", "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_table\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a new table in the specified instance. The table can be created with a full set of initial column families, specified in the request. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableTableAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `table_id`: >>> table_id = '' >>> >>> # TODO: Initialize `table`: >>> table = {} >>> >>> response = client.create_table(parent, table_id, table) Args: parent (str): The unique name of the instance in which to create the table. Values are of the form ``projects/<project>/instances/<instance>``. table_id (str): The name by which the new table should be referred to within the parent instance, e.g., ``foobar`` rather than ``<parent>/tables/foobar``. table (Union[dict, ~google.cloud.bigtable_admin_v2.types.Table]): The Table to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Table` initial_splits (list[Union[dict, ~google.cloud.bigtable_admin_v2.types.Split]]): The optional list of row keys that will be used to initially split the table into several tablets (tablets are similar to HBase regions). Given two split keys, ``s1`` and ``s2``, three tablets will be created, spanning the key ranges: ``[, s1), [s1, s2), [s2, )``. Example: - Row keys := ``["a", "apple", "custom", "customer_1", "customer_2",`` ``"other", "zz"]`` - initial\_split\_keys := ``["apple", "customer_1", "customer_2", "other"]`` - Key assignment: - Tablet 1 ``[, apple) => {"a"}.`` - Tablet 2 ``[apple, customer_1) => {"apple", "custom"}.`` - Tablet 3 ``[customer_1, customer_2) => {"customer_1"}.`` - Tablet 4 ``[customer_2, other) => {"customer_2"}.`` - Tablet 5 ``[other, ) => {"other", "zz"}.`` If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Split` 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.bigtable_admin_v2.types.Table` 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", "table", "in", "the", "specified", "instance", ".", "The", "table", "can", "be", "created", "with", "a", "full", "set", "of", "initial", "column", "families", "specified", "in", "the", "request", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_table_admin_client.py#L231-L339
28,222
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_table_admin_client.py
BigtableTableAdminClient.create_table_from_snapshot
def create_table_from_snapshot( self, parent, table_id, source_snapshot, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new table from the specified snapshot. The target table must not exist. The snapshot and the table must be in the same instance. Note: This is a private alpha release of Cloud Bigtable snapshots. This feature is not currently available to most Cloud Bigtable customers. This feature might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableTableAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `table_id`: >>> table_id = '' >>> >>> # TODO: Initialize `source_snapshot`: >>> source_snapshot = '' >>> >>> response = client.create_table_from_snapshot(parent, table_id, source_snapshot) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): The unique name of the instance in which to create the table. Values are of the form ``projects/<project>/instances/<instance>``. table_id (str): The name by which the new table should be referred to within the parent instance, e.g., ``foobar`` rather than ``<parent>/tables/foobar``. source_snapshot (str): The unique name of the snapshot from which to restore the table. The snapshot and the table must be in the same instance. Values are of the form ``projects/<project>/instances/<instance>/clusters/<cluster>/snapshots/<snapshot>``. 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.bigtable_admin_v2.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_table_from_snapshot" not in self._inner_api_calls: self._inner_api_calls[ "create_table_from_snapshot" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_table_from_snapshot, default_retry=self._method_configs["CreateTableFromSnapshot"].retry, default_timeout=self._method_configs["CreateTableFromSnapshot"].timeout, client_info=self._client_info, ) request = bigtable_table_admin_pb2.CreateTableFromSnapshotRequest( parent=parent, table_id=table_id, source_snapshot=source_snapshot ) 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_table_from_snapshot"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, table_pb2.Table, metadata_type=bigtable_table_admin_pb2.CreateTableFromSnapshotMetadata, )
python
def create_table_from_snapshot( self, parent, table_id, source_snapshot, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new table from the specified snapshot. The target table must not exist. The snapshot and the table must be in the same instance. Note: This is a private alpha release of Cloud Bigtable snapshots. This feature is not currently available to most Cloud Bigtable customers. This feature might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableTableAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `table_id`: >>> table_id = '' >>> >>> # TODO: Initialize `source_snapshot`: >>> source_snapshot = '' >>> >>> response = client.create_table_from_snapshot(parent, table_id, source_snapshot) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): The unique name of the instance in which to create the table. Values are of the form ``projects/<project>/instances/<instance>``. table_id (str): The name by which the new table should be referred to within the parent instance, e.g., ``foobar`` rather than ``<parent>/tables/foobar``. source_snapshot (str): The unique name of the snapshot from which to restore the table. The snapshot and the table must be in the same instance. Values are of the form ``projects/<project>/instances/<instance>/clusters/<cluster>/snapshots/<snapshot>``. 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.bigtable_admin_v2.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_table_from_snapshot" not in self._inner_api_calls: self._inner_api_calls[ "create_table_from_snapshot" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_table_from_snapshot, default_retry=self._method_configs["CreateTableFromSnapshot"].retry, default_timeout=self._method_configs["CreateTableFromSnapshot"].timeout, client_info=self._client_info, ) request = bigtable_table_admin_pb2.CreateTableFromSnapshotRequest( parent=parent, table_id=table_id, source_snapshot=source_snapshot ) 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_table_from_snapshot"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, table_pb2.Table, metadata_type=bigtable_table_admin_pb2.CreateTableFromSnapshotMetadata, )
[ "def", "create_table_from_snapshot", "(", "self", ",", "parent", ",", "table_id", ",", "source_snapshot", ",", "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_table_from_snapshot\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_table_from_snapshot\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_table_from_snapshot", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateTableFromSnapshot\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateTableFromSnapshot\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "bigtable_table_admin_pb2", ".", "CreateTableFromSnapshotRequest", "(", "parent", "=", "parent", ",", "table_id", "=", "table_id", ",", "source_snapshot", "=", "source_snapshot", ")", "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_table_from_snapshot\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "table_pb2", ".", "Table", ",", "metadata_type", "=", "bigtable_table_admin_pb2", ".", "CreateTableFromSnapshotMetadata", ",", ")" ]
Creates a new table from the specified snapshot. The target table must not exist. The snapshot and the table must be in the same instance. Note: This is a private alpha release of Cloud Bigtable snapshots. This feature is not currently available to most Cloud Bigtable customers. This feature might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableTableAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `table_id`: >>> table_id = '' >>> >>> # TODO: Initialize `source_snapshot`: >>> source_snapshot = '' >>> >>> response = client.create_table_from_snapshot(parent, table_id, source_snapshot) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): The unique name of the instance in which to create the table. Values are of the form ``projects/<project>/instances/<instance>``. table_id (str): The name by which the new table should be referred to within the parent instance, e.g., ``foobar`` rather than ``<parent>/tables/foobar``. source_snapshot (str): The unique name of the snapshot from which to restore the table. The snapshot and the table must be in the same instance. Values are of the form ``projects/<project>/instances/<instance>/clusters/<cluster>/snapshots/<snapshot>``. 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.bigtable_admin_v2.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", "new", "table", "from", "the", "specified", "snapshot", ".", "The", "target", "table", "must", "not", "exist", ".", "The", "snapshot", "and", "the", "table", "must", "be", "in", "the", "same", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_table_admin_client.py#L341-L447
28,223
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_table_admin_client.py
BigtableTableAdminClient.snapshot_table
def snapshot_table( self, name, cluster, snapshot_id, description, ttl=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new snapshot in the specified cluster from the specified source table. The cluster and the table must be in the same instance. Note: This is a private alpha release of Cloud Bigtable snapshots. This feature is not currently available to most Cloud Bigtable customers. This feature might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableTableAdminClient() >>> >>> name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> # TODO: Initialize `cluster`: >>> cluster = '' >>> >>> # TODO: Initialize `snapshot_id`: >>> snapshot_id = '' >>> >>> # TODO: Initialize `description`: >>> description = '' >>> >>> response = client.snapshot_table(name, cluster, snapshot_id, description) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): The unique name of the table to have the snapshot taken. Values are of the form ``projects/<project>/instances/<instance>/tables/<table>``. cluster (str): The name of the cluster where the snapshot will be created in. Values are of the form ``projects/<project>/instances/<instance>/clusters/<cluster>``. snapshot_id (str): The ID by which the new snapshot should be referred to within the parent cluster, e.g., ``mysnapshot`` of the form: ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*`` rather than ``projects/<project>/instances/<instance>/clusters/<cluster>/snapshots/mysnapshot``. description (str): Description of the snapshot. ttl (Union[dict, ~google.cloud.bigtable_admin_v2.types.Duration]): The amount of time that the new snapshot can stay active after it is created. Once 'ttl' expires, the snapshot will get deleted. The maximum amount of time a snapshot can stay active is 7 days. If 'ttl' is not specified, the default value of 24 hours will be used. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Duration` 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.bigtable_admin_v2.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 "snapshot_table" not in self._inner_api_calls: self._inner_api_calls[ "snapshot_table" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.snapshot_table, default_retry=self._method_configs["SnapshotTable"].retry, default_timeout=self._method_configs["SnapshotTable"].timeout, client_info=self._client_info, ) request = bigtable_table_admin_pb2.SnapshotTableRequest( name=name, cluster=cluster, snapshot_id=snapshot_id, description=description, ttl=ttl, ) 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["snapshot_table"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, table_pb2.Snapshot, metadata_type=bigtable_table_admin_pb2.SnapshotTableMetadata, )
python
def snapshot_table( self, name, cluster, snapshot_id, description, ttl=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new snapshot in the specified cluster from the specified source table. The cluster and the table must be in the same instance. Note: This is a private alpha release of Cloud Bigtable snapshots. This feature is not currently available to most Cloud Bigtable customers. This feature might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableTableAdminClient() >>> >>> name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> # TODO: Initialize `cluster`: >>> cluster = '' >>> >>> # TODO: Initialize `snapshot_id`: >>> snapshot_id = '' >>> >>> # TODO: Initialize `description`: >>> description = '' >>> >>> response = client.snapshot_table(name, cluster, snapshot_id, description) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): The unique name of the table to have the snapshot taken. Values are of the form ``projects/<project>/instances/<instance>/tables/<table>``. cluster (str): The name of the cluster where the snapshot will be created in. Values are of the form ``projects/<project>/instances/<instance>/clusters/<cluster>``. snapshot_id (str): The ID by which the new snapshot should be referred to within the parent cluster, e.g., ``mysnapshot`` of the form: ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*`` rather than ``projects/<project>/instances/<instance>/clusters/<cluster>/snapshots/mysnapshot``. description (str): Description of the snapshot. ttl (Union[dict, ~google.cloud.bigtable_admin_v2.types.Duration]): The amount of time that the new snapshot can stay active after it is created. Once 'ttl' expires, the snapshot will get deleted. The maximum amount of time a snapshot can stay active is 7 days. If 'ttl' is not specified, the default value of 24 hours will be used. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Duration` 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.bigtable_admin_v2.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 "snapshot_table" not in self._inner_api_calls: self._inner_api_calls[ "snapshot_table" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.snapshot_table, default_retry=self._method_configs["SnapshotTable"].retry, default_timeout=self._method_configs["SnapshotTable"].timeout, client_info=self._client_info, ) request = bigtable_table_admin_pb2.SnapshotTableRequest( name=name, cluster=cluster, snapshot_id=snapshot_id, description=description, ttl=ttl, ) 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["snapshot_table"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, table_pb2.Snapshot, metadata_type=bigtable_table_admin_pb2.SnapshotTableMetadata, )
[ "def", "snapshot_table", "(", "self", ",", "name", ",", "cluster", ",", "snapshot_id", ",", "description", ",", "ttl", "=", "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", "\"snapshot_table\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"snapshot_table\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "snapshot_table", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"SnapshotTable\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"SnapshotTable\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "bigtable_table_admin_pb2", ".", "SnapshotTableRequest", "(", "name", "=", "name", ",", "cluster", "=", "cluster", ",", "snapshot_id", "=", "snapshot_id", ",", "description", "=", "description", ",", "ttl", "=", "ttl", ",", ")", "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", "[", "\"snapshot_table\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "table_pb2", ".", "Snapshot", ",", "metadata_type", "=", "bigtable_table_admin_pb2", ".", "SnapshotTableMetadata", ",", ")" ]
Creates a new snapshot in the specified cluster from the specified source table. The cluster and the table must be in the same instance. Note: This is a private alpha release of Cloud Bigtable snapshots. This feature is not currently available to most Cloud Bigtable customers. This feature might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableTableAdminClient() >>> >>> name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> # TODO: Initialize `cluster`: >>> cluster = '' >>> >>> # TODO: Initialize `snapshot_id`: >>> snapshot_id = '' >>> >>> # TODO: Initialize `description`: >>> description = '' >>> >>> response = client.snapshot_table(name, cluster, snapshot_id, description) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): The unique name of the table to have the snapshot taken. Values are of the form ``projects/<project>/instances/<instance>/tables/<table>``. cluster (str): The name of the cluster where the snapshot will be created in. Values are of the form ``projects/<project>/instances/<instance>/clusters/<cluster>``. snapshot_id (str): The ID by which the new snapshot should be referred to within the parent cluster, e.g., ``mysnapshot`` of the form: ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*`` rather than ``projects/<project>/instances/<instance>/clusters/<cluster>/snapshots/mysnapshot``. description (str): Description of the snapshot. ttl (Union[dict, ~google.cloud.bigtable_admin_v2.types.Duration]): The amount of time that the new snapshot can stay active after it is created. Once 'ttl' expires, the snapshot will get deleted. The maximum amount of time a snapshot can stay active is 7 days. If 'ttl' is not specified, the default value of 24 hours will be used. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Duration` 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.bigtable_admin_v2.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", "new", "snapshot", "in", "the", "specified", "cluster", "from", "the", "specified", "source", "table", ".", "The", "cluster", "and", "the", "table", "must", "be", "in", "the", "same", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_table_admin_client.py#L1022-L1146
28,224
googleapis/google-cloud-python
talent/google/cloud/talent_v4beta1/gapic/company_service_client.py
CompanyServiceClient.company_path
def company_path(cls, project, company): """Return a fully-qualified company string.""" return google.api_core.path_template.expand( "projects/{project}/companies/{company}", project=project, company=company )
python
def company_path(cls, project, company): """Return a fully-qualified company string.""" return google.api_core.path_template.expand( "projects/{project}/companies/{company}", project=project, company=company )
[ "def", "company_path", "(", "cls", ",", "project", ",", "company", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/companies/{company}\"", ",", "project", "=", "project", ",", "company", "=", "company", ")" ]
Return a fully-qualified company string.
[ "Return", "a", "fully", "-", "qualified", "company", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/company_service_client.py#L81-L85
28,225
googleapis/google-cloud-python
talent/google/cloud/talent_v4beta1/gapic/company_service_client.py
CompanyServiceClient.create_company
def create_company( self, parent, company, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new company entity. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompanyServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `company`: >>> company = {} >>> >>> response = client.create_company(parent, company) Args: parent (str): Required. Resource name of the project under which the company is created. The format is "projects/{project\_id}", for example, "projects/api-test-project". company (Union[dict, ~google.cloud.talent_v4beta1.types.Company]): Required. The company to be created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Company` 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.Company` 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_company" not in self._inner_api_calls: self._inner_api_calls[ "create_company" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_company, default_retry=self._method_configs["CreateCompany"].retry, default_timeout=self._method_configs["CreateCompany"].timeout, client_info=self._client_info, ) request = company_service_pb2.CreateCompanyRequest( parent=parent, company=company ) return self._inner_api_calls["create_company"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_company( self, parent, company, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new company entity. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompanyServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `company`: >>> company = {} >>> >>> response = client.create_company(parent, company) Args: parent (str): Required. Resource name of the project under which the company is created. The format is "projects/{project\_id}", for example, "projects/api-test-project". company (Union[dict, ~google.cloud.talent_v4beta1.types.Company]): Required. The company to be created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Company` 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.Company` 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_company" not in self._inner_api_calls: self._inner_api_calls[ "create_company" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_company, default_retry=self._method_configs["CreateCompany"].retry, default_timeout=self._method_configs["CreateCompany"].timeout, client_info=self._client_info, ) request = company_service_pb2.CreateCompanyRequest( parent=parent, company=company ) return self._inner_api_calls["create_company"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_company", "(", "self", ",", "parent", ",", "company", ",", "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_company\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_company\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_company", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateCompany\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateCompany\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "company_service_pb2", ".", "CreateCompanyRequest", "(", "parent", "=", "parent", ",", "company", "=", "company", ")", "return", "self", ".", "_inner_api_calls", "[", "\"create_company\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a new company entity. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompanyServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `company`: >>> company = {} >>> >>> response = client.create_company(parent, company) Args: parent (str): Required. Resource name of the project under which the company is created. The format is "projects/{project\_id}", for example, "projects/api-test-project". company (Union[dict, ~google.cloud.talent_v4beta1.types.Company]): Required. The company to be created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Company` 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.Company` 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", "company", "entity", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/company_service_client.py#L186-L257
28,226
googleapis/google-cloud-python
talent/google/cloud/talent_v4beta1/gapic/company_service_client.py
CompanyServiceClient.update_company
def update_company( self, company, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates specified company. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompanyServiceClient() >>> >>> # TODO: Initialize `company`: >>> company = {} >>> >>> response = client.update_company(company) Args: company (Union[dict, ~google.cloud.talent_v4beta1.types.Company]): Required. The company resource to replace the current resource in the system. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Company` update_mask (Union[dict, ~google.cloud.talent_v4beta1.types.FieldMask]): Optional but strongly recommended for the best service experience. If ``update_mask`` is provided, only the specified fields in ``company`` are updated. Otherwise all the fields are updated. A field mask to specify the company fields to be updated. Only top level fields of ``Company`` are supported. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.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.talent_v4beta1.types.Company` 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_company" not in self._inner_api_calls: self._inner_api_calls[ "update_company" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_company, default_retry=self._method_configs["UpdateCompany"].retry, default_timeout=self._method_configs["UpdateCompany"].timeout, client_info=self._client_info, ) request = company_service_pb2.UpdateCompanyRequest( company=company, update_mask=update_mask ) return self._inner_api_calls["update_company"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def update_company( self, company, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates specified company. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompanyServiceClient() >>> >>> # TODO: Initialize `company`: >>> company = {} >>> >>> response = client.update_company(company) Args: company (Union[dict, ~google.cloud.talent_v4beta1.types.Company]): Required. The company resource to replace the current resource in the system. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Company` update_mask (Union[dict, ~google.cloud.talent_v4beta1.types.FieldMask]): Optional but strongly recommended for the best service experience. If ``update_mask`` is provided, only the specified fields in ``company`` are updated. Otherwise all the fields are updated. A field mask to specify the company fields to be updated. Only top level fields of ``Company`` are supported. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.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.talent_v4beta1.types.Company` 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_company" not in self._inner_api_calls: self._inner_api_calls[ "update_company" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_company, default_retry=self._method_configs["UpdateCompany"].retry, default_timeout=self._method_configs["UpdateCompany"].timeout, client_info=self._client_info, ) request = company_service_pb2.UpdateCompanyRequest( company=company, update_mask=update_mask ) return self._inner_api_calls["update_company"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "update_company", "(", "self", ",", "company", ",", "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_company\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"update_company\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "update_company", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"UpdateCompany\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"UpdateCompany\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "company_service_pb2", ".", "UpdateCompanyRequest", "(", "company", "=", "company", ",", "update_mask", "=", "update_mask", ")", "return", "self", ".", "_inner_api_calls", "[", "\"update_company\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Updates specified company. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompanyServiceClient() >>> >>> # TODO: Initialize `company`: >>> company = {} >>> >>> response = client.update_company(company) Args: company (Union[dict, ~google.cloud.talent_v4beta1.types.Company]): Required. The company resource to replace the current resource in the system. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Company` update_mask (Union[dict, ~google.cloud.talent_v4beta1.types.FieldMask]): Optional but strongly recommended for the best service experience. If ``update_mask`` is provided, only the specified fields in ``company`` are updated. Otherwise all the fields are updated. A field mask to specify the company fields to be updated. Only top level fields of ``Company`` are supported. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.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.talent_v4beta1.types.Company` 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", "specified", "company", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/company_service_client.py#L320-L393
28,227
googleapis/google-cloud-python
dns/google/cloud/dns/client.py
Client.quotas
def quotas(self): """Return DNS quotas for the project associated with this client. See https://cloud.google.com/dns/api/v1/projects/get :rtype: mapping :returns: keys for the mapping correspond to those of the ``quota`` sub-mapping of the project resource. """ path = "/projects/%s" % (self.project,) resp = self._connection.api_request(method="GET", path=path) return { key: int(value) for key, value in resp["quota"].items() if key != "kind" }
python
def quotas(self): """Return DNS quotas for the project associated with this client. See https://cloud.google.com/dns/api/v1/projects/get :rtype: mapping :returns: keys for the mapping correspond to those of the ``quota`` sub-mapping of the project resource. """ path = "/projects/%s" % (self.project,) resp = self._connection.api_request(method="GET", path=path) return { key: int(value) for key, value in resp["quota"].items() if key != "kind" }
[ "def", "quotas", "(", "self", ")", ":", "path", "=", "\"/projects/%s\"", "%", "(", "self", ".", "project", ",", ")", "resp", "=", "self", ".", "_connection", ".", "api_request", "(", "method", "=", "\"GET\"", ",", "path", "=", "path", ")", "return", "{", "key", ":", "int", "(", "value", ")", "for", "key", ",", "value", "in", "resp", "[", "\"quota\"", "]", ".", "items", "(", ")", "if", "key", "!=", "\"kind\"", "}" ]
Return DNS quotas for the project associated with this client. See https://cloud.google.com/dns/api/v1/projects/get :rtype: mapping :returns: keys for the mapping correspond to those of the ``quota`` sub-mapping of the project resource.
[ "Return", "DNS", "quotas", "for", "the", "project", "associated", "with", "this", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/client.py#L57-L72
28,228
googleapis/google-cloud-python
dns/google/cloud/dns/client.py
Client.list_zones
def list_zones(self, max_results=None, page_token=None): """List zones for the project associated with this client. See https://cloud.google.com/dns/api/v1/managedZones/list :type max_results: int :param max_results: maximum number of zones to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: Optional. If present, return the next batch of zones, using the value, which must correspond to the ``nextPageToken`` value returned in the previous response. Deprecated: use the ``pages`` property of the returned iterator instead of manually passing the token. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.dns.zone.ManagedZone` belonging to this project. """ path = "/projects/%s/managedZones" % (self.project,) return page_iterator.HTTPIterator( client=self, api_request=self._connection.api_request, path=path, item_to_value=_item_to_zone, items_key="managedZones", page_token=page_token, max_results=max_results, )
python
def list_zones(self, max_results=None, page_token=None): """List zones for the project associated with this client. See https://cloud.google.com/dns/api/v1/managedZones/list :type max_results: int :param max_results: maximum number of zones to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: Optional. If present, return the next batch of zones, using the value, which must correspond to the ``nextPageToken`` value returned in the previous response. Deprecated: use the ``pages`` property of the returned iterator instead of manually passing the token. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.dns.zone.ManagedZone` belonging to this project. """ path = "/projects/%s/managedZones" % (self.project,) return page_iterator.HTTPIterator( client=self, api_request=self._connection.api_request, path=path, item_to_value=_item_to_zone, items_key="managedZones", page_token=page_token, max_results=max_results, )
[ "def", "list_zones", "(", "self", ",", "max_results", "=", "None", ",", "page_token", "=", "None", ")", ":", "path", "=", "\"/projects/%s/managedZones\"", "%", "(", "self", ".", "project", ",", ")", "return", "page_iterator", ".", "HTTPIterator", "(", "client", "=", "self", ",", "api_request", "=", "self", ".", "_connection", ".", "api_request", ",", "path", "=", "path", ",", "item_to_value", "=", "_item_to_zone", ",", "items_key", "=", "\"managedZones\"", ",", "page_token", "=", "page_token", ",", "max_results", "=", "max_results", ",", ")" ]
List zones for the project associated with this client. See https://cloud.google.com/dns/api/v1/managedZones/list :type max_results: int :param max_results: maximum number of zones to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: Optional. If present, return the next batch of zones, using the value, which must correspond to the ``nextPageToken`` value returned in the previous response. Deprecated: use the ``pages`` property of the returned iterator instead of manually passing the token. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.dns.zone.ManagedZone` belonging to this project.
[ "List", "zones", "for", "the", "project", "associated", "with", "this", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/client.py#L74-L104
28,229
googleapis/google-cloud-python
dns/google/cloud/dns/client.py
Client.zone
def zone(self, name, dns_name=None, description=None): """Construct a zone bound to this client. :type name: str :param name: Name of the zone. :type dns_name: str :param dns_name: (Optional) DNS name of the zone. If not passed, then calls to :meth:`zone.create` will fail. :type description: str :param description: (Optional) the description for the zone. If not passed, defaults to the value of 'dns_name'. :rtype: :class:`google.cloud.dns.zone.ManagedZone` :returns: a new ``ManagedZone`` instance. """ return ManagedZone(name, dns_name, client=self, description=description)
python
def zone(self, name, dns_name=None, description=None): """Construct a zone bound to this client. :type name: str :param name: Name of the zone. :type dns_name: str :param dns_name: (Optional) DNS name of the zone. If not passed, then calls to :meth:`zone.create` will fail. :type description: str :param description: (Optional) the description for the zone. If not passed, defaults to the value of 'dns_name'. :rtype: :class:`google.cloud.dns.zone.ManagedZone` :returns: a new ``ManagedZone`` instance. """ return ManagedZone(name, dns_name, client=self, description=description)
[ "def", "zone", "(", "self", ",", "name", ",", "dns_name", "=", "None", ",", "description", "=", "None", ")", ":", "return", "ManagedZone", "(", "name", ",", "dns_name", ",", "client", "=", "self", ",", "description", "=", "description", ")" ]
Construct a zone bound to this client. :type name: str :param name: Name of the zone. :type dns_name: str :param dns_name: (Optional) DNS name of the zone. If not passed, then calls to :meth:`zone.create` will fail. :type description: str :param description: (Optional) the description for the zone. If not passed, defaults to the value of 'dns_name'. :rtype: :class:`google.cloud.dns.zone.ManagedZone` :returns: a new ``ManagedZone`` instance.
[ "Construct", "a", "zone", "bound", "to", "this", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/client.py#L106-L125
28,230
googleapis/google-cloud-python
datastore/google/cloud/datastore/query.py
_pb_from_query
def _pb_from_query(query): """Convert a Query instance to the corresponding protobuf. :type query: :class:`Query` :param query: The source query. :rtype: :class:`.query_pb2.Query` :returns: A protobuf that can be sent to the protobuf API. N.b. that it does not contain "in-flight" fields for ongoing query executions (cursors, offset, limit). """ pb = query_pb2.Query() for projection_name in query.projection: pb.projection.add().property.name = projection_name if query.kind: pb.kind.add().name = query.kind composite_filter = pb.filter.composite_filter composite_filter.op = query_pb2.CompositeFilter.AND if query.ancestor: ancestor_pb = query.ancestor.to_protobuf() # Filter on __key__ HAS_ANCESTOR == ancestor. ancestor_filter = composite_filter.filters.add().property_filter ancestor_filter.property.name = "__key__" ancestor_filter.op = query_pb2.PropertyFilter.HAS_ANCESTOR ancestor_filter.value.key_value.CopyFrom(ancestor_pb) for property_name, operator, value in query.filters: pb_op_enum = query.OPERATORS.get(operator) # Add the specific filter property_filter = composite_filter.filters.add().property_filter property_filter.property.name = property_name property_filter.op = pb_op_enum # Set the value to filter on based on the type. if property_name == "__key__": key_pb = value.to_protobuf() property_filter.value.key_value.CopyFrom(key_pb) else: helpers._set_protobuf_value(property_filter.value, value) if not composite_filter.filters: pb.ClearField("filter") for prop in query.order: property_order = pb.order.add() if prop.startswith("-"): property_order.property.name = prop[1:] property_order.direction = property_order.DESCENDING else: property_order.property.name = prop property_order.direction = property_order.ASCENDING for distinct_on_name in query.distinct_on: pb.distinct_on.add().name = distinct_on_name return pb
python
def _pb_from_query(query): """Convert a Query instance to the corresponding protobuf. :type query: :class:`Query` :param query: The source query. :rtype: :class:`.query_pb2.Query` :returns: A protobuf that can be sent to the protobuf API. N.b. that it does not contain "in-flight" fields for ongoing query executions (cursors, offset, limit). """ pb = query_pb2.Query() for projection_name in query.projection: pb.projection.add().property.name = projection_name if query.kind: pb.kind.add().name = query.kind composite_filter = pb.filter.composite_filter composite_filter.op = query_pb2.CompositeFilter.AND if query.ancestor: ancestor_pb = query.ancestor.to_protobuf() # Filter on __key__ HAS_ANCESTOR == ancestor. ancestor_filter = composite_filter.filters.add().property_filter ancestor_filter.property.name = "__key__" ancestor_filter.op = query_pb2.PropertyFilter.HAS_ANCESTOR ancestor_filter.value.key_value.CopyFrom(ancestor_pb) for property_name, operator, value in query.filters: pb_op_enum = query.OPERATORS.get(operator) # Add the specific filter property_filter = composite_filter.filters.add().property_filter property_filter.property.name = property_name property_filter.op = pb_op_enum # Set the value to filter on based on the type. if property_name == "__key__": key_pb = value.to_protobuf() property_filter.value.key_value.CopyFrom(key_pb) else: helpers._set_protobuf_value(property_filter.value, value) if not composite_filter.filters: pb.ClearField("filter") for prop in query.order: property_order = pb.order.add() if prop.startswith("-"): property_order.property.name = prop[1:] property_order.direction = property_order.DESCENDING else: property_order.property.name = prop property_order.direction = property_order.ASCENDING for distinct_on_name in query.distinct_on: pb.distinct_on.add().name = distinct_on_name return pb
[ "def", "_pb_from_query", "(", "query", ")", ":", "pb", "=", "query_pb2", ".", "Query", "(", ")", "for", "projection_name", "in", "query", ".", "projection", ":", "pb", ".", "projection", ".", "add", "(", ")", ".", "property", ".", "name", "=", "projection_name", "if", "query", ".", "kind", ":", "pb", ".", "kind", ".", "add", "(", ")", ".", "name", "=", "query", ".", "kind", "composite_filter", "=", "pb", ".", "filter", ".", "composite_filter", "composite_filter", ".", "op", "=", "query_pb2", ".", "CompositeFilter", ".", "AND", "if", "query", ".", "ancestor", ":", "ancestor_pb", "=", "query", ".", "ancestor", ".", "to_protobuf", "(", ")", "# Filter on __key__ HAS_ANCESTOR == ancestor.", "ancestor_filter", "=", "composite_filter", ".", "filters", ".", "add", "(", ")", ".", "property_filter", "ancestor_filter", ".", "property", ".", "name", "=", "\"__key__\"", "ancestor_filter", ".", "op", "=", "query_pb2", ".", "PropertyFilter", ".", "HAS_ANCESTOR", "ancestor_filter", ".", "value", ".", "key_value", ".", "CopyFrom", "(", "ancestor_pb", ")", "for", "property_name", ",", "operator", ",", "value", "in", "query", ".", "filters", ":", "pb_op_enum", "=", "query", ".", "OPERATORS", ".", "get", "(", "operator", ")", "# Add the specific filter", "property_filter", "=", "composite_filter", ".", "filters", ".", "add", "(", ")", ".", "property_filter", "property_filter", ".", "property", ".", "name", "=", "property_name", "property_filter", ".", "op", "=", "pb_op_enum", "# Set the value to filter on based on the type.", "if", "property_name", "==", "\"__key__\"", ":", "key_pb", "=", "value", ".", "to_protobuf", "(", ")", "property_filter", ".", "value", ".", "key_value", ".", "CopyFrom", "(", "key_pb", ")", "else", ":", "helpers", ".", "_set_protobuf_value", "(", "property_filter", ".", "value", ",", "value", ")", "if", "not", "composite_filter", ".", "filters", ":", "pb", ".", "ClearField", "(", "\"filter\"", ")", "for", "prop", "in", "query", ".", "order", ":", "property_order", "=", "pb", ".", "order", ".", "add", "(", ")", "if", "prop", ".", "startswith", "(", "\"-\"", ")", ":", "property_order", ".", "property", ".", "name", "=", "prop", "[", "1", ":", "]", "property_order", ".", "direction", "=", "property_order", ".", "DESCENDING", "else", ":", "property_order", ".", "property", ".", "name", "=", "prop", "property_order", ".", "direction", "=", "property_order", ".", "ASCENDING", "for", "distinct_on_name", "in", "query", ".", "distinct_on", ":", "pb", ".", "distinct_on", ".", "add", "(", ")", ".", "name", "=", "distinct_on_name", "return", "pb" ]
Convert a Query instance to the corresponding protobuf. :type query: :class:`Query` :param query: The source query. :rtype: :class:`.query_pb2.Query` :returns: A protobuf that can be sent to the protobuf API. N.b. that it does not contain "in-flight" fields for ongoing query executions (cursors, offset, limit).
[ "Convert", "a", "Query", "instance", "to", "the", "corresponding", "protobuf", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/query.py#L543-L605
28,231
googleapis/google-cloud-python
datastore/google/cloud/datastore/query.py
Query.namespace
def namespace(self, value): """Update the query's namespace. :type value: str """ if not isinstance(value, str): raise ValueError("Namespace must be a string") self._namespace = value
python
def namespace(self, value): """Update the query's namespace. :type value: str """ if not isinstance(value, str): raise ValueError("Namespace must be a string") self._namespace = value
[ "def", "namespace", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "raise", "ValueError", "(", "\"Namespace must be a string\"", ")", "self", ".", "_namespace", "=", "value" ]
Update the query's namespace. :type value: str
[ "Update", "the", "query", "s", "namespace", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/query.py#L137-L144
28,232
googleapis/google-cloud-python
datastore/google/cloud/datastore/query.py
Query.kind
def kind(self, value): """Update the Kind of the Query. :type value: str :param value: updated kind for the query. .. note:: The protobuf specification allows for ``kind`` to be repeated, but the current implementation returns an error if more than one value is passed. If the back-end changes in the future to allow multiple values, this method will be updated to allow passing either a string or a sequence of strings. """ if not isinstance(value, str): raise TypeError("Kind must be a string") self._kind = value
python
def kind(self, value): """Update the Kind of the Query. :type value: str :param value: updated kind for the query. .. note:: The protobuf specification allows for ``kind`` to be repeated, but the current implementation returns an error if more than one value is passed. If the back-end changes in the future to allow multiple values, this method will be updated to allow passing either a string or a sequence of strings. """ if not isinstance(value, str): raise TypeError("Kind must be a string") self._kind = value
[ "def", "kind", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "raise", "TypeError", "(", "\"Kind must be a string\"", ")", "self", ".", "_kind", "=", "value" ]
Update the Kind of the Query. :type value: str :param value: updated kind for the query. .. note:: The protobuf specification allows for ``kind`` to be repeated, but the current implementation returns an error if more than one value is passed. If the back-end changes in the future to allow multiple values, this method will be updated to allow passing either a string or a sequence of strings.
[ "Update", "the", "Kind", "of", "the", "Query", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/query.py#L156-L172
28,233
googleapis/google-cloud-python
datastore/google/cloud/datastore/query.py
Query.ancestor
def ancestor(self, value): """Set the ancestor for the query :type value: :class:`~google.cloud.datastore.key.Key` :param value: the new ancestor key """ if not isinstance(value, Key): raise TypeError("Ancestor must be a Key") self._ancestor = value
python
def ancestor(self, value): """Set the ancestor for the query :type value: :class:`~google.cloud.datastore.key.Key` :param value: the new ancestor key """ if not isinstance(value, Key): raise TypeError("Ancestor must be a Key") self._ancestor = value
[ "def", "ancestor", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "Key", ")", ":", "raise", "TypeError", "(", "\"Ancestor must be a Key\"", ")", "self", ".", "_ancestor", "=", "value" ]
Set the ancestor for the query :type value: :class:`~google.cloud.datastore.key.Key` :param value: the new ancestor key
[ "Set", "the", "ancestor", "for", "the", "query" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/query.py#L184-L192
28,234
googleapis/google-cloud-python
datastore/google/cloud/datastore/query.py
Query.add_filter
def add_filter(self, property_name, operator, value): """Filter the query based on a property name, operator and a value. Expressions take the form of:: .add_filter('<property>', '<operator>', <value>) where property is a property stored on the entity in the datastore and operator is one of ``OPERATORS`` (ie, ``=``, ``<``, ``<=``, ``>``, ``>=``):: >>> from google.cloud import datastore >>> client = datastore.Client() >>> query = client.query(kind='Person') >>> query.add_filter('name', '=', 'James') >>> query.add_filter('age', '>', 50) :type property_name: str :param property_name: A property name. :type operator: str :param operator: One of ``=``, ``<``, ``<=``, ``>``, ``>=``. :type value: :class:`int`, :class:`str`, :class:`bool`, :class:`float`, :class:`NoneType`, :class:`datetime.datetime`, :class:`google.cloud.datastore.key.Key` :param value: The value to filter on. :raises: :class:`ValueError` if ``operation`` is not one of the specified values, or if a filter names ``'__key__'`` but passes an invalid value (a key is required). """ if self.OPERATORS.get(operator) is None: error_message = 'Invalid expression: "%s"' % (operator,) choices_message = "Please use one of: =, <, <=, >, >=." raise ValueError(error_message, choices_message) if property_name == "__key__" and not isinstance(value, Key): raise ValueError('Invalid key: "%s"' % value) self._filters.append((property_name, operator, value))
python
def add_filter(self, property_name, operator, value): """Filter the query based on a property name, operator and a value. Expressions take the form of:: .add_filter('<property>', '<operator>', <value>) where property is a property stored on the entity in the datastore and operator is one of ``OPERATORS`` (ie, ``=``, ``<``, ``<=``, ``>``, ``>=``):: >>> from google.cloud import datastore >>> client = datastore.Client() >>> query = client.query(kind='Person') >>> query.add_filter('name', '=', 'James') >>> query.add_filter('age', '>', 50) :type property_name: str :param property_name: A property name. :type operator: str :param operator: One of ``=``, ``<``, ``<=``, ``>``, ``>=``. :type value: :class:`int`, :class:`str`, :class:`bool`, :class:`float`, :class:`NoneType`, :class:`datetime.datetime`, :class:`google.cloud.datastore.key.Key` :param value: The value to filter on. :raises: :class:`ValueError` if ``operation`` is not one of the specified values, or if a filter names ``'__key__'`` but passes an invalid value (a key is required). """ if self.OPERATORS.get(operator) is None: error_message = 'Invalid expression: "%s"' % (operator,) choices_message = "Please use one of: =, <, <=, >, >=." raise ValueError(error_message, choices_message) if property_name == "__key__" and not isinstance(value, Key): raise ValueError('Invalid key: "%s"' % value) self._filters.append((property_name, operator, value))
[ "def", "add_filter", "(", "self", ",", "property_name", ",", "operator", ",", "value", ")", ":", "if", "self", ".", "OPERATORS", ".", "get", "(", "operator", ")", "is", "None", ":", "error_message", "=", "'Invalid expression: \"%s\"'", "%", "(", "operator", ",", ")", "choices_message", "=", "\"Please use one of: =, <, <=, >, >=.\"", "raise", "ValueError", "(", "error_message", ",", "choices_message", ")", "if", "property_name", "==", "\"__key__\"", "and", "not", "isinstance", "(", "value", ",", "Key", ")", ":", "raise", "ValueError", "(", "'Invalid key: \"%s\"'", "%", "value", ")", "self", ".", "_filters", ".", "append", "(", "(", "property_name", ",", "operator", ",", "value", ")", ")" ]
Filter the query based on a property name, operator and a value. Expressions take the form of:: .add_filter('<property>', '<operator>', <value>) where property is a property stored on the entity in the datastore and operator is one of ``OPERATORS`` (ie, ``=``, ``<``, ``<=``, ``>``, ``>=``):: >>> from google.cloud import datastore >>> client = datastore.Client() >>> query = client.query(kind='Person') >>> query.add_filter('name', '=', 'James') >>> query.add_filter('age', '>', 50) :type property_name: str :param property_name: A property name. :type operator: str :param operator: One of ``=``, ``<``, ``<=``, ``>``, ``>=``. :type value: :class:`int`, :class:`str`, :class:`bool`, :class:`float`, :class:`NoneType`, :class:`datetime.datetime`, :class:`google.cloud.datastore.key.Key` :param value: The value to filter on. :raises: :class:`ValueError` if ``operation`` is not one of the specified values, or if a filter names ``'__key__'`` but passes an invalid value (a key is required).
[ "Filter", "the", "query", "based", "on", "a", "property", "name", "operator", "and", "a", "value", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/query.py#L209-L250
28,235
googleapis/google-cloud-python
datastore/google/cloud/datastore/query.py
Query.projection
def projection(self, projection): """Set the fields returned the query. :type projection: str or sequence of strings :param projection: Each value is a string giving the name of a property to be included in the projection query. """ if isinstance(projection, str): projection = [projection] self._projection[:] = projection
python
def projection(self, projection): """Set the fields returned the query. :type projection: str or sequence of strings :param projection: Each value is a string giving the name of a property to be included in the projection query. """ if isinstance(projection, str): projection = [projection] self._projection[:] = projection
[ "def", "projection", "(", "self", ",", "projection", ")", ":", "if", "isinstance", "(", "projection", ",", "str", ")", ":", "projection", "=", "[", "projection", "]", "self", ".", "_projection", "[", ":", "]", "=", "projection" ]
Set the fields returned the query. :type projection: str or sequence of strings :param projection: Each value is a string giving the name of a property to be included in the projection query.
[ "Set", "the", "fields", "returned", "the", "query", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/query.py#L262-L271
28,236
googleapis/google-cloud-python
datastore/google/cloud/datastore/query.py
Query.order
def order(self, value): """Set the fields used to sort query results. Sort fields will be applied in the order specified. :type value: str or sequence of strings :param value: Each value is a string giving the name of the property on which to sort, optionally preceded by a hyphen (-) to specify descending order. Omitting the hyphen implies ascending order. """ if isinstance(value, str): value = [value] self._order[:] = value
python
def order(self, value): """Set the fields used to sort query results. Sort fields will be applied in the order specified. :type value: str or sequence of strings :param value: Each value is a string giving the name of the property on which to sort, optionally preceded by a hyphen (-) to specify descending order. Omitting the hyphen implies ascending order. """ if isinstance(value, str): value = [value] self._order[:] = value
[ "def", "order", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "[", "value", "]", "self", ".", "_order", "[", ":", "]", "=", "value" ]
Set the fields used to sort query results. Sort fields will be applied in the order specified. :type value: str or sequence of strings :param value: Each value is a string giving the name of the property on which to sort, optionally preceded by a hyphen (-) to specify descending order. Omitting the hyphen implies ascending order.
[ "Set", "the", "fields", "used", "to", "sort", "query", "results", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/query.py#L299-L312
28,237
googleapis/google-cloud-python
datastore/google/cloud/datastore/query.py
Query.distinct_on
def distinct_on(self, value): """Set fields used to group query results. :type value: str or sequence of strings :param value: Each value is a string giving the name of a property to use to group results together. """ if isinstance(value, str): value = [value] self._distinct_on[:] = value
python
def distinct_on(self, value): """Set fields used to group query results. :type value: str or sequence of strings :param value: Each value is a string giving the name of a property to use to group results together. """ if isinstance(value, str): value = [value] self._distinct_on[:] = value
[ "def", "distinct_on", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "[", "value", "]", "self", ".", "_distinct_on", "[", ":", "]", "=", "value" ]
Set fields used to group query results. :type value: str or sequence of strings :param value: Each value is a string giving the name of a property to use to group results together.
[ "Set", "fields", "used", "to", "group", "query", "results", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/query.py#L324-L333
28,238
googleapis/google-cloud-python
datastore/google/cloud/datastore/query.py
Query.fetch
def fetch( self, limit=None, offset=0, start_cursor=None, end_cursor=None, client=None, eventual=False, ): """Execute the Query; return an iterator for the matching entities. For example:: >>> from google.cloud import datastore >>> client = datastore.Client() >>> query = client.query(kind='Person') >>> query.add_filter('name', '=', 'Sally') >>> list(query.fetch()) [<Entity object>, <Entity object>, ...] >>> list(query.fetch(1)) [<Entity object>] :type limit: int :param limit: (Optional) limit passed through to the iterator. :type offset: int :param offset: (Optional) offset passed through to the iterator. :type start_cursor: bytes :param start_cursor: (Optional) cursor passed through to the iterator. :type end_cursor: bytes :param end_cursor: (Optional) cursor passed through to the iterator. :type client: :class:`google.cloud.datastore.client.Client` :param client: (Optional) client used to connect to datastore. If not supplied, uses the query's value. :type eventual: bool :param eventual: (Optional) Defaults to strongly consistent (False). Setting True will use eventual consistency, but cannot be used inside a transaction or will raise ValueError. :rtype: :class:`Iterator` :returns: The iterator for the query. """ if client is None: client = self._client return Iterator( self, client, limit=limit, offset=offset, start_cursor=start_cursor, end_cursor=end_cursor, eventual=eventual, )
python
def fetch( self, limit=None, offset=0, start_cursor=None, end_cursor=None, client=None, eventual=False, ): """Execute the Query; return an iterator for the matching entities. For example:: >>> from google.cloud import datastore >>> client = datastore.Client() >>> query = client.query(kind='Person') >>> query.add_filter('name', '=', 'Sally') >>> list(query.fetch()) [<Entity object>, <Entity object>, ...] >>> list(query.fetch(1)) [<Entity object>] :type limit: int :param limit: (Optional) limit passed through to the iterator. :type offset: int :param offset: (Optional) offset passed through to the iterator. :type start_cursor: bytes :param start_cursor: (Optional) cursor passed through to the iterator. :type end_cursor: bytes :param end_cursor: (Optional) cursor passed through to the iterator. :type client: :class:`google.cloud.datastore.client.Client` :param client: (Optional) client used to connect to datastore. If not supplied, uses the query's value. :type eventual: bool :param eventual: (Optional) Defaults to strongly consistent (False). Setting True will use eventual consistency, but cannot be used inside a transaction or will raise ValueError. :rtype: :class:`Iterator` :returns: The iterator for the query. """ if client is None: client = self._client return Iterator( self, client, limit=limit, offset=offset, start_cursor=start_cursor, end_cursor=end_cursor, eventual=eventual, )
[ "def", "fetch", "(", "self", ",", "limit", "=", "None", ",", "offset", "=", "0", ",", "start_cursor", "=", "None", ",", "end_cursor", "=", "None", ",", "client", "=", "None", ",", "eventual", "=", "False", ",", ")", ":", "if", "client", "is", "None", ":", "client", "=", "self", ".", "_client", "return", "Iterator", "(", "self", ",", "client", ",", "limit", "=", "limit", ",", "offset", "=", "offset", ",", "start_cursor", "=", "start_cursor", ",", "end_cursor", "=", "end_cursor", ",", "eventual", "=", "eventual", ",", ")" ]
Execute the Query; return an iterator for the matching entities. For example:: >>> from google.cloud import datastore >>> client = datastore.Client() >>> query = client.query(kind='Person') >>> query.add_filter('name', '=', 'Sally') >>> list(query.fetch()) [<Entity object>, <Entity object>, ...] >>> list(query.fetch(1)) [<Entity object>] :type limit: int :param limit: (Optional) limit passed through to the iterator. :type offset: int :param offset: (Optional) offset passed through to the iterator. :type start_cursor: bytes :param start_cursor: (Optional) cursor passed through to the iterator. :type end_cursor: bytes :param end_cursor: (Optional) cursor passed through to the iterator. :type client: :class:`google.cloud.datastore.client.Client` :param client: (Optional) client used to connect to datastore. If not supplied, uses the query's value. :type eventual: bool :param eventual: (Optional) Defaults to strongly consistent (False). Setting True will use eventual consistency, but cannot be used inside a transaction or will raise ValueError. :rtype: :class:`Iterator` :returns: The iterator for the query.
[ "Execute", "the", "Query", ";", "return", "an", "iterator", "for", "the", "matching", "entities", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/query.py#L335-L393
28,239
googleapis/google-cloud-python
datastore/google/cloud/datastore/query.py
Iterator._build_protobuf
def _build_protobuf(self): """Build a query protobuf. Relies on the current state of the iterator. :rtype: :class:`.query_pb2.Query` :returns: The query protobuf object for the current state of the iterator. """ pb = _pb_from_query(self._query) start_cursor = self.next_page_token if start_cursor is not None: pb.start_cursor = base64.urlsafe_b64decode(start_cursor) end_cursor = self._end_cursor if end_cursor is not None: pb.end_cursor = base64.urlsafe_b64decode(end_cursor) if self.max_results is not None: pb.limit.value = self.max_results - self.num_results if start_cursor is None and self._offset is not None: # NOTE: We don't need to add an offset to the request protobuf # if we are using an existing cursor, because the offset # is only relative to the start of the result set, not # relative to each page (this method is called per-page) pb.offset = self._offset return pb
python
def _build_protobuf(self): """Build a query protobuf. Relies on the current state of the iterator. :rtype: :class:`.query_pb2.Query` :returns: The query protobuf object for the current state of the iterator. """ pb = _pb_from_query(self._query) start_cursor = self.next_page_token if start_cursor is not None: pb.start_cursor = base64.urlsafe_b64decode(start_cursor) end_cursor = self._end_cursor if end_cursor is not None: pb.end_cursor = base64.urlsafe_b64decode(end_cursor) if self.max_results is not None: pb.limit.value = self.max_results - self.num_results if start_cursor is None and self._offset is not None: # NOTE: We don't need to add an offset to the request protobuf # if we are using an existing cursor, because the offset # is only relative to the start of the result set, not # relative to each page (this method is called per-page) pb.offset = self._offset return pb
[ "def", "_build_protobuf", "(", "self", ")", ":", "pb", "=", "_pb_from_query", "(", "self", ".", "_query", ")", "start_cursor", "=", "self", ".", "next_page_token", "if", "start_cursor", "is", "not", "None", ":", "pb", ".", "start_cursor", "=", "base64", ".", "urlsafe_b64decode", "(", "start_cursor", ")", "end_cursor", "=", "self", ".", "_end_cursor", "if", "end_cursor", "is", "not", "None", ":", "pb", ".", "end_cursor", "=", "base64", ".", "urlsafe_b64decode", "(", "end_cursor", ")", "if", "self", ".", "max_results", "is", "not", "None", ":", "pb", ".", "limit", ".", "value", "=", "self", ".", "max_results", "-", "self", ".", "num_results", "if", "start_cursor", "is", "None", "and", "self", ".", "_offset", "is", "not", "None", ":", "# NOTE: We don't need to add an offset to the request protobuf", "# if we are using an existing cursor, because the offset", "# is only relative to the start of the result set, not", "# relative to each page (this method is called per-page)", "pb", ".", "offset", "=", "self", ".", "_offset", "return", "pb" ]
Build a query protobuf. Relies on the current state of the iterator. :rtype: :class:`.query_pb2.Query` :returns: The query protobuf object for the current state of the iterator.
[ "Build", "a", "query", "protobuf", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/query.py#L454-L484
28,240
googleapis/google-cloud-python
datastore/google/cloud/datastore/query.py
Iterator._process_query_results
def _process_query_results(self, response_pb): """Process the response from a datastore query. :type response_pb: :class:`.datastore_pb2.RunQueryResponse` :param response_pb: The protobuf response from a ``runQuery`` request. :rtype: iterable :returns: The next page of entity results. :raises ValueError: If ``more_results`` is an unexpected value. """ self._skipped_results = response_pb.batch.skipped_results if response_pb.batch.more_results == _NO_MORE_RESULTS: self.next_page_token = None else: self.next_page_token = base64.urlsafe_b64encode( response_pb.batch.end_cursor ) self._end_cursor = None if response_pb.batch.more_results == _NOT_FINISHED: self._more_results = True elif response_pb.batch.more_results in _FINISHED: self._more_results = False else: raise ValueError("Unexpected value returned for `more_results`.") return [result.entity for result in response_pb.batch.entity_results]
python
def _process_query_results(self, response_pb): """Process the response from a datastore query. :type response_pb: :class:`.datastore_pb2.RunQueryResponse` :param response_pb: The protobuf response from a ``runQuery`` request. :rtype: iterable :returns: The next page of entity results. :raises ValueError: If ``more_results`` is an unexpected value. """ self._skipped_results = response_pb.batch.skipped_results if response_pb.batch.more_results == _NO_MORE_RESULTS: self.next_page_token = None else: self.next_page_token = base64.urlsafe_b64encode( response_pb.batch.end_cursor ) self._end_cursor = None if response_pb.batch.more_results == _NOT_FINISHED: self._more_results = True elif response_pb.batch.more_results in _FINISHED: self._more_results = False else: raise ValueError("Unexpected value returned for `more_results`.") return [result.entity for result in response_pb.batch.entity_results]
[ "def", "_process_query_results", "(", "self", ",", "response_pb", ")", ":", "self", ".", "_skipped_results", "=", "response_pb", ".", "batch", ".", "skipped_results", "if", "response_pb", ".", "batch", ".", "more_results", "==", "_NO_MORE_RESULTS", ":", "self", ".", "next_page_token", "=", "None", "else", ":", "self", ".", "next_page_token", "=", "base64", ".", "urlsafe_b64encode", "(", "response_pb", ".", "batch", ".", "end_cursor", ")", "self", ".", "_end_cursor", "=", "None", "if", "response_pb", ".", "batch", ".", "more_results", "==", "_NOT_FINISHED", ":", "self", ".", "_more_results", "=", "True", "elif", "response_pb", ".", "batch", ".", "more_results", "in", "_FINISHED", ":", "self", ".", "_more_results", "=", "False", "else", ":", "raise", "ValueError", "(", "\"Unexpected value returned for `more_results`.\"", ")", "return", "[", "result", ".", "entity", "for", "result", "in", "response_pb", ".", "batch", ".", "entity_results", "]" ]
Process the response from a datastore query. :type response_pb: :class:`.datastore_pb2.RunQueryResponse` :param response_pb: The protobuf response from a ``runQuery`` request. :rtype: iterable :returns: The next page of entity results. :raises ValueError: If ``more_results`` is an unexpected value.
[ "Process", "the", "response", "from", "a", "datastore", "query", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/query.py#L486-L513
28,241
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/batch.py
_BatchBase.update
def update(self, table, columns, values): """Update one or more existing table rows. :type table: str :param table: Name of the table to be modified. :type columns: list of str :param columns: Name of the table columns to be modified. :type values: list of lists :param values: Values to be modified. """ self._mutations.append(Mutation(update=_make_write_pb(table, columns, values)))
python
def update(self, table, columns, values): """Update one or more existing table rows. :type table: str :param table: Name of the table to be modified. :type columns: list of str :param columns: Name of the table columns to be modified. :type values: list of lists :param values: Values to be modified. """ self._mutations.append(Mutation(update=_make_write_pb(table, columns, values)))
[ "def", "update", "(", "self", ",", "table", ",", "columns", ",", "values", ")", ":", "self", ".", "_mutations", ".", "append", "(", "Mutation", "(", "update", "=", "_make_write_pb", "(", "table", ",", "columns", ",", "values", ")", ")", ")" ]
Update one or more existing table rows. :type table: str :param table: Name of the table to be modified. :type columns: list of str :param columns: Name of the table columns to be modified. :type values: list of lists :param values: Values to be modified.
[ "Update", "one", "or", "more", "existing", "table", "rows", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/batch.py#L64-L76
28,242
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/batch.py
_BatchBase.delete
def delete(self, table, keyset): """Delete one or more table rows. :type table: str :param table: Name of the table to be modified. :type keyset: :class:`~google.cloud.spanner_v1.keyset.Keyset` :param keyset: Keys/ranges identifying rows to delete. """ delete = Mutation.Delete(table=table, key_set=keyset._to_pb()) self._mutations.append(Mutation(delete=delete))
python
def delete(self, table, keyset): """Delete one or more table rows. :type table: str :param table: Name of the table to be modified. :type keyset: :class:`~google.cloud.spanner_v1.keyset.Keyset` :param keyset: Keys/ranges identifying rows to delete. """ delete = Mutation.Delete(table=table, key_set=keyset._to_pb()) self._mutations.append(Mutation(delete=delete))
[ "def", "delete", "(", "self", ",", "table", ",", "keyset", ")", ":", "delete", "=", "Mutation", ".", "Delete", "(", "table", "=", "table", ",", "key_set", "=", "keyset", ".", "_to_pb", "(", ")", ")", "self", ".", "_mutations", ".", "append", "(", "Mutation", "(", "delete", "=", "delete", ")", ")" ]
Delete one or more table rows. :type table: str :param table: Name of the table to be modified. :type keyset: :class:`~google.cloud.spanner_v1.keyset.Keyset` :param keyset: Keys/ranges identifying rows to delete.
[ "Delete", "one", "or", "more", "table", "rows", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/batch.py#L108-L118
28,243
googleapis/google-cloud-python
bigquery/docs/snippets.py
dataset_exists
def dataset_exists(client, dataset_reference): """Return if a dataset exists. Args: client (google.cloud.bigquery.client.Client): A client to connect to the BigQuery API. dataset_reference (google.cloud.bigquery.dataset.DatasetReference): A reference to the dataset to look for. Returns: bool: ``True`` if the dataset exists, ``False`` otherwise. """ from google.cloud.exceptions import NotFound try: client.get_dataset(dataset_reference) return True except NotFound: return False
python
def dataset_exists(client, dataset_reference): """Return if a dataset exists. Args: client (google.cloud.bigquery.client.Client): A client to connect to the BigQuery API. dataset_reference (google.cloud.bigquery.dataset.DatasetReference): A reference to the dataset to look for. Returns: bool: ``True`` if the dataset exists, ``False`` otherwise. """ from google.cloud.exceptions import NotFound try: client.get_dataset(dataset_reference) return True except NotFound: return False
[ "def", "dataset_exists", "(", "client", ",", "dataset_reference", ")", ":", "from", "google", ".", "cloud", ".", "exceptions", "import", "NotFound", "try", ":", "client", ".", "get_dataset", "(", "dataset_reference", ")", "return", "True", "except", "NotFound", ":", "return", "False" ]
Return if a dataset exists. Args: client (google.cloud.bigquery.client.Client): A client to connect to the BigQuery API. dataset_reference (google.cloud.bigquery.dataset.DatasetReference): A reference to the dataset to look for. Returns: bool: ``True`` if the dataset exists, ``False`` otherwise.
[ "Return", "if", "a", "dataset", "exists", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/docs/snippets.py#L178-L196
28,244
googleapis/google-cloud-python
bigquery/docs/snippets.py
table_exists
def table_exists(client, table_reference): """Return if a table exists. Args: client (google.cloud.bigquery.client.Client): A client to connect to the BigQuery API. table_reference (google.cloud.bigquery.table.TableReference): A reference to the table to look for. Returns: bool: ``True`` if the table exists, ``False`` otherwise. """ from google.cloud.exceptions import NotFound try: client.get_table(table_reference) return True except NotFound: return False
python
def table_exists(client, table_reference): """Return if a table exists. Args: client (google.cloud.bigquery.client.Client): A client to connect to the BigQuery API. table_reference (google.cloud.bigquery.table.TableReference): A reference to the table to look for. Returns: bool: ``True`` if the table exists, ``False`` otherwise. """ from google.cloud.exceptions import NotFound try: client.get_table(table_reference) return True except NotFound: return False
[ "def", "table_exists", "(", "client", ",", "table_reference", ")", ":", "from", "google", ".", "cloud", ".", "exceptions", "import", "NotFound", "try", ":", "client", ".", "get_table", "(", "table_reference", ")", "return", "True", "except", "NotFound", ":", "return", "False" ]
Return if a table exists. Args: client (google.cloud.bigquery.client.Client): A client to connect to the BigQuery API. table_reference (google.cloud.bigquery.table.TableReference): A reference to the table to look for. Returns: bool: ``True`` if the table exists, ``False`` otherwise.
[ "Return", "if", "a", "table", "exists", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/docs/snippets.py#L460-L478
28,245
googleapis/google-cloud-python
datastore/google/cloud/datastore_v1/gapic/datastore_client.py
DatastoreClient.run_query
def run_query( self, project_id, partition_id, read_options=None, query=None, gql_query=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Queries for entities. Example: >>> from google.cloud import datastore_v1 >>> >>> client = datastore_v1.DatastoreClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `partition_id`: >>> partition_id = {} >>> >>> response = client.run_query(project_id, partition_id) Args: project_id (str): The ID of the project against which to make the request. partition_id (Union[dict, ~google.cloud.datastore_v1.types.PartitionId]): Entities are partitioned into subsets, identified by a partition ID. Queries are scoped to a single partition. This partition ID is normalized with the standard default context partition ID. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.PartitionId` read_options (Union[dict, ~google.cloud.datastore_v1.types.ReadOptions]): The options for this query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.ReadOptions` query (Union[dict, ~google.cloud.datastore_v1.types.Query]): The query to run. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.Query` gql_query (Union[dict, ~google.cloud.datastore_v1.types.GqlQuery]): The GQL query to run. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.GqlQuery` 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.datastore_v1.types.RunQueryResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "run_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(query=query, gql_query=gql_query) request = datastore_pb2.RunQueryRequest( project_id=project_id, partition_id=partition_id, read_options=read_options, query=query, gql_query=gql_query, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("project_id", project_id)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["run_query"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def run_query( self, project_id, partition_id, read_options=None, query=None, gql_query=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Queries for entities. Example: >>> from google.cloud import datastore_v1 >>> >>> client = datastore_v1.DatastoreClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `partition_id`: >>> partition_id = {} >>> >>> response = client.run_query(project_id, partition_id) Args: project_id (str): The ID of the project against which to make the request. partition_id (Union[dict, ~google.cloud.datastore_v1.types.PartitionId]): Entities are partitioned into subsets, identified by a partition ID. Queries are scoped to a single partition. This partition ID is normalized with the standard default context partition ID. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.PartitionId` read_options (Union[dict, ~google.cloud.datastore_v1.types.ReadOptions]): The options for this query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.ReadOptions` query (Union[dict, ~google.cloud.datastore_v1.types.Query]): The query to run. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.Query` gql_query (Union[dict, ~google.cloud.datastore_v1.types.GqlQuery]): The GQL query to run. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.GqlQuery` 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.datastore_v1.types.RunQueryResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "run_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(query=query, gql_query=gql_query) request = datastore_pb2.RunQueryRequest( project_id=project_id, partition_id=partition_id, read_options=read_options, query=query, gql_query=gql_query, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("project_id", project_id)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["run_query"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "run_query", "(", "self", ",", "project_id", ",", "partition_id", ",", "read_options", "=", "None", ",", "query", "=", "None", ",", "gql_query", "=", "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", "(", "query", "=", "query", ",", "gql_query", "=", "gql_query", ")", "request", "=", "datastore_pb2", ".", "RunQueryRequest", "(", "project_id", "=", "project_id", ",", "partition_id", "=", "partition_id", ",", "read_options", "=", "read_options", ",", "query", "=", "query", ",", "gql_query", "=", "gql_query", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"project_id\"", ",", "project_id", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"run_query\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Queries for entities. Example: >>> from google.cloud import datastore_v1 >>> >>> client = datastore_v1.DatastoreClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `partition_id`: >>> partition_id = {} >>> >>> response = client.run_query(project_id, partition_id) Args: project_id (str): The ID of the project against which to make the request. partition_id (Union[dict, ~google.cloud.datastore_v1.types.PartitionId]): Entities are partitioned into subsets, identified by a partition ID. Queries are scoped to a single partition. This partition ID is normalized with the standard default context partition ID. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.PartitionId` read_options (Union[dict, ~google.cloud.datastore_v1.types.ReadOptions]): The options for this query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.ReadOptions` query (Union[dict, ~google.cloud.datastore_v1.types.Query]): The query to run. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.Query` gql_query (Union[dict, ~google.cloud.datastore_v1.types.GqlQuery]): The GQL query to run. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.GqlQuery` 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.datastore_v1.types.RunQueryResponse` 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.
[ "Queries", "for", "entities", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore_v1/gapic/datastore_client.py#L264-L368
28,246
googleapis/google-cloud-python
datastore/google/cloud/datastore_v1/gapic/datastore_client.py
DatastoreClient.commit
def commit( self, project_id, mode, mutations, transaction=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Commits a transaction, optionally creating, deleting or modifying some entities. Example: >>> from google.cloud import datastore_v1 >>> from google.cloud.datastore_v1 import enums >>> >>> client = datastore_v1.DatastoreClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `mode`: >>> mode = enums.CommitRequest.Mode.MODE_UNSPECIFIED >>> >>> # TODO: Initialize `mutations`: >>> mutations = [] >>> >>> response = client.commit(project_id, mode, mutations) Args: project_id (str): The ID of the project against which to make the request. mode (~google.cloud.datastore_v1.types.Mode): The type of commit to perform. Defaults to ``TRANSACTIONAL``. mutations (list[Union[dict, ~google.cloud.datastore_v1.types.Mutation]]): The mutations to perform. When mode is ``TRANSACTIONAL``, mutations affecting a single entity are applied in order. The following sequences of mutations affecting a single entity are not permitted in a single ``Commit`` request: - ``insert`` followed by ``insert`` - ``update`` followed by ``insert`` - ``upsert`` followed by ``insert`` - ``delete`` followed by ``update`` When mode is ``NON_TRANSACTIONAL``, no two mutations may affect a single entity. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.Mutation` transaction (bytes): The identifier of the transaction associated with the commit. A transaction identifier is returned by a call to ``Datastore.BeginTransaction``. 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.datastore_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=transaction) request = datastore_pb2.CommitRequest( project_id=project_id, mode=mode, mutations=mutations, transaction=transaction, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("project_id", project_id)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["commit"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def commit( self, project_id, mode, mutations, transaction=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Commits a transaction, optionally creating, deleting or modifying some entities. Example: >>> from google.cloud import datastore_v1 >>> from google.cloud.datastore_v1 import enums >>> >>> client = datastore_v1.DatastoreClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `mode`: >>> mode = enums.CommitRequest.Mode.MODE_UNSPECIFIED >>> >>> # TODO: Initialize `mutations`: >>> mutations = [] >>> >>> response = client.commit(project_id, mode, mutations) Args: project_id (str): The ID of the project against which to make the request. mode (~google.cloud.datastore_v1.types.Mode): The type of commit to perform. Defaults to ``TRANSACTIONAL``. mutations (list[Union[dict, ~google.cloud.datastore_v1.types.Mutation]]): The mutations to perform. When mode is ``TRANSACTIONAL``, mutations affecting a single entity are applied in order. The following sequences of mutations affecting a single entity are not permitted in a single ``Commit`` request: - ``insert`` followed by ``insert`` - ``update`` followed by ``insert`` - ``upsert`` followed by ``insert`` - ``delete`` followed by ``update`` When mode is ``NON_TRANSACTIONAL``, no two mutations may affect a single entity. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.Mutation` transaction (bytes): The identifier of the transaction associated with the commit. A transaction identifier is returned by a call to ``Datastore.BeginTransaction``. 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.datastore_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=transaction) request = datastore_pb2.CommitRequest( project_id=project_id, mode=mode, mutations=mutations, transaction=transaction, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("project_id", project_id)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["commit"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "commit", "(", "self", ",", "project_id", ",", "mode", ",", "mutations", ",", "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", "=", "transaction", ")", "request", "=", "datastore_pb2", ".", "CommitRequest", "(", "project_id", "=", "project_id", ",", "mode", "=", "mode", ",", "mutations", "=", "mutations", ",", "transaction", "=", "transaction", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"project_id\"", ",", "project_id", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"commit\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Commits a transaction, optionally creating, deleting or modifying some entities. Example: >>> from google.cloud import datastore_v1 >>> from google.cloud.datastore_v1 import enums >>> >>> client = datastore_v1.DatastoreClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `mode`: >>> mode = enums.CommitRequest.Mode.MODE_UNSPECIFIED >>> >>> # TODO: Initialize `mutations`: >>> mutations = [] >>> >>> response = client.commit(project_id, mode, mutations) Args: project_id (str): The ID of the project against which to make the request. mode (~google.cloud.datastore_v1.types.Mode): The type of commit to perform. Defaults to ``TRANSACTIONAL``. mutations (list[Union[dict, ~google.cloud.datastore_v1.types.Mutation]]): The mutations to perform. When mode is ``TRANSACTIONAL``, mutations affecting a single entity are applied in order. The following sequences of mutations affecting a single entity are not permitted in a single ``Commit`` request: - ``insert`` followed by ``insert`` - ``update`` followed by ``insert`` - ``upsert`` followed by ``insert`` - ``delete`` followed by ``update`` When mode is ``NON_TRANSACTIONAL``, no two mutations may affect a single entity. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datastore_v1.types.Mutation` transaction (bytes): The identifier of the transaction associated with the commit. A transaction identifier is returned by a call to ``Datastore.BeginTransaction``. 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.datastore_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", "optionally", "creating", "deleting", "or", "modifying", "some", "entities", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore_v1/gapic/datastore_client.py#L447-L555
28,247
googleapis/google-cloud-python
logging/google/cloud/logging/handlers/app_engine.py
AppEngineHandler.get_gae_resource
def get_gae_resource(self): """Return the GAE resource using the environment variables. :rtype: :class:`~google.cloud.logging.resource.Resource` :returns: Monitored resource for GAE. """ gae_resource = Resource( type="gae_app", labels={ "project_id": self.project_id, "module_id": self.module_id, "version_id": self.version_id, }, ) return gae_resource
python
def get_gae_resource(self): """Return the GAE resource using the environment variables. :rtype: :class:`~google.cloud.logging.resource.Resource` :returns: Monitored resource for GAE. """ gae_resource = Resource( type="gae_app", labels={ "project_id": self.project_id, "module_id": self.module_id, "version_id": self.version_id, }, ) return gae_resource
[ "def", "get_gae_resource", "(", "self", ")", ":", "gae_resource", "=", "Resource", "(", "type", "=", "\"gae_app\"", ",", "labels", "=", "{", "\"project_id\"", ":", "self", ".", "project_id", ",", "\"module_id\"", ":", "self", ".", "module_id", ",", "\"version_id\"", ":", "self", ".", "version_id", ",", "}", ",", ")", "return", "gae_resource" ]
Return the GAE resource using the environment variables. :rtype: :class:`~google.cloud.logging.resource.Resource` :returns: Monitored resource for GAE.
[ "Return", "the", "GAE", "resource", "using", "the", "environment", "variables", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/app_engine.py#L72-L86
28,248
googleapis/google-cloud-python
logging/google/cloud/logging/handlers/app_engine.py
AppEngineHandler.get_gae_labels
def get_gae_labels(self): """Return the labels for GAE app. If the trace ID can be detected, it will be included as a label. Currently, no other labels are included. :rtype: dict :returns: Labels for GAE app. """ gae_labels = {} trace_id = get_trace_id() if trace_id is not None: gae_labels[_TRACE_ID_LABEL] = trace_id return gae_labels
python
def get_gae_labels(self): """Return the labels for GAE app. If the trace ID can be detected, it will be included as a label. Currently, no other labels are included. :rtype: dict :returns: Labels for GAE app. """ gae_labels = {} trace_id = get_trace_id() if trace_id is not None: gae_labels[_TRACE_ID_LABEL] = trace_id return gae_labels
[ "def", "get_gae_labels", "(", "self", ")", ":", "gae_labels", "=", "{", "}", "trace_id", "=", "get_trace_id", "(", ")", "if", "trace_id", "is", "not", "None", ":", "gae_labels", "[", "_TRACE_ID_LABEL", "]", "=", "trace_id", "return", "gae_labels" ]
Return the labels for GAE app. If the trace ID can be detected, it will be included as a label. Currently, no other labels are included. :rtype: dict :returns: Labels for GAE app.
[ "Return", "the", "labels", "for", "GAE", "app", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/app_engine.py#L88-L103
28,249
googleapis/google-cloud-python
iam/google/cloud/iam_credentials_v1/gapic/iam_credentials_client.py
IAMCredentialsClient.service_account_path
def service_account_path(cls, project, service_account): """Return a fully-qualified service_account string.""" return google.api_core.path_template.expand( "projects/{project}/serviceAccounts/{service_account}", project=project, service_account=service_account, )
python
def service_account_path(cls, project, service_account): """Return a fully-qualified service_account string.""" return google.api_core.path_template.expand( "projects/{project}/serviceAccounts/{service_account}", project=project, service_account=service_account, )
[ "def", "service_account_path", "(", "cls", ",", "project", ",", "service_account", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/serviceAccounts/{service_account}\"", ",", "project", "=", "project", ",", "service_account", "=", "service_account", ",", ")" ]
Return a fully-qualified service_account string.
[ "Return", "a", "fully", "-", "qualified", "service_account", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/iam/google/cloud/iam_credentials_v1/gapic/iam_credentials_client.py#L82-L88
28,250
googleapis/google-cloud-python
iam/google/cloud/iam_credentials_v1/gapic/iam_credentials_client.py
IAMCredentialsClient.generate_access_token
def generate_access_token( self, name, scope, delegates=None, lifetime=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Generates an OAuth 2.0 access token for a service account. Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `scope`: >>> scope = [] >>> >>> response = client.generate_access_token(name, scope) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. scope (list[str]): Code to identify the scopes to be included in the OAuth 2.0 access token. See https://developers.google.com/identity/protocols/googlescopes for more information. At least one value required. delegates (list[str]): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`` lifetime (Union[dict, ~google.cloud.iam_credentials_v1.types.Duration]): The desired lifetime duration of the access token in seconds. Must be set to a value less than or equal to 3600 (1 hour). If a value is not specified, the token's lifetime will be set to a default value of one hour. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.iam_credentials_v1.types.Duration` 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.iam_credentials_v1.types.GenerateAccessTokenResponse` 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 "generate_access_token" not in self._inner_api_calls: self._inner_api_calls[ "generate_access_token" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.generate_access_token, default_retry=self._method_configs["GenerateAccessToken"].retry, default_timeout=self._method_configs["GenerateAccessToken"].timeout, client_info=self._client_info, ) request = common_pb2.GenerateAccessTokenRequest( name=name, scope=scope, delegates=delegates, lifetime=lifetime ) 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["generate_access_token"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def generate_access_token( self, name, scope, delegates=None, lifetime=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Generates an OAuth 2.0 access token for a service account. Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `scope`: >>> scope = [] >>> >>> response = client.generate_access_token(name, scope) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. scope (list[str]): Code to identify the scopes to be included in the OAuth 2.0 access token. See https://developers.google.com/identity/protocols/googlescopes for more information. At least one value required. delegates (list[str]): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`` lifetime (Union[dict, ~google.cloud.iam_credentials_v1.types.Duration]): The desired lifetime duration of the access token in seconds. Must be set to a value less than or equal to 3600 (1 hour). If a value is not specified, the token's lifetime will be set to a default value of one hour. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.iam_credentials_v1.types.Duration` 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.iam_credentials_v1.types.GenerateAccessTokenResponse` 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 "generate_access_token" not in self._inner_api_calls: self._inner_api_calls[ "generate_access_token" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.generate_access_token, default_retry=self._method_configs["GenerateAccessToken"].retry, default_timeout=self._method_configs["GenerateAccessToken"].timeout, client_info=self._client_info, ) request = common_pb2.GenerateAccessTokenRequest( name=name, scope=scope, delegates=delegates, lifetime=lifetime ) 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["generate_access_token"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "generate_access_token", "(", "self", ",", "name", ",", "scope", ",", "delegates", "=", "None", ",", "lifetime", "=", "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", "\"generate_access_token\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"generate_access_token\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "generate_access_token", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"GenerateAccessToken\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"GenerateAccessToken\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "common_pb2", ".", "GenerateAccessTokenRequest", "(", "name", "=", "name", ",", "scope", "=", "scope", ",", "delegates", "=", "delegates", ",", "lifetime", "=", "lifetime", ")", "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", "[", "\"generate_access_token\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Generates an OAuth 2.0 access token for a service account. Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `scope`: >>> scope = [] >>> >>> response = client.generate_access_token(name, scope) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. scope (list[str]): Code to identify the scopes to be included in the OAuth 2.0 access token. See https://developers.google.com/identity/protocols/googlescopes for more information. At least one value required. delegates (list[str]): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`` lifetime (Union[dict, ~google.cloud.iam_credentials_v1.types.Duration]): The desired lifetime duration of the access token in seconds. Must be set to a value less than or equal to 3600 (1 hour). If a value is not specified, the token's lifetime will be set to a default value of one hour. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.iam_credentials_v1.types.Duration` 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.iam_credentials_v1.types.GenerateAccessTokenResponse` 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.
[ "Generates", "an", "OAuth", "2", ".", "0", "access", "token", "for", "a", "service", "account", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/iam/google/cloud/iam_credentials_v1/gapic/iam_credentials_client.py#L189-L286
28,251
googleapis/google-cloud-python
iam/google/cloud/iam_credentials_v1/gapic/iam_credentials_client.py
IAMCredentialsClient.generate_id_token
def generate_id_token( self, name, audience, delegates=None, include_email=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Generates an OpenID Connect ID token for a service account. Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `audience`: >>> audience = '' >>> >>> response = client.generate_id_token(name, audience) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. audience (str): The audience for the token, such as the API or account that this token grants access to. delegates (list[str]): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`` include_email (bool): Include the service account email in the token. If set to ``true``, the token will contain ``email`` and ``email_verified`` claims. 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.iam_credentials_v1.types.GenerateIdTokenResponse` 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 "generate_id_token" not in self._inner_api_calls: self._inner_api_calls[ "generate_id_token" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.generate_id_token, default_retry=self._method_configs["GenerateIdToken"].retry, default_timeout=self._method_configs["GenerateIdToken"].timeout, client_info=self._client_info, ) request = common_pb2.GenerateIdTokenRequest( name=name, audience=audience, delegates=delegates, include_email=include_email, ) 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["generate_id_token"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def generate_id_token( self, name, audience, delegates=None, include_email=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Generates an OpenID Connect ID token for a service account. Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `audience`: >>> audience = '' >>> >>> response = client.generate_id_token(name, audience) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. audience (str): The audience for the token, such as the API or account that this token grants access to. delegates (list[str]): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`` include_email (bool): Include the service account email in the token. If set to ``true``, the token will contain ``email`` and ``email_verified`` claims. 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.iam_credentials_v1.types.GenerateIdTokenResponse` 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 "generate_id_token" not in self._inner_api_calls: self._inner_api_calls[ "generate_id_token" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.generate_id_token, default_retry=self._method_configs["GenerateIdToken"].retry, default_timeout=self._method_configs["GenerateIdToken"].timeout, client_info=self._client_info, ) request = common_pb2.GenerateIdTokenRequest( name=name, audience=audience, delegates=delegates, include_email=include_email, ) 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["generate_id_token"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "generate_id_token", "(", "self", ",", "name", ",", "audience", ",", "delegates", "=", "None", ",", "include_email", "=", "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", "\"generate_id_token\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"generate_id_token\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "generate_id_token", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"GenerateIdToken\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"GenerateIdToken\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "common_pb2", ".", "GenerateIdTokenRequest", "(", "name", "=", "name", ",", "audience", "=", "audience", ",", "delegates", "=", "delegates", ",", "include_email", "=", "include_email", ",", ")", "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", "[", "\"generate_id_token\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Generates an OpenID Connect ID token for a service account. Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `audience`: >>> audience = '' >>> >>> response = client.generate_id_token(name, audience) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. audience (str): The audience for the token, such as the API or account that this token grants access to. delegates (list[str]): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`` include_email (bool): Include the service account email in the token. If set to ``true``, the token will contain ``email`` and ``email_verified`` claims. 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.iam_credentials_v1.types.GenerateIdTokenResponse` 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.
[ "Generates", "an", "OpenID", "Connect", "ID", "token", "for", "a", "service", "account", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/iam/google/cloud/iam_credentials_v1/gapic/iam_credentials_client.py#L288-L381
28,252
googleapis/google-cloud-python
iam/google/cloud/iam_credentials_v1/gapic/iam_credentials_client.py
IAMCredentialsClient.sign_blob
def sign_blob( self, name, payload, delegates=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Signs a blob using a service account's system-managed private key. Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `payload`: >>> payload = b'' >>> >>> response = client.sign_blob(name, payload) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. payload (bytes): The bytes to sign. delegates (list[str]): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`` 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.iam_credentials_v1.types.SignBlobResponse` 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 "sign_blob" not in self._inner_api_calls: self._inner_api_calls[ "sign_blob" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.sign_blob, default_retry=self._method_configs["SignBlob"].retry, default_timeout=self._method_configs["SignBlob"].timeout, client_info=self._client_info, ) request = common_pb2.SignBlobRequest( name=name, payload=payload, delegates=delegates ) 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["sign_blob"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def sign_blob( self, name, payload, delegates=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Signs a blob using a service account's system-managed private key. Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `payload`: >>> payload = b'' >>> >>> response = client.sign_blob(name, payload) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. payload (bytes): The bytes to sign. delegates (list[str]): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`` 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.iam_credentials_v1.types.SignBlobResponse` 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 "sign_blob" not in self._inner_api_calls: self._inner_api_calls[ "sign_blob" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.sign_blob, default_retry=self._method_configs["SignBlob"].retry, default_timeout=self._method_configs["SignBlob"].timeout, client_info=self._client_info, ) request = common_pb2.SignBlobRequest( name=name, payload=payload, delegates=delegates ) 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["sign_blob"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "sign_blob", "(", "self", ",", "name", ",", "payload", ",", "delegates", "=", "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", "\"sign_blob\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"sign_blob\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "sign_blob", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"SignBlob\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"SignBlob\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "common_pb2", ".", "SignBlobRequest", "(", "name", "=", "name", ",", "payload", "=", "payload", ",", "delegates", "=", "delegates", ")", "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", "[", "\"sign_blob\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Signs a blob using a service account's system-managed private key. Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `payload`: >>> payload = b'' >>> >>> response = client.sign_blob(name, payload) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. payload (bytes): The bytes to sign. delegates (list[str]): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`` 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.iam_credentials_v1.types.SignBlobResponse` 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.
[ "Signs", "a", "blob", "using", "a", "service", "account", "s", "system", "-", "managed", "private", "key", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/iam/google/cloud/iam_credentials_v1/gapic/iam_credentials_client.py#L383-L469
28,253
googleapis/google-cloud-python
iam/google/cloud/iam_credentials_v1/gapic/iam_credentials_client.py
IAMCredentialsClient.generate_identity_binding_access_token
def generate_identity_binding_access_token( self, name, scope, jwt, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Exchange a JWT signed by third party identity provider to an OAuth 2.0 access token Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `scope`: >>> scope = [] >>> >>> # TODO: Initialize `jwt`: >>> jwt = '' >>> >>> response = client.generate_identity_binding_access_token(name, scope, jwt) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. scope (list[str]): Code to identify the scopes to be included in the OAuth 2.0 access token. See https://developers.google.com/identity/protocols/googlescopes for more information. At least one value required. jwt (str): Required. Input token. Must be in JWT format according to RFC7523 (https://tools.ietf.org/html/rfc7523) and must have 'kid' field in the header. Supported signing algorithms: RS256 (RS512, ES256, ES512 coming soon). Mandatory payload fields (along the lines of RFC 7523, section 3): - iss: issuer of the token. Must provide a discovery document at $iss/.well-known/openid-configuration . The document needs to be formatted according to section 4.2 of the OpenID Connect Discovery 1.0 specification. - iat: Issue time in seconds since epoch. Must be in the past. - exp: Expiration time in seconds since epoch. Must be less than 48 hours after iat. We recommend to create tokens that last shorter than 6 hours to improve security unless business reasons mandate longer expiration times. Shorter token lifetimes are generally more secure since tokens that have been exfiltrated by attackers can be used for a shorter time. you can configure the maximum lifetime of the incoming token in the configuration of the mapper. The resulting Google token will expire within an hour or at "exp", whichever is earlier. - sub: JWT subject, identity asserted in the JWT. - aud: Configured in the mapper policy. By default the service account email. Claims from the incoming token can be transferred into the output token accoding to the mapper configuration. The outgoing claim size is limited. Outgoing claims size must be less than 4kB serialized as JSON without whitespace. Example header: { "alg": "RS256", "kid": "92a4265e14ab04d4d228a48d10d4ca31610936f8" } Example payload: { "iss": "https://accounts.google.com", "iat": 1517963104, "exp": 1517966704, "aud": "https://iamcredentials.googleapis.com/", "sub": "113475438248934895348", "my\_claims": { "additional\_claim": "value" } } 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.iam_credentials_v1.types.GenerateIdentityBindingAccessTokenResponse` 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 "generate_identity_binding_access_token" not in self._inner_api_calls: self._inner_api_calls[ "generate_identity_binding_access_token" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.generate_identity_binding_access_token, default_retry=self._method_configs[ "GenerateIdentityBindingAccessToken" ].retry, default_timeout=self._method_configs[ "GenerateIdentityBindingAccessToken" ].timeout, client_info=self._client_info, ) request = common_pb2.GenerateIdentityBindingAccessTokenRequest( name=name, scope=scope, jwt=jwt ) 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["generate_identity_binding_access_token"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def generate_identity_binding_access_token( self, name, scope, jwt, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Exchange a JWT signed by third party identity provider to an OAuth 2.0 access token Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `scope`: >>> scope = [] >>> >>> # TODO: Initialize `jwt`: >>> jwt = '' >>> >>> response = client.generate_identity_binding_access_token(name, scope, jwt) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. scope (list[str]): Code to identify the scopes to be included in the OAuth 2.0 access token. See https://developers.google.com/identity/protocols/googlescopes for more information. At least one value required. jwt (str): Required. Input token. Must be in JWT format according to RFC7523 (https://tools.ietf.org/html/rfc7523) and must have 'kid' field in the header. Supported signing algorithms: RS256 (RS512, ES256, ES512 coming soon). Mandatory payload fields (along the lines of RFC 7523, section 3): - iss: issuer of the token. Must provide a discovery document at $iss/.well-known/openid-configuration . The document needs to be formatted according to section 4.2 of the OpenID Connect Discovery 1.0 specification. - iat: Issue time in seconds since epoch. Must be in the past. - exp: Expiration time in seconds since epoch. Must be less than 48 hours after iat. We recommend to create tokens that last shorter than 6 hours to improve security unless business reasons mandate longer expiration times. Shorter token lifetimes are generally more secure since tokens that have been exfiltrated by attackers can be used for a shorter time. you can configure the maximum lifetime of the incoming token in the configuration of the mapper. The resulting Google token will expire within an hour or at "exp", whichever is earlier. - sub: JWT subject, identity asserted in the JWT. - aud: Configured in the mapper policy. By default the service account email. Claims from the incoming token can be transferred into the output token accoding to the mapper configuration. The outgoing claim size is limited. Outgoing claims size must be less than 4kB serialized as JSON without whitespace. Example header: { "alg": "RS256", "kid": "92a4265e14ab04d4d228a48d10d4ca31610936f8" } Example payload: { "iss": "https://accounts.google.com", "iat": 1517963104, "exp": 1517966704, "aud": "https://iamcredentials.googleapis.com/", "sub": "113475438248934895348", "my\_claims": { "additional\_claim": "value" } } 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.iam_credentials_v1.types.GenerateIdentityBindingAccessTokenResponse` 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 "generate_identity_binding_access_token" not in self._inner_api_calls: self._inner_api_calls[ "generate_identity_binding_access_token" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.generate_identity_binding_access_token, default_retry=self._method_configs[ "GenerateIdentityBindingAccessToken" ].retry, default_timeout=self._method_configs[ "GenerateIdentityBindingAccessToken" ].timeout, client_info=self._client_info, ) request = common_pb2.GenerateIdentityBindingAccessTokenRequest( name=name, scope=scope, jwt=jwt ) 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["generate_identity_binding_access_token"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "generate_identity_binding_access_token", "(", "self", ",", "name", ",", "scope", ",", "jwt", ",", "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", "\"generate_identity_binding_access_token\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"generate_identity_binding_access_token\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "generate_identity_binding_access_token", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"GenerateIdentityBindingAccessToken\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"GenerateIdentityBindingAccessToken\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "common_pb2", ".", "GenerateIdentityBindingAccessTokenRequest", "(", "name", "=", "name", ",", "scope", "=", "scope", ",", "jwt", "=", "jwt", ")", "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", "[", "\"generate_identity_binding_access_token\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Exchange a JWT signed by third party identity provider to an OAuth 2.0 access token Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]') >>> >>> # TODO: Initialize `scope`: >>> scope = [] >>> >>> # TODO: Initialize `jwt`: >>> jwt = '' >>> >>> response = client.generate_identity_binding_access_token(name, scope, jwt) Args: name (str): The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. scope (list[str]): Code to identify the scopes to be included in the OAuth 2.0 access token. See https://developers.google.com/identity/protocols/googlescopes for more information. At least one value required. jwt (str): Required. Input token. Must be in JWT format according to RFC7523 (https://tools.ietf.org/html/rfc7523) and must have 'kid' field in the header. Supported signing algorithms: RS256 (RS512, ES256, ES512 coming soon). Mandatory payload fields (along the lines of RFC 7523, section 3): - iss: issuer of the token. Must provide a discovery document at $iss/.well-known/openid-configuration . The document needs to be formatted according to section 4.2 of the OpenID Connect Discovery 1.0 specification. - iat: Issue time in seconds since epoch. Must be in the past. - exp: Expiration time in seconds since epoch. Must be less than 48 hours after iat. We recommend to create tokens that last shorter than 6 hours to improve security unless business reasons mandate longer expiration times. Shorter token lifetimes are generally more secure since tokens that have been exfiltrated by attackers can be used for a shorter time. you can configure the maximum lifetime of the incoming token in the configuration of the mapper. The resulting Google token will expire within an hour or at "exp", whichever is earlier. - sub: JWT subject, identity asserted in the JWT. - aud: Configured in the mapper policy. By default the service account email. Claims from the incoming token can be transferred into the output token accoding to the mapper configuration. The outgoing claim size is limited. Outgoing claims size must be less than 4kB serialized as JSON without whitespace. Example header: { "alg": "RS256", "kid": "92a4265e14ab04d4d228a48d10d4ca31610936f8" } Example payload: { "iss": "https://accounts.google.com", "iat": 1517963104, "exp": 1517966704, "aud": "https://iamcredentials.googleapis.com/", "sub": "113475438248934895348", "my\_claims": { "additional\_claim": "value" } } 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.iam_credentials_v1.types.GenerateIdentityBindingAccessTokenResponse` 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.
[ "Exchange", "a", "JWT", "signed", "by", "third", "party", "identity", "provider", "to", "an", "OAuth", "2", ".", "0", "access", "token" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/iam/google/cloud/iam_credentials_v1/gapic/iam_credentials_client.py#L559-L682
28,254
googleapis/google-cloud-python
datacatalog/google/cloud/datacatalog_v1beta1/gapic/data_catalog_client.py
DataCatalogClient.entry_path
def entry_path(cls, project, location, entry_group, entry): """Return a fully-qualified entry string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}", project=project, location=location, entry_group=entry_group, entry=entry, )
python
def entry_path(cls, project, location, entry_group, entry): """Return a fully-qualified entry string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}", project=project, location=location, entry_group=entry_group, entry=entry, )
[ "def", "entry_path", "(", "cls", ",", "project", ",", "location", ",", "entry_group", ",", "entry", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}\"", ",", "project", "=", "project", ",", "location", "=", "location", ",", "entry_group", "=", "entry_group", ",", "entry", "=", "entry", ",", ")" ]
Return a fully-qualified entry string.
[ "Return", "a", "fully", "-", "qualified", "entry", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datacatalog/google/cloud/datacatalog_v1beta1/gapic/data_catalog_client.py#L86-L94
28,255
googleapis/google-cloud-python
datacatalog/google/cloud/datacatalog_v1beta1/gapic/data_catalog_client.py
DataCatalogClient.lookup_entry
def lookup_entry( self, linked_resource=None, sql_resource=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Get an entry by target resource name. This method allows clients to use the resource name from the source Google Cloud Platform service to get the Cloud Data Catalog Entry. Example: >>> from google.cloud import datacatalog_v1beta1 >>> >>> client = datacatalog_v1beta1.DataCatalogClient() >>> >>> response = client.lookup_entry() Args: linked_resource (str): The full name of the Google Cloud Platform resource the Data Catalog entry represents. See: https://cloud.google.com/apis/design/resource\_names#full\_resource\_name Full names are case-sensitive. Examples: "//bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId". "//pubsub.googleapis.com/projects/projectId/topics/topicId" sql_resource (str): The SQL name of the entry. SQL names are case-sensitive. Examples: 1. cloud\_pubsub.project\_id.topic\_id 2. bigquery.project\_id.dataset\_id.table\_id 3. datacatalog.project\_id.location\_id.entry\_group\_id.entry\_id retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.datacatalog_v1beta1.types.Entry` 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 "lookup_entry" not in self._inner_api_calls: self._inner_api_calls[ "lookup_entry" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.lookup_entry, default_retry=self._method_configs["LookupEntry"].retry, default_timeout=self._method_configs["LookupEntry"].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( linked_resource=linked_resource, sql_resource=sql_resource ) request = datacatalog_pb2.LookupEntryRequest( linked_resource=linked_resource, sql_resource=sql_resource ) return self._inner_api_calls["lookup_entry"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def lookup_entry( self, linked_resource=None, sql_resource=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Get an entry by target resource name. This method allows clients to use the resource name from the source Google Cloud Platform service to get the Cloud Data Catalog Entry. Example: >>> from google.cloud import datacatalog_v1beta1 >>> >>> client = datacatalog_v1beta1.DataCatalogClient() >>> >>> response = client.lookup_entry() Args: linked_resource (str): The full name of the Google Cloud Platform resource the Data Catalog entry represents. See: https://cloud.google.com/apis/design/resource\_names#full\_resource\_name Full names are case-sensitive. Examples: "//bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId". "//pubsub.googleapis.com/projects/projectId/topics/topicId" sql_resource (str): The SQL name of the entry. SQL names are case-sensitive. Examples: 1. cloud\_pubsub.project\_id.topic\_id 2. bigquery.project\_id.dataset\_id.table\_id 3. datacatalog.project\_id.location\_id.entry\_group\_id.entry\_id retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.datacatalog_v1beta1.types.Entry` 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 "lookup_entry" not in self._inner_api_calls: self._inner_api_calls[ "lookup_entry" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.lookup_entry, default_retry=self._method_configs["LookupEntry"].retry, default_timeout=self._method_configs["LookupEntry"].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( linked_resource=linked_resource, sql_resource=sql_resource ) request = datacatalog_pb2.LookupEntryRequest( linked_resource=linked_resource, sql_resource=sql_resource ) return self._inner_api_calls["lookup_entry"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "lookup_entry", "(", "self", ",", "linked_resource", "=", "None", ",", "sql_resource", "=", "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", "\"lookup_entry\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"lookup_entry\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "lookup_entry", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"LookupEntry\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"LookupEntry\"", "]", ".", "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", "(", "linked_resource", "=", "linked_resource", ",", "sql_resource", "=", "sql_resource", ")", "request", "=", "datacatalog_pb2", ".", "LookupEntryRequest", "(", "linked_resource", "=", "linked_resource", ",", "sql_resource", "=", "sql_resource", ")", "return", "self", ".", "_inner_api_calls", "[", "\"lookup_entry\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Get an entry by target resource name. This method allows clients to use the resource name from the source Google Cloud Platform service to get the Cloud Data Catalog Entry. Example: >>> from google.cloud import datacatalog_v1beta1 >>> >>> client = datacatalog_v1beta1.DataCatalogClient() >>> >>> response = client.lookup_entry() Args: linked_resource (str): The full name of the Google Cloud Platform resource the Data Catalog entry represents. See: https://cloud.google.com/apis/design/resource\_names#full\_resource\_name Full names are case-sensitive. Examples: "//bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId". "//pubsub.googleapis.com/projects/projectId/topics/topicId" sql_resource (str): The SQL name of the entry. SQL names are case-sensitive. Examples: 1. cloud\_pubsub.project\_id.topic\_id 2. bigquery.project\_id.dataset\_id.table\_id 3. datacatalog.project\_id.location\_id.entry\_group\_id.entry\_id retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.datacatalog_v1beta1.types.Entry` 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.
[ "Get", "an", "entry", "by", "target", "resource", "name", ".", "This", "method", "allows", "clients", "to", "use", "the", "resource", "name", "from", "the", "source", "Google", "Cloud", "Platform", "service", "to", "get", "the", "Cloud", "Data", "Catalog", "Entry", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datacatalog/google/cloud/datacatalog_v1beta1/gapic/data_catalog_client.py#L195-L272
28,256
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/document.py
_get_document_path
def _get_document_path(client, path): """Convert a path tuple into a full path string. Of the form: ``projects/{project_id}/databases/{database_id}/... documents/{document_path}`` Args: client (~.firestore_v1beta1.client.Client): The client that holds configuration details and a GAPIC client object. path (Tuple[str, ...]): The components in a document path. Returns: str: The fully-qualified document path. """ parts = (client._database_string, "documents") + path return _helpers.DOCUMENT_PATH_DELIMITER.join(parts)
python
def _get_document_path(client, path): """Convert a path tuple into a full path string. Of the form: ``projects/{project_id}/databases/{database_id}/... documents/{document_path}`` Args: client (~.firestore_v1beta1.client.Client): The client that holds configuration details and a GAPIC client object. path (Tuple[str, ...]): The components in a document path. Returns: str: The fully-qualified document path. """ parts = (client._database_string, "documents") + path return _helpers.DOCUMENT_PATH_DELIMITER.join(parts)
[ "def", "_get_document_path", "(", "client", ",", "path", ")", ":", "parts", "=", "(", "client", ".", "_database_string", ",", "\"documents\"", ")", "+", "path", "return", "_helpers", ".", "DOCUMENT_PATH_DELIMITER", ".", "join", "(", "parts", ")" ]
Convert a path tuple into a full path string. Of the form: ``projects/{project_id}/databases/{database_id}/... documents/{document_path}`` Args: client (~.firestore_v1beta1.client.Client): The client that holds configuration details and a GAPIC client object. path (Tuple[str, ...]): The components in a document path. Returns: str: The fully-qualified document path.
[ "Convert", "a", "path", "tuple", "into", "a", "full", "path", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L695-L712
28,257
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/document.py
_consume_single_get
def _consume_single_get(response_iterator): """Consume a gRPC stream that should contain a single response. The stream will correspond to a ``BatchGetDocuments`` request made for a single document. Args: response_iterator (~google.cloud.exceptions.GrpcRendezvous): A streaming iterator returned from a ``BatchGetDocuments`` request. Returns: ~google.cloud.proto.firestore.v1beta1.\ firestore_pb2.BatchGetDocumentsResponse: The single "get" response in the batch. Raises: ValueError: If anything other than exactly one response is returned. """ # Calling ``list()`` consumes the entire iterator. all_responses = list(response_iterator) if len(all_responses) != 1: raise ValueError( "Unexpected response from `BatchGetDocumentsResponse`", all_responses, "Expected only one result", ) return all_responses[0]
python
def _consume_single_get(response_iterator): """Consume a gRPC stream that should contain a single response. The stream will correspond to a ``BatchGetDocuments`` request made for a single document. Args: response_iterator (~google.cloud.exceptions.GrpcRendezvous): A streaming iterator returned from a ``BatchGetDocuments`` request. Returns: ~google.cloud.proto.firestore.v1beta1.\ firestore_pb2.BatchGetDocumentsResponse: The single "get" response in the batch. Raises: ValueError: If anything other than exactly one response is returned. """ # Calling ``list()`` consumes the entire iterator. all_responses = list(response_iterator) if len(all_responses) != 1: raise ValueError( "Unexpected response from `BatchGetDocumentsResponse`", all_responses, "Expected only one result", ) return all_responses[0]
[ "def", "_consume_single_get", "(", "response_iterator", ")", ":", "# Calling ``list()`` consumes the entire iterator.", "all_responses", "=", "list", "(", "response_iterator", ")", "if", "len", "(", "all_responses", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Unexpected response from `BatchGetDocumentsResponse`\"", ",", "all_responses", ",", "\"Expected only one result\"", ",", ")", "return", "all_responses", "[", "0", "]" ]
Consume a gRPC stream that should contain a single response. The stream will correspond to a ``BatchGetDocuments`` request made for a single document. Args: response_iterator (~google.cloud.exceptions.GrpcRendezvous): A streaming iterator returned from a ``BatchGetDocuments`` request. Returns: ~google.cloud.proto.firestore.v1beta1.\ firestore_pb2.BatchGetDocumentsResponse: The single "get" response in the batch. Raises: ValueError: If anything other than exactly one response is returned.
[ "Consume", "a", "gRPC", "stream", "that", "should", "contain", "a", "single", "response", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L715-L743
28,258
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/document.py
DocumentReference._document_path
def _document_path(self): """Create and cache the full path for this document. Of the form: ``projects/{project_id}/databases/{database_id}/... documents/{document_path}`` Returns: str: The full document path. Raises: ValueError: If the current document reference has no ``client``. """ if self._document_path_internal is None: if self._client is None: raise ValueError("A document reference requires a `client`.") self._document_path_internal = _get_document_path(self._client, self._path) return self._document_path_internal
python
def _document_path(self): """Create and cache the full path for this document. Of the form: ``projects/{project_id}/databases/{database_id}/... documents/{document_path}`` Returns: str: The full document path. Raises: ValueError: If the current document reference has no ``client``. """ if self._document_path_internal is None: if self._client is None: raise ValueError("A document reference requires a `client`.") self._document_path_internal = _get_document_path(self._client, self._path) return self._document_path_internal
[ "def", "_document_path", "(", "self", ")", ":", "if", "self", ".", "_document_path_internal", "is", "None", ":", "if", "self", ".", "_client", "is", "None", ":", "raise", "ValueError", "(", "\"A document reference requires a `client`.\"", ")", "self", ".", "_document_path_internal", "=", "_get_document_path", "(", "self", ".", "_client", ",", "self", ".", "_path", ")", "return", "self", ".", "_document_path_internal" ]
Create and cache the full path for this document. Of the form: ``projects/{project_id}/databases/{database_id}/... documents/{document_path}`` Returns: str: The full document path. Raises: ValueError: If the current document reference has no ``client``.
[ "Create", "and", "cache", "the", "full", "path", "for", "this", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L130-L149
28,259
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/document.py
DocumentReference.collection
def collection(self, collection_id): """Create a sub-collection underneath the current document. Args: collection_id (str): The sub-collection identifier (sometimes referred to as the "kind"). Returns: ~.firestore_v1beta1.collection.CollectionReference: The child collection. """ child_path = self._path + (collection_id,) return self._client.collection(*child_path)
python
def collection(self, collection_id): """Create a sub-collection underneath the current document. Args: collection_id (str): The sub-collection identifier (sometimes referred to as the "kind"). Returns: ~.firestore_v1beta1.collection.CollectionReference: The child collection. """ child_path = self._path + (collection_id,) return self._client.collection(*child_path)
[ "def", "collection", "(", "self", ",", "collection_id", ")", ":", "child_path", "=", "self", ".", "_path", "+", "(", "collection_id", ",", ")", "return", "self", ".", "_client", ".", "collection", "(", "*", "child_path", ")" ]
Create a sub-collection underneath the current document. Args: collection_id (str): The sub-collection identifier (sometimes referred to as the "kind"). Returns: ~.firestore_v1beta1.collection.CollectionReference: The child collection.
[ "Create", "a", "sub", "-", "collection", "underneath", "the", "current", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L171-L183
28,260
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/document.py
DocumentReference.create
def create(self, document_data): """Create the current document in the Firestore database. Args: document_data (dict): Property names and values to use for creating a document. Returns: google.cloud.firestore_v1beta1.types.WriteResult: The write result corresponding to the committed document. A write result contains an ``update_time`` field. Raises: ~google.cloud.exceptions.Conflict: If the document already exists. """ batch = self._client.batch() batch.create(self, document_data) write_results = batch.commit() return _first_write_result(write_results)
python
def create(self, document_data): """Create the current document in the Firestore database. Args: document_data (dict): Property names and values to use for creating a document. Returns: google.cloud.firestore_v1beta1.types.WriteResult: The write result corresponding to the committed document. A write result contains an ``update_time`` field. Raises: ~google.cloud.exceptions.Conflict: If the document already exists. """ batch = self._client.batch() batch.create(self, document_data) write_results = batch.commit() return _first_write_result(write_results)
[ "def", "create", "(", "self", ",", "document_data", ")", ":", "batch", "=", "self", ".", "_client", ".", "batch", "(", ")", "batch", ".", "create", "(", "self", ",", "document_data", ")", "write_results", "=", "batch", ".", "commit", "(", ")", "return", "_first_write_result", "(", "write_results", ")" ]
Create the current document in the Firestore database. Args: document_data (dict): Property names and values to use for creating a document. Returns: google.cloud.firestore_v1beta1.types.WriteResult: The write result corresponding to the committed document. A write result contains an ``update_time`` field. Raises: ~google.cloud.exceptions.Conflict: If the document already exists.
[ "Create", "the", "current", "document", "in", "the", "Firestore", "database", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L185-L203
28,261
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/document.py
DocumentReference.set
def set(self, document_data, merge=False): """Replace the current document in the Firestore database. A write ``option`` can be specified to indicate preconditions of the "set" operation. If no ``option`` is specified and this document doesn't exist yet, this method will create it. Overwrites all content for the document with the fields in ``document_data``. This method performs almost the same functionality as :meth:`create`. The only difference is that this method doesn't make any requirements on the existence of the document (unless ``option`` is used), whereas as :meth:`create` will fail if the document already exists. Args: document_data (dict): Property names and values to use for replacing a document. merge (Optional[bool] or Optional[List<apispec>]): If True, apply merging instead of overwriting the state of the document. Returns: google.cloud.firestore_v1beta1.types.WriteResult: The write result corresponding to the committed document. A write result contains an ``update_time`` field. """ batch = self._client.batch() batch.set(self, document_data, merge=merge) write_results = batch.commit() return _first_write_result(write_results)
python
def set(self, document_data, merge=False): """Replace the current document in the Firestore database. A write ``option`` can be specified to indicate preconditions of the "set" operation. If no ``option`` is specified and this document doesn't exist yet, this method will create it. Overwrites all content for the document with the fields in ``document_data``. This method performs almost the same functionality as :meth:`create`. The only difference is that this method doesn't make any requirements on the existence of the document (unless ``option`` is used), whereas as :meth:`create` will fail if the document already exists. Args: document_data (dict): Property names and values to use for replacing a document. merge (Optional[bool] or Optional[List<apispec>]): If True, apply merging instead of overwriting the state of the document. Returns: google.cloud.firestore_v1beta1.types.WriteResult: The write result corresponding to the committed document. A write result contains an ``update_time`` field. """ batch = self._client.batch() batch.set(self, document_data, merge=merge) write_results = batch.commit() return _first_write_result(write_results)
[ "def", "set", "(", "self", ",", "document_data", ",", "merge", "=", "False", ")", ":", "batch", "=", "self", ".", "_client", ".", "batch", "(", ")", "batch", ".", "set", "(", "self", ",", "document_data", ",", "merge", "=", "merge", ")", "write_results", "=", "batch", ".", "commit", "(", ")", "return", "_first_write_result", "(", "write_results", ")" ]
Replace the current document in the Firestore database. A write ``option`` can be specified to indicate preconditions of the "set" operation. If no ``option`` is specified and this document doesn't exist yet, this method will create it. Overwrites all content for the document with the fields in ``document_data``. This method performs almost the same functionality as :meth:`create`. The only difference is that this method doesn't make any requirements on the existence of the document (unless ``option`` is used), whereas as :meth:`create` will fail if the document already exists. Args: document_data (dict): Property names and values to use for replacing a document. merge (Optional[bool] or Optional[List<apispec>]): If True, apply merging instead of overwriting the state of the document. Returns: google.cloud.firestore_v1beta1.types.WriteResult: The write result corresponding to the committed document. A write result contains an ``update_time`` field.
[ "Replace", "the", "current", "document", "in", "the", "Firestore", "database", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L205-L234
28,262
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/document.py
DocumentReference.update
def update(self, field_updates, option=None): """Update an existing document in the Firestore database. By default, this method verifies that the document exists on the server before making updates. A write ``option`` can be specified to override these preconditions. Each key in ``field_updates`` can either be a field name or a **field path** (For more information on **field paths**, see :meth:`~.firestore_v1beta1.client.Client.field_path`.) To illustrate this, consider a document with .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', }, 'other': True, } stored on the server. If the field name is used in the update: .. code-block:: python >>> field_updates = { ... 'foo': { ... 'quux': 800, ... }, ... } >>> document.update(field_updates) then all of ``foo`` will be overwritten on the server and the new value will be .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'quux': 800, }, 'other': True, } On the other hand, if a ``.``-delimited **field path** is used in the update: .. code-block:: python >>> field_updates = { ... 'foo.quux': 800, ... } >>> document.update(field_updates) then only ``foo.quux`` will be updated on the server and the field ``foo.bar`` will remain intact: .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', 'quux': 800, }, 'other': True, } .. warning:: A **field path** can only be used as a top-level key in ``field_updates``. To delete / remove a field from an existing document, use the :attr:`~.firestore_v1beta1.transforms.DELETE_FIELD` sentinel. So with the example above, sending .. code-block:: python >>> field_updates = { ... 'other': firestore.DELETE_FIELD, ... } >>> document.update(field_updates) would update the value on the server to: .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', }, } To set a field to the current time on the server when the update is received, use the :attr:`~.firestore_v1beta1.transforms.SERVER_TIMESTAMP` sentinel. Sending .. code-block:: python >>> field_updates = { ... 'foo.now': firestore.SERVER_TIMESTAMP, ... } >>> document.update(field_updates) would update the value on the server to: .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', 'now': datetime.datetime(2012, ...), }, 'other': True, } Args: field_updates (dict): Field names or paths to update and values to update with. option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. Returns: google.cloud.firestore_v1beta1.types.WriteResult: The write result corresponding to the updated document. A write result contains an ``update_time`` field. Raises: ~google.cloud.exceptions.NotFound: If the document does not exist. """ batch = self._client.batch() batch.update(self, field_updates, option=option) write_results = batch.commit() return _first_write_result(write_results)
python
def update(self, field_updates, option=None): """Update an existing document in the Firestore database. By default, this method verifies that the document exists on the server before making updates. A write ``option`` can be specified to override these preconditions. Each key in ``field_updates`` can either be a field name or a **field path** (For more information on **field paths**, see :meth:`~.firestore_v1beta1.client.Client.field_path`.) To illustrate this, consider a document with .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', }, 'other': True, } stored on the server. If the field name is used in the update: .. code-block:: python >>> field_updates = { ... 'foo': { ... 'quux': 800, ... }, ... } >>> document.update(field_updates) then all of ``foo`` will be overwritten on the server and the new value will be .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'quux': 800, }, 'other': True, } On the other hand, if a ``.``-delimited **field path** is used in the update: .. code-block:: python >>> field_updates = { ... 'foo.quux': 800, ... } >>> document.update(field_updates) then only ``foo.quux`` will be updated on the server and the field ``foo.bar`` will remain intact: .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', 'quux': 800, }, 'other': True, } .. warning:: A **field path** can only be used as a top-level key in ``field_updates``. To delete / remove a field from an existing document, use the :attr:`~.firestore_v1beta1.transforms.DELETE_FIELD` sentinel. So with the example above, sending .. code-block:: python >>> field_updates = { ... 'other': firestore.DELETE_FIELD, ... } >>> document.update(field_updates) would update the value on the server to: .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', }, } To set a field to the current time on the server when the update is received, use the :attr:`~.firestore_v1beta1.transforms.SERVER_TIMESTAMP` sentinel. Sending .. code-block:: python >>> field_updates = { ... 'foo.now': firestore.SERVER_TIMESTAMP, ... } >>> document.update(field_updates) would update the value on the server to: .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', 'now': datetime.datetime(2012, ...), }, 'other': True, } Args: field_updates (dict): Field names or paths to update and values to update with. option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. Returns: google.cloud.firestore_v1beta1.types.WriteResult: The write result corresponding to the updated document. A write result contains an ``update_time`` field. Raises: ~google.cloud.exceptions.NotFound: If the document does not exist. """ batch = self._client.batch() batch.update(self, field_updates, option=option) write_results = batch.commit() return _first_write_result(write_results)
[ "def", "update", "(", "self", ",", "field_updates", ",", "option", "=", "None", ")", ":", "batch", "=", "self", ".", "_client", ".", "batch", "(", ")", "batch", ".", "update", "(", "self", ",", "field_updates", ",", "option", "=", "option", ")", "write_results", "=", "batch", ".", "commit", "(", ")", "return", "_first_write_result", "(", "write_results", ")" ]
Update an existing document in the Firestore database. By default, this method verifies that the document exists on the server before making updates. A write ``option`` can be specified to override these preconditions. Each key in ``field_updates`` can either be a field name or a **field path** (For more information on **field paths**, see :meth:`~.firestore_v1beta1.client.Client.field_path`.) To illustrate this, consider a document with .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', }, 'other': True, } stored on the server. If the field name is used in the update: .. code-block:: python >>> field_updates = { ... 'foo': { ... 'quux': 800, ... }, ... } >>> document.update(field_updates) then all of ``foo`` will be overwritten on the server and the new value will be .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'quux': 800, }, 'other': True, } On the other hand, if a ``.``-delimited **field path** is used in the update: .. code-block:: python >>> field_updates = { ... 'foo.quux': 800, ... } >>> document.update(field_updates) then only ``foo.quux`` will be updated on the server and the field ``foo.bar`` will remain intact: .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', 'quux': 800, }, 'other': True, } .. warning:: A **field path** can only be used as a top-level key in ``field_updates``. To delete / remove a field from an existing document, use the :attr:`~.firestore_v1beta1.transforms.DELETE_FIELD` sentinel. So with the example above, sending .. code-block:: python >>> field_updates = { ... 'other': firestore.DELETE_FIELD, ... } >>> document.update(field_updates) would update the value on the server to: .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', }, } To set a field to the current time on the server when the update is received, use the :attr:`~.firestore_v1beta1.transforms.SERVER_TIMESTAMP` sentinel. Sending .. code-block:: python >>> field_updates = { ... 'foo.now': firestore.SERVER_TIMESTAMP, ... } >>> document.update(field_updates) would update the value on the server to: .. code-block:: python >>> snapshot = document.get() >>> snapshot.to_dict() { 'foo': { 'bar': 'baz', 'now': datetime.datetime(2012, ...), }, 'other': True, } Args: field_updates (dict): Field names or paths to update and values to update with. option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. Returns: google.cloud.firestore_v1beta1.types.WriteResult: The write result corresponding to the updated document. A write result contains an ``update_time`` field. Raises: ~google.cloud.exceptions.NotFound: If the document does not exist.
[ "Update", "an", "existing", "document", "in", "the", "Firestore", "database", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L236-L381
28,263
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/document.py
DocumentReference.delete
def delete(self, option=None): """Delete the current document in the Firestore database. Args: option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. Returns: google.protobuf.timestamp_pb2.Timestamp: The time that the delete request was received by the server. If the document did not exist when the delete was sent (i.e. nothing was deleted), this method will still succeed and will still return the time that the request was received by the server. """ write_pb = _helpers.pb_for_delete(self._document_path, option) commit_response = self._client._firestore_api.commit( self._client._database_string, [write_pb], transaction=None, metadata=self._client._rpc_metadata, ) return commit_response.commit_time
python
def delete(self, option=None): """Delete the current document in the Firestore database. Args: option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. Returns: google.protobuf.timestamp_pb2.Timestamp: The time that the delete request was received by the server. If the document did not exist when the delete was sent (i.e. nothing was deleted), this method will still succeed and will still return the time that the request was received by the server. """ write_pb = _helpers.pb_for_delete(self._document_path, option) commit_response = self._client._firestore_api.commit( self._client._database_string, [write_pb], transaction=None, metadata=self._client._rpc_metadata, ) return commit_response.commit_time
[ "def", "delete", "(", "self", ",", "option", "=", "None", ")", ":", "write_pb", "=", "_helpers", ".", "pb_for_delete", "(", "self", ".", "_document_path", ",", "option", ")", "commit_response", "=", "self", ".", "_client", ".", "_firestore_api", ".", "commit", "(", "self", ".", "_client", ".", "_database_string", ",", "[", "write_pb", "]", ",", "transaction", "=", "None", ",", "metadata", "=", "self", ".", "_client", ".", "_rpc_metadata", ",", ")", "return", "commit_response", ".", "commit_time" ]
Delete the current document in the Firestore database. Args: option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. Returns: google.protobuf.timestamp_pb2.Timestamp: The time that the delete request was received by the server. If the document did not exist when the delete was sent (i.e. nothing was deleted), this method will still succeed and will still return the time that the request was received by the server.
[ "Delete", "the", "current", "document", "in", "the", "Firestore", "database", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L383-L406
28,264
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/document.py
DocumentReference.get
def get(self, field_paths=None, transaction=None): """Retrieve a snapshot of the current document. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. If a ``transaction`` is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed). Args: field_paths (Optional[Iterable[str, ...]]): An iterable of field paths (``.``-delimited list of field names) to use as a projection of document fields in the returned results. If no value is provided, all fields will be returned. transaction (Optional[~.firestore_v1beta1.transaction.\ Transaction]): An existing transaction that this reference will be retrieved in. Returns: ~.firestore_v1beta1.document.DocumentSnapshot: A snapshot of the current document. If the document does not exist at the time of `snapshot`, the snapshot `reference`, `data`, `update_time`, and `create_time` attributes will all be `None` and `exists` will be `False`. """ if isinstance(field_paths, six.string_types): raise ValueError("'field_paths' must be a sequence of paths, not a string.") if field_paths is not None: mask = common_pb2.DocumentMask(field_paths=sorted(field_paths)) else: mask = None firestore_api = self._client._firestore_api try: document_pb = firestore_api.get_document( self._document_path, mask=mask, transaction=_helpers.get_transaction_id(transaction), metadata=self._client._rpc_metadata, ) except exceptions.NotFound: data = None exists = False create_time = None update_time = None else: data = _helpers.decode_dict(document_pb.fields, self._client) exists = True create_time = document_pb.create_time update_time = document_pb.update_time return DocumentSnapshot( reference=self, data=data, exists=exists, read_time=None, # No server read_time available create_time=create_time, update_time=update_time, )
python
def get(self, field_paths=None, transaction=None): """Retrieve a snapshot of the current document. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. If a ``transaction`` is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed). Args: field_paths (Optional[Iterable[str, ...]]): An iterable of field paths (``.``-delimited list of field names) to use as a projection of document fields in the returned results. If no value is provided, all fields will be returned. transaction (Optional[~.firestore_v1beta1.transaction.\ Transaction]): An existing transaction that this reference will be retrieved in. Returns: ~.firestore_v1beta1.document.DocumentSnapshot: A snapshot of the current document. If the document does not exist at the time of `snapshot`, the snapshot `reference`, `data`, `update_time`, and `create_time` attributes will all be `None` and `exists` will be `False`. """ if isinstance(field_paths, six.string_types): raise ValueError("'field_paths' must be a sequence of paths, not a string.") if field_paths is not None: mask = common_pb2.DocumentMask(field_paths=sorted(field_paths)) else: mask = None firestore_api = self._client._firestore_api try: document_pb = firestore_api.get_document( self._document_path, mask=mask, transaction=_helpers.get_transaction_id(transaction), metadata=self._client._rpc_metadata, ) except exceptions.NotFound: data = None exists = False create_time = None update_time = None else: data = _helpers.decode_dict(document_pb.fields, self._client) exists = True create_time = document_pb.create_time update_time = document_pb.update_time return DocumentSnapshot( reference=self, data=data, exists=exists, read_time=None, # No server read_time available create_time=create_time, update_time=update_time, )
[ "def", "get", "(", "self", ",", "field_paths", "=", "None", ",", "transaction", "=", "None", ")", ":", "if", "isinstance", "(", "field_paths", ",", "six", ".", "string_types", ")", ":", "raise", "ValueError", "(", "\"'field_paths' must be a sequence of paths, not a string.\"", ")", "if", "field_paths", "is", "not", "None", ":", "mask", "=", "common_pb2", ".", "DocumentMask", "(", "field_paths", "=", "sorted", "(", "field_paths", ")", ")", "else", ":", "mask", "=", "None", "firestore_api", "=", "self", ".", "_client", ".", "_firestore_api", "try", ":", "document_pb", "=", "firestore_api", ".", "get_document", "(", "self", ".", "_document_path", ",", "mask", "=", "mask", ",", "transaction", "=", "_helpers", ".", "get_transaction_id", "(", "transaction", ")", ",", "metadata", "=", "self", ".", "_client", ".", "_rpc_metadata", ",", ")", "except", "exceptions", ".", "NotFound", ":", "data", "=", "None", "exists", "=", "False", "create_time", "=", "None", "update_time", "=", "None", "else", ":", "data", "=", "_helpers", ".", "decode_dict", "(", "document_pb", ".", "fields", ",", "self", ".", "_client", ")", "exists", "=", "True", "create_time", "=", "document_pb", ".", "create_time", "update_time", "=", "document_pb", ".", "update_time", "return", "DocumentSnapshot", "(", "reference", "=", "self", ",", "data", "=", "data", ",", "exists", "=", "exists", ",", "read_time", "=", "None", ",", "# No server read_time available", "create_time", "=", "create_time", ",", "update_time", "=", "update_time", ",", ")" ]
Retrieve a snapshot of the current document. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. If a ``transaction`` is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed). Args: field_paths (Optional[Iterable[str, ...]]): An iterable of field paths (``.``-delimited list of field names) to use as a projection of document fields in the returned results. If no value is provided, all fields will be returned. transaction (Optional[~.firestore_v1beta1.transaction.\ Transaction]): An existing transaction that this reference will be retrieved in. Returns: ~.firestore_v1beta1.document.DocumentSnapshot: A snapshot of the current document. If the document does not exist at the time of `snapshot`, the snapshot `reference`, `data`, `update_time`, and `create_time` attributes will all be `None` and `exists` will be `False`.
[ "Retrieve", "a", "snapshot", "of", "the", "current", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L408-L468
28,265
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/document.py
DocumentReference.collections
def collections(self, page_size=None): """List subcollections of the current document. Args: page_size (Optional[int]]): The maximum number of collections in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. Returns: Sequence[~.firestore_v1beta1.collection.CollectionReference]: iterator of subcollections of the current document. If the document does not exist at the time of `snapshot`, the iterator will be empty """ iterator = self._client._firestore_api.list_collection_ids( self._document_path, page_size=page_size, metadata=self._client._rpc_metadata, ) iterator.document = self iterator.item_to_value = _item_to_collection_ref return iterator
python
def collections(self, page_size=None): """List subcollections of the current document. Args: page_size (Optional[int]]): The maximum number of collections in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. Returns: Sequence[~.firestore_v1beta1.collection.CollectionReference]: iterator of subcollections of the current document. If the document does not exist at the time of `snapshot`, the iterator will be empty """ iterator = self._client._firestore_api.list_collection_ids( self._document_path, page_size=page_size, metadata=self._client._rpc_metadata, ) iterator.document = self iterator.item_to_value = _item_to_collection_ref return iterator
[ "def", "collections", "(", "self", ",", "page_size", "=", "None", ")", ":", "iterator", "=", "self", ".", "_client", ".", "_firestore_api", ".", "list_collection_ids", "(", "self", ".", "_document_path", ",", "page_size", "=", "page_size", ",", "metadata", "=", "self", ".", "_client", ".", "_rpc_metadata", ",", ")", "iterator", ".", "document", "=", "self", "iterator", ".", "item_to_value", "=", "_item_to_collection_ref", "return", "iterator" ]
List subcollections of the current document. Args: page_size (Optional[int]]): The maximum number of collections in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. Returns: Sequence[~.firestore_v1beta1.collection.CollectionReference]: iterator of subcollections of the current document. If the document does not exist at the time of `snapshot`, the iterator will be empty
[ "List", "subcollections", "of", "the", "current", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L470-L491
28,266
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/document.py
DocumentSnapshot.get
def get(self, field_path): """Get a value from the snapshot data. If the data is nested, for example: .. code-block:: python >>> snapshot.to_dict() { 'top1': { 'middle2': { 'bottom3': 20, 'bottom4': 22, }, 'middle5': True, }, 'top6': b'\x00\x01 foo', } a **field path** can be used to access the nested data. For example: .. code-block:: python >>> snapshot.get('top1') { 'middle2': { 'bottom3': 20, 'bottom4': 22, }, 'middle5': True, } >>> snapshot.get('top1.middle2') { 'bottom3': 20, 'bottom4': 22, } >>> snapshot.get('top1.middle2.bottom3') 20 See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. A copy is returned since the data may contain mutable values, but the data stored in the snapshot must remain immutable. Args: field_path (str): A field path (``.``-delimited list of field names). Returns: Any or None: (A copy of) the value stored for the ``field_path`` or None if snapshot document does not exist. Raises: KeyError: If the ``field_path`` does not match nested data in the snapshot. """ if not self._exists: return None nested_data = field_path_module.get_nested_value(field_path, self._data) return copy.deepcopy(nested_data)
python
def get(self, field_path): """Get a value from the snapshot data. If the data is nested, for example: .. code-block:: python >>> snapshot.to_dict() { 'top1': { 'middle2': { 'bottom3': 20, 'bottom4': 22, }, 'middle5': True, }, 'top6': b'\x00\x01 foo', } a **field path** can be used to access the nested data. For example: .. code-block:: python >>> snapshot.get('top1') { 'middle2': { 'bottom3': 20, 'bottom4': 22, }, 'middle5': True, } >>> snapshot.get('top1.middle2') { 'bottom3': 20, 'bottom4': 22, } >>> snapshot.get('top1.middle2.bottom3') 20 See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. A copy is returned since the data may contain mutable values, but the data stored in the snapshot must remain immutable. Args: field_path (str): A field path (``.``-delimited list of field names). Returns: Any or None: (A copy of) the value stored for the ``field_path`` or None if snapshot document does not exist. Raises: KeyError: If the ``field_path`` does not match nested data in the snapshot. """ if not self._exists: return None nested_data = field_path_module.get_nested_value(field_path, self._data) return copy.deepcopy(nested_data)
[ "def", "get", "(", "self", ",", "field_path", ")", ":", "if", "not", "self", ".", "_exists", ":", "return", "None", "nested_data", "=", "field_path_module", ".", "get_nested_value", "(", "field_path", ",", "self", ".", "_data", ")", "return", "copy", ".", "deepcopy", "(", "nested_data", ")" ]
Get a value from the snapshot data. If the data is nested, for example: .. code-block:: python >>> snapshot.to_dict() { 'top1': { 'middle2': { 'bottom3': 20, 'bottom4': 22, }, 'middle5': True, }, 'top6': b'\x00\x01 foo', } a **field path** can be used to access the nested data. For example: .. code-block:: python >>> snapshot.get('top1') { 'middle2': { 'bottom3': 20, 'bottom4': 22, }, 'middle5': True, } >>> snapshot.get('top1.middle2') { 'bottom3': 20, 'bottom4': 22, } >>> snapshot.get('top1.middle2.bottom3') 20 See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. A copy is returned since the data may contain mutable values, but the data stored in the snapshot must remain immutable. Args: field_path (str): A field path (``.``-delimited list of field names). Returns: Any or None: (A copy of) the value stored for the ``field_path`` or None if snapshot document does not exist. Raises: KeyError: If the ``field_path`` does not match nested data in the snapshot.
[ "Get", "a", "value", "from", "the", "snapshot", "data", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L615-L677
28,267
googleapis/google-cloud-python
spanner/google/cloud/spanner_admin_database_v1/gapic/database_admin_client.py
DatabaseAdminClient.database_path
def database_path(cls, project, instance, database): """Return a fully-qualified database string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/databases/{database}", project=project, instance=instance, database=database, )
python
def database_path(cls, project, instance, database): """Return a fully-qualified database string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/databases/{database}", project=project, instance=instance, database=database, )
[ "def", "database_path", "(", "cls", ",", "project", ",", "instance", ",", "database", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/instances/{instance}/databases/{database}\"", ",", "project", "=", "project", ",", "instance", "=", "instance", ",", "database", "=", "database", ",", ")" ]
Return a fully-qualified database string.
[ "Return", "a", "fully", "-", "qualified", "database", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_admin_database_v1/gapic/database_admin_client.py#L95-L102
28,268
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/client.py
Client.list_instances
def list_instances(self): """List instances owned by the project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_instances] :end-before: [END bigtable_list_instances] :rtype: tuple :returns: (instances, failed_locations), where 'instances' is list of :class:`google.cloud.bigtable.instance.Instance`, and 'failed_locations' is a list of locations which could not be resolved. """ resp = self.instance_admin_client.list_instances(self.project_path) instances = [Instance.from_pb(instance, self) for instance in resp.instances] return instances, resp.failed_locations
python
def list_instances(self): """List instances owned by the project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_instances] :end-before: [END bigtable_list_instances] :rtype: tuple :returns: (instances, failed_locations), where 'instances' is list of :class:`google.cloud.bigtable.instance.Instance`, and 'failed_locations' is a list of locations which could not be resolved. """ resp = self.instance_admin_client.list_instances(self.project_path) instances = [Instance.from_pb(instance, self) for instance in resp.instances] return instances, resp.failed_locations
[ "def", "list_instances", "(", "self", ")", ":", "resp", "=", "self", ".", "instance_admin_client", ".", "list_instances", "(", "self", ".", "project_path", ")", "instances", "=", "[", "Instance", ".", "from_pb", "(", "instance", ",", "self", ")", "for", "instance", "in", "resp", ".", "instances", "]", "return", "instances", ",", "resp", ".", "failed_locations" ]
List instances owned by the project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_instances] :end-before: [END bigtable_list_instances] :rtype: tuple :returns: (instances, failed_locations), where 'instances' is list of :class:`google.cloud.bigtable.instance.Instance`, and 'failed_locations' is a list of locations which could not be resolved.
[ "List", "instances", "owned", "by", "the", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/client.py#L302-L320
28,269
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/client.py
Client.list_clusters
def list_clusters(self): """List the clusters in the project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_clusters_in_project] :end-before: [END bigtable_list_clusters_in_project] :rtype: tuple :returns: (clusters, failed_locations), where 'clusters' is list of :class:`google.cloud.bigtable.instance.Cluster`, and 'failed_locations' is a list of strings representing locations which could not be resolved. """ resp = self.instance_admin_client.list_clusters( self.instance_admin_client.instance_path(self.project, "-") ) clusters = [] instances = {} for cluster in resp.clusters: match_cluster_name = _CLUSTER_NAME_RE.match(cluster.name) instance_id = match_cluster_name.group("instance") if instance_id not in instances: instances[instance_id] = self.instance(instance_id) clusters.append(Cluster.from_pb(cluster, instances[instance_id])) return clusters, resp.failed_locations
python
def list_clusters(self): """List the clusters in the project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_clusters_in_project] :end-before: [END bigtable_list_clusters_in_project] :rtype: tuple :returns: (clusters, failed_locations), where 'clusters' is list of :class:`google.cloud.bigtable.instance.Cluster`, and 'failed_locations' is a list of strings representing locations which could not be resolved. """ resp = self.instance_admin_client.list_clusters( self.instance_admin_client.instance_path(self.project, "-") ) clusters = [] instances = {} for cluster in resp.clusters: match_cluster_name = _CLUSTER_NAME_RE.match(cluster.name) instance_id = match_cluster_name.group("instance") if instance_id not in instances: instances[instance_id] = self.instance(instance_id) clusters.append(Cluster.from_pb(cluster, instances[instance_id])) return clusters, resp.failed_locations
[ "def", "list_clusters", "(", "self", ")", ":", "resp", "=", "self", ".", "instance_admin_client", ".", "list_clusters", "(", "self", ".", "instance_admin_client", ".", "instance_path", "(", "self", ".", "project", ",", "\"-\"", ")", ")", "clusters", "=", "[", "]", "instances", "=", "{", "}", "for", "cluster", "in", "resp", ".", "clusters", ":", "match_cluster_name", "=", "_CLUSTER_NAME_RE", ".", "match", "(", "cluster", ".", "name", ")", "instance_id", "=", "match_cluster_name", ".", "group", "(", "\"instance\"", ")", "if", "instance_id", "not", "in", "instances", ":", "instances", "[", "instance_id", "]", "=", "self", ".", "instance", "(", "instance_id", ")", "clusters", ".", "append", "(", "Cluster", ".", "from_pb", "(", "cluster", ",", "instances", "[", "instance_id", "]", ")", ")", "return", "clusters", ",", "resp", ".", "failed_locations" ]
List the clusters in the project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_clusters_in_project] :end-before: [END bigtable_list_clusters_in_project] :rtype: tuple :returns: (clusters, failed_locations), where 'clusters' is list of :class:`google.cloud.bigtable.instance.Cluster`, and 'failed_locations' is a list of strings representing locations which could not be resolved.
[ "List", "the", "clusters", "in", "the", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/client.py#L322-L349
28,270
googleapis/google-cloud-python
container/google/cloud/container_v1/gapic/cluster_manager_client.py
ClusterManagerClient.list_clusters
def list_clusters( self, project_id, zone, parent=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists all clusters owned by a project in either the specified zone or all zones. Example: >>> from google.cloud import container_v1 >>> >>> client = container_v1.ClusterManagerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `zone`: >>> zone = '' >>> >>> response = client.list_clusters(project_id, zone) Args: project_id (str): Deprecated. The Google Developers Console `project ID or project number <https://support.google.com/cloud/answer/6158840>`__. This field has been deprecated and replaced by the parent field. zone (str): Deprecated. The name of the Google Compute Engine `zone <https://cloud.google.com/compute/docs/zones#available>`__ in which the cluster resides, or "-" for all zones. This field has been deprecated and replaced by the parent field. parent (str): The parent (project and location) where the clusters will be listed. Specified in the format 'projects/*/locations/*'. Location "-" matches all zones and all regions. 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.container_v1.types.ListClustersResponse` 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 "list_clusters" not in self._inner_api_calls: self._inner_api_calls[ "list_clusters" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_clusters, default_retry=self._method_configs["ListClusters"].retry, default_timeout=self._method_configs["ListClusters"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.ListClustersRequest( project_id=project_id, zone=zone, parent=parent ) return self._inner_api_calls["list_clusters"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def list_clusters( self, project_id, zone, parent=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists all clusters owned by a project in either the specified zone or all zones. Example: >>> from google.cloud import container_v1 >>> >>> client = container_v1.ClusterManagerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `zone`: >>> zone = '' >>> >>> response = client.list_clusters(project_id, zone) Args: project_id (str): Deprecated. The Google Developers Console `project ID or project number <https://support.google.com/cloud/answer/6158840>`__. This field has been deprecated and replaced by the parent field. zone (str): Deprecated. The name of the Google Compute Engine `zone <https://cloud.google.com/compute/docs/zones#available>`__ in which the cluster resides, or "-" for all zones. This field has been deprecated and replaced by the parent field. parent (str): The parent (project and location) where the clusters will be listed. Specified in the format 'projects/*/locations/*'. Location "-" matches all zones and all regions. 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.container_v1.types.ListClustersResponse` 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 "list_clusters" not in self._inner_api_calls: self._inner_api_calls[ "list_clusters" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_clusters, default_retry=self._method_configs["ListClusters"].retry, default_timeout=self._method_configs["ListClusters"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.ListClustersRequest( project_id=project_id, zone=zone, parent=parent ) return self._inner_api_calls["list_clusters"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "list_clusters", "(", "self", ",", "project_id", ",", "zone", ",", "parent", "=", "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_clusters\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"list_clusters\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "list_clusters", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"ListClusters\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"ListClusters\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "cluster_service_pb2", ".", "ListClustersRequest", "(", "project_id", "=", "project_id", ",", "zone", "=", "zone", ",", "parent", "=", "parent", ")", "return", "self", ".", "_inner_api_calls", "[", "\"list_clusters\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Lists all clusters owned by a project in either the specified zone or all zones. Example: >>> from google.cloud import container_v1 >>> >>> client = container_v1.ClusterManagerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `zone`: >>> zone = '' >>> >>> response = client.list_clusters(project_id, zone) Args: project_id (str): Deprecated. The Google Developers Console `project ID or project number <https://support.google.com/cloud/answer/6158840>`__. This field has been deprecated and replaced by the parent field. zone (str): Deprecated. The name of the Google Compute Engine `zone <https://cloud.google.com/compute/docs/zones#available>`__ in which the cluster resides, or "-" for all zones. This field has been deprecated and replaced by the parent field. parent (str): The parent (project and location) where the clusters will be listed. Specified in the format 'projects/*/locations/*'. Location "-" matches all zones and all regions. 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.container_v1.types.ListClustersResponse` 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.
[ "Lists", "all", "clusters", "owned", "by", "a", "project", "in", "either", "the", "specified", "zone", "or", "all", "zones", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/container/google/cloud/container_v1/gapic/cluster_manager_client.py#L169-L241
28,271
googleapis/google-cloud-python
container/google/cloud/container_v1/gapic/cluster_manager_client.py
ClusterManagerClient.get_cluster
def get_cluster( self, project_id, zone, cluster_id, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the details of a specific cluster. Example: >>> from google.cloud import container_v1 >>> >>> client = container_v1.ClusterManagerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `zone`: >>> zone = '' >>> >>> # TODO: Initialize `cluster_id`: >>> cluster_id = '' >>> >>> response = client.get_cluster(project_id, zone, cluster_id) Args: project_id (str): Deprecated. The Google Developers Console `project ID or project number <https://support.google.com/cloud/answer/6158840>`__. This field has been deprecated and replaced by the name field. zone (str): Deprecated. The name of the Google Compute Engine `zone <https://cloud.google.com/compute/docs/zones#available>`__ in which the cluster resides. This field has been deprecated and replaced by the name field. cluster_id (str): Deprecated. The name of the cluster to retrieve. This field has been deprecated and replaced by the name field. name (str): The name (project, location, cluster) of the cluster to retrieve. Specified in the format 'projects/*/locations/*/clusters/\*'. 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.container_v1.types.Cluster` 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_cluster" not in self._inner_api_calls: self._inner_api_calls[ "get_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_cluster, default_retry=self._method_configs["GetCluster"].retry, default_timeout=self._method_configs["GetCluster"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.GetClusterRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, name=name ) return self._inner_api_calls["get_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def get_cluster( self, project_id, zone, cluster_id, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the details of a specific cluster. Example: >>> from google.cloud import container_v1 >>> >>> client = container_v1.ClusterManagerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `zone`: >>> zone = '' >>> >>> # TODO: Initialize `cluster_id`: >>> cluster_id = '' >>> >>> response = client.get_cluster(project_id, zone, cluster_id) Args: project_id (str): Deprecated. The Google Developers Console `project ID or project number <https://support.google.com/cloud/answer/6158840>`__. This field has been deprecated and replaced by the name field. zone (str): Deprecated. The name of the Google Compute Engine `zone <https://cloud.google.com/compute/docs/zones#available>`__ in which the cluster resides. This field has been deprecated and replaced by the name field. cluster_id (str): Deprecated. The name of the cluster to retrieve. This field has been deprecated and replaced by the name field. name (str): The name (project, location, cluster) of the cluster to retrieve. Specified in the format 'projects/*/locations/*/clusters/\*'. 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.container_v1.types.Cluster` 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_cluster" not in self._inner_api_calls: self._inner_api_calls[ "get_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_cluster, default_retry=self._method_configs["GetCluster"].retry, default_timeout=self._method_configs["GetCluster"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.GetClusterRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, name=name ) return self._inner_api_calls["get_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "get_cluster", "(", "self", ",", "project_id", ",", "zone", ",", "cluster_id", ",", "name", "=", "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_cluster\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"get_cluster\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "get_cluster", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"GetCluster\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"GetCluster\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "cluster_service_pb2", ".", "GetClusterRequest", "(", "project_id", "=", "project_id", ",", "zone", "=", "zone", ",", "cluster_id", "=", "cluster_id", ",", "name", "=", "name", ")", "return", "self", ".", "_inner_api_calls", "[", "\"get_cluster\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Gets the details of a specific cluster. Example: >>> from google.cloud import container_v1 >>> >>> client = container_v1.ClusterManagerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `zone`: >>> zone = '' >>> >>> # TODO: Initialize `cluster_id`: >>> cluster_id = '' >>> >>> response = client.get_cluster(project_id, zone, cluster_id) Args: project_id (str): Deprecated. The Google Developers Console `project ID or project number <https://support.google.com/cloud/answer/6158840>`__. This field has been deprecated and replaced by the name field. zone (str): Deprecated. The name of the Google Compute Engine `zone <https://cloud.google.com/compute/docs/zones#available>`__ in which the cluster resides. This field has been deprecated and replaced by the name field. cluster_id (str): Deprecated. The name of the cluster to retrieve. This field has been deprecated and replaced by the name field. name (str): The name (project, location, cluster) of the cluster to retrieve. Specified in the format 'projects/*/locations/*/clusters/\*'. 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.container_v1.types.Cluster` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Gets", "the", "details", "of", "a", "specific", "cluster", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/container/google/cloud/container_v1/gapic/cluster_manager_client.py#L243-L319
28,272
googleapis/google-cloud-python
container/google/cloud/container_v1/gapic/cluster_manager_client.py
ClusterManagerClient.set_labels
def set_labels( self, project_id, zone, cluster_id, resource_labels, label_fingerprint, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Sets labels on a cluster. Example: >>> from google.cloud import container_v1 >>> >>> client = container_v1.ClusterManagerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `zone`: >>> zone = '' >>> >>> # TODO: Initialize `cluster_id`: >>> cluster_id = '' >>> >>> # TODO: Initialize `resource_labels`: >>> resource_labels = {} >>> >>> # TODO: Initialize `label_fingerprint`: >>> label_fingerprint = '' >>> >>> response = client.set_labels(project_id, zone, cluster_id, resource_labels, label_fingerprint) Args: project_id (str): Deprecated. The Google Developers Console `project ID or project number <https://developers.google.com/console/help/new/#projectnumber>`__. This field has been deprecated and replaced by the name field. zone (str): Deprecated. The name of the Google Compute Engine `zone <https://cloud.google.com/compute/docs/zones#available>`__ in which the cluster resides. This field has been deprecated and replaced by the name field. cluster_id (str): Deprecated. The name of the cluster. This field has been deprecated and replaced by the name field. resource_labels (dict[str -> str]): The labels to set for that cluster. label_fingerprint (str): The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Kubernetes Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels. Make a <code>get()</code> request to the resource to get the latest fingerprint. name (str): The name (project, location, cluster id) of the cluster to set labels. Specified in the format 'projects/*/locations/*/clusters/\*'. 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.container_v1.types.Operation` 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 "set_labels" not in self._inner_api_calls: self._inner_api_calls[ "set_labels" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_labels, default_retry=self._method_configs["SetLabels"].retry, default_timeout=self._method_configs["SetLabels"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetLabelsRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, resource_labels=resource_labels, label_fingerprint=label_fingerprint, name=name, ) return self._inner_api_calls["set_labels"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def set_labels( self, project_id, zone, cluster_id, resource_labels, label_fingerprint, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Sets labels on a cluster. Example: >>> from google.cloud import container_v1 >>> >>> client = container_v1.ClusterManagerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `zone`: >>> zone = '' >>> >>> # TODO: Initialize `cluster_id`: >>> cluster_id = '' >>> >>> # TODO: Initialize `resource_labels`: >>> resource_labels = {} >>> >>> # TODO: Initialize `label_fingerprint`: >>> label_fingerprint = '' >>> >>> response = client.set_labels(project_id, zone, cluster_id, resource_labels, label_fingerprint) Args: project_id (str): Deprecated. The Google Developers Console `project ID or project number <https://developers.google.com/console/help/new/#projectnumber>`__. This field has been deprecated and replaced by the name field. zone (str): Deprecated. The name of the Google Compute Engine `zone <https://cloud.google.com/compute/docs/zones#available>`__ in which the cluster resides. This field has been deprecated and replaced by the name field. cluster_id (str): Deprecated. The name of the cluster. This field has been deprecated and replaced by the name field. resource_labels (dict[str -> str]): The labels to set for that cluster. label_fingerprint (str): The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Kubernetes Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels. Make a <code>get()</code> request to the resource to get the latest fingerprint. name (str): The name (project, location, cluster id) of the cluster to set labels. Specified in the format 'projects/*/locations/*/clusters/\*'. 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.container_v1.types.Operation` 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 "set_labels" not in self._inner_api_calls: self._inner_api_calls[ "set_labels" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_labels, default_retry=self._method_configs["SetLabels"].retry, default_timeout=self._method_configs["SetLabels"].timeout, client_info=self._client_info, ) request = cluster_service_pb2.SetLabelsRequest( project_id=project_id, zone=zone, cluster_id=cluster_id, resource_labels=resource_labels, label_fingerprint=label_fingerprint, name=name, ) return self._inner_api_calls["set_labels"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "set_labels", "(", "self", ",", "project_id", ",", "zone", ",", "cluster_id", ",", "resource_labels", ",", "label_fingerprint", ",", "name", "=", "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", "\"set_labels\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"set_labels\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "set_labels", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"SetLabels\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"SetLabels\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "cluster_service_pb2", ".", "SetLabelsRequest", "(", "project_id", "=", "project_id", ",", "zone", "=", "zone", ",", "cluster_id", "=", "cluster_id", ",", "resource_labels", "=", "resource_labels", ",", "label_fingerprint", "=", "label_fingerprint", ",", "name", "=", "name", ",", ")", "return", "self", ".", "_inner_api_calls", "[", "\"set_labels\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Sets labels on a cluster. Example: >>> from google.cloud import container_v1 >>> >>> client = container_v1.ClusterManagerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `zone`: >>> zone = '' >>> >>> # TODO: Initialize `cluster_id`: >>> cluster_id = '' >>> >>> # TODO: Initialize `resource_labels`: >>> resource_labels = {} >>> >>> # TODO: Initialize `label_fingerprint`: >>> label_fingerprint = '' >>> >>> response = client.set_labels(project_id, zone, cluster_id, resource_labels, label_fingerprint) Args: project_id (str): Deprecated. The Google Developers Console `project ID or project number <https://developers.google.com/console/help/new/#projectnumber>`__. This field has been deprecated and replaced by the name field. zone (str): Deprecated. The name of the Google Compute Engine `zone <https://cloud.google.com/compute/docs/zones#available>`__ in which the cluster resides. This field has been deprecated and replaced by the name field. cluster_id (str): Deprecated. The name of the cluster. This field has been deprecated and replaced by the name field. resource_labels (dict[str -> str]): The labels to set for that cluster. label_fingerprint (str): The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Kubernetes Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels. Make a <code>get()</code> request to the resource to get the latest fingerprint. name (str): The name (project, location, cluster id) of the cluster to set labels. Specified in the format 'projects/*/locations/*/clusters/\*'. 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.container_v1.types.Operation` 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.
[ "Sets", "labels", "on", "a", "cluster", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/container/google/cloud/container_v1/gapic/cluster_manager_client.py#L2191-L2287
28,273
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/metrics_service_v2_client.py
MetricsServiceV2Client.metric_path
def metric_path(cls, project, metric): """Return a fully-qualified metric string.""" return google.api_core.path_template.expand( "projects/{project}/metrics/{metric}", project=project, metric=metric )
python
def metric_path(cls, project, metric): """Return a fully-qualified metric string.""" return google.api_core.path_template.expand( "projects/{project}/metrics/{metric}", project=project, metric=metric )
[ "def", "metric_path", "(", "cls", ",", "project", ",", "metric", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/metrics/{metric}\"", ",", "project", "=", "project", ",", "metric", "=", "metric", ")" ]
Return a fully-qualified metric string.
[ "Return", "a", "fully", "-", "qualified", "metric", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/metrics_service_v2_client.py#L87-L91
28,274
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/metrics_service_v2_client.py
MetricsServiceV2Client.get_log_metric
def get_log_metric( self, metric_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets a logs-based metric. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.MetricsServiceV2Client() >>> >>> metric_name = client.metric_path('[PROJECT]', '[METRIC]') >>> >>> response = client.get_log_metric(metric_name) Args: metric_name (str): The resource name of the desired metric: :: "projects/[PROJECT_ID]/metrics/[METRIC_ID]" retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.logging_v2.types.LogMetric` 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_log_metric" not in self._inner_api_calls: self._inner_api_calls[ "get_log_metric" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_log_metric, default_retry=self._method_configs["GetLogMetric"].retry, default_timeout=self._method_configs["GetLogMetric"].timeout, client_info=self._client_info, ) request = logging_metrics_pb2.GetLogMetricRequest(metric_name=metric_name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("metric_name", metric_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_log_metric"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def get_log_metric( self, metric_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets a logs-based metric. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.MetricsServiceV2Client() >>> >>> metric_name = client.metric_path('[PROJECT]', '[METRIC]') >>> >>> response = client.get_log_metric(metric_name) Args: metric_name (str): The resource name of the desired metric: :: "projects/[PROJECT_ID]/metrics/[METRIC_ID]" retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.logging_v2.types.LogMetric` 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_log_metric" not in self._inner_api_calls: self._inner_api_calls[ "get_log_metric" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_log_metric, default_retry=self._method_configs["GetLogMetric"].retry, default_timeout=self._method_configs["GetLogMetric"].timeout, client_info=self._client_info, ) request = logging_metrics_pb2.GetLogMetricRequest(metric_name=metric_name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("metric_name", metric_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_log_metric"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "get_log_metric", "(", "self", ",", "metric_name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"get_log_metric\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"get_log_metric\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "get_log_metric", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"GetLogMetric\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"GetLogMetric\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "logging_metrics_pb2", ".", "GetLogMetricRequest", "(", "metric_name", "=", "metric_name", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"metric_name\"", ",", "metric_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_log_metric\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Gets a logs-based metric. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.MetricsServiceV2Client() >>> >>> metric_name = client.metric_path('[PROJECT]', '[METRIC]') >>> >>> response = client.get_log_metric(metric_name) Args: metric_name (str): The resource name of the desired metric: :: "projects/[PROJECT_ID]/metrics/[METRIC_ID]" retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.logging_v2.types.LogMetric` 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", "logs", "-", "based", "metric", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/metrics_service_v2_client.py#L299-L370
28,275
googleapis/google-cloud-python
monitoring/google/cloud/monitoring_v3/gapic/metric_service_client.py
MetricServiceClient.metric_descriptor_path
def metric_descriptor_path(cls, project, metric_descriptor): """Return a fully-qualified metric_descriptor string.""" return google.api_core.path_template.expand( "projects/{project}/metricDescriptors/{metric_descriptor=**}", project=project, metric_descriptor=metric_descriptor, )
python
def metric_descriptor_path(cls, project, metric_descriptor): """Return a fully-qualified metric_descriptor string.""" return google.api_core.path_template.expand( "projects/{project}/metricDescriptors/{metric_descriptor=**}", project=project, metric_descriptor=metric_descriptor, )
[ "def", "metric_descriptor_path", "(", "cls", ",", "project", ",", "metric_descriptor", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/metricDescriptors/{metric_descriptor=**}\"", ",", "project", "=", "project", ",", "metric_descriptor", "=", "metric_descriptor", ",", ")" ]
Return a fully-qualified metric_descriptor string.
[ "Return", "a", "fully", "-", "qualified", "metric_descriptor", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/gapic/metric_service_client.py#L96-L102
28,276
googleapis/google-cloud-python
monitoring/google/cloud/monitoring_v3/gapic/metric_service_client.py
MetricServiceClient.monitored_resource_descriptor_path
def monitored_resource_descriptor_path(cls, project, monitored_resource_descriptor): """Return a fully-qualified monitored_resource_descriptor string.""" return google.api_core.path_template.expand( "projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}", project=project, monitored_resource_descriptor=monitored_resource_descriptor, )
python
def monitored_resource_descriptor_path(cls, project, monitored_resource_descriptor): """Return a fully-qualified monitored_resource_descriptor string.""" return google.api_core.path_template.expand( "projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}", project=project, monitored_resource_descriptor=monitored_resource_descriptor, )
[ "def", "monitored_resource_descriptor_path", "(", "cls", ",", "project", ",", "monitored_resource_descriptor", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}\"", ",", "project", "=", "project", ",", "monitored_resource_descriptor", "=", "monitored_resource_descriptor", ",", ")" ]
Return a fully-qualified monitored_resource_descriptor string.
[ "Return", "a", "fully", "-", "qualified", "monitored_resource_descriptor", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/gapic/metric_service_client.py#L105-L111
28,277
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/keyset.py
KeyRange._to_pb
def _to_pb(self): """Construct a KeyRange protobuf. :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeyRange` :returns: protobuf corresponding to this instance. """ kwargs = {} if self.start_open is not None: kwargs["start_open"] = _make_list_value_pb(self.start_open) if self.start_closed is not None: kwargs["start_closed"] = _make_list_value_pb(self.start_closed) if self.end_open is not None: kwargs["end_open"] = _make_list_value_pb(self.end_open) if self.end_closed is not None: kwargs["end_closed"] = _make_list_value_pb(self.end_closed) return KeyRangePB(**kwargs)
python
def _to_pb(self): """Construct a KeyRange protobuf. :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeyRange` :returns: protobuf corresponding to this instance. """ kwargs = {} if self.start_open is not None: kwargs["start_open"] = _make_list_value_pb(self.start_open) if self.start_closed is not None: kwargs["start_closed"] = _make_list_value_pb(self.start_closed) if self.end_open is not None: kwargs["end_open"] = _make_list_value_pb(self.end_open) if self.end_closed is not None: kwargs["end_closed"] = _make_list_value_pb(self.end_closed) return KeyRangePB(**kwargs)
[ "def", "_to_pb", "(", "self", ")", ":", "kwargs", "=", "{", "}", "if", "self", ".", "start_open", "is", "not", "None", ":", "kwargs", "[", "\"start_open\"", "]", "=", "_make_list_value_pb", "(", "self", ".", "start_open", ")", "if", "self", ".", "start_closed", "is", "not", "None", ":", "kwargs", "[", "\"start_closed\"", "]", "=", "_make_list_value_pb", "(", "self", ".", "start_closed", ")", "if", "self", ".", "end_open", "is", "not", "None", ":", "kwargs", "[", "\"end_open\"", "]", "=", "_make_list_value_pb", "(", "self", ".", "end_open", ")", "if", "self", ".", "end_closed", "is", "not", "None", ":", "kwargs", "[", "\"end_closed\"", "]", "=", "_make_list_value_pb", "(", "self", ".", "end_closed", ")", "return", "KeyRangePB", "(", "*", "*", "kwargs", ")" ]
Construct a KeyRange protobuf. :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeyRange` :returns: protobuf corresponding to this instance.
[ "Construct", "a", "KeyRange", "protobuf", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/keyset.py#L68-L88
28,278
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/keyset.py
KeyRange._to_dict
def _to_dict(self): """Return keyrange's state as a dict. :rtype: dict :returns: state of this instance. """ mapping = {} if self.start_open: mapping["start_open"] = self.start_open if self.start_closed: mapping["start_closed"] = self.start_closed if self.end_open: mapping["end_open"] = self.end_open if self.end_closed: mapping["end_closed"] = self.end_closed return mapping
python
def _to_dict(self): """Return keyrange's state as a dict. :rtype: dict :returns: state of this instance. """ mapping = {} if self.start_open: mapping["start_open"] = self.start_open if self.start_closed: mapping["start_closed"] = self.start_closed if self.end_open: mapping["end_open"] = self.end_open if self.end_closed: mapping["end_closed"] = self.end_closed return mapping
[ "def", "_to_dict", "(", "self", ")", ":", "mapping", "=", "{", "}", "if", "self", ".", "start_open", ":", "mapping", "[", "\"start_open\"", "]", "=", "self", ".", "start_open", "if", "self", ".", "start_closed", ":", "mapping", "[", "\"start_closed\"", "]", "=", "self", ".", "start_closed", "if", "self", ".", "end_open", ":", "mapping", "[", "\"end_open\"", "]", "=", "self", ".", "end_open", "if", "self", ".", "end_closed", ":", "mapping", "[", "\"end_closed\"", "]", "=", "self", ".", "end_closed", "return", "mapping" ]
Return keyrange's state as a dict. :rtype: dict :returns: state of this instance.
[ "Return", "keyrange", "s", "state", "as", "a", "dict", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/keyset.py#L90-L110
28,279
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/keyset.py
KeySet._to_pb
def _to_pb(self): """Construct a KeySet protobuf. :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeySet` :returns: protobuf corresponding to this instance. """ if self.all_: return KeySetPB(all=True) kwargs = {} if self.keys: kwargs["keys"] = _make_list_value_pbs(self.keys) if self.ranges: kwargs["ranges"] = [krange._to_pb() for krange in self.ranges] return KeySetPB(**kwargs)
python
def _to_pb(self): """Construct a KeySet protobuf. :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeySet` :returns: protobuf corresponding to this instance. """ if self.all_: return KeySetPB(all=True) kwargs = {} if self.keys: kwargs["keys"] = _make_list_value_pbs(self.keys) if self.ranges: kwargs["ranges"] = [krange._to_pb() for krange in self.ranges] return KeySetPB(**kwargs)
[ "def", "_to_pb", "(", "self", ")", ":", "if", "self", ".", "all_", ":", "return", "KeySetPB", "(", "all", "=", "True", ")", "kwargs", "=", "{", "}", "if", "self", ".", "keys", ":", "kwargs", "[", "\"keys\"", "]", "=", "_make_list_value_pbs", "(", "self", ".", "keys", ")", "if", "self", ".", "ranges", ":", "kwargs", "[", "\"ranges\"", "]", "=", "[", "krange", ".", "_to_pb", "(", ")", "for", "krange", "in", "self", ".", "ranges", "]", "return", "KeySetPB", "(", "*", "*", "kwargs", ")" ]
Construct a KeySet protobuf. :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeySet` :returns: protobuf corresponding to this instance.
[ "Construct", "a", "KeySet", "protobuf", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/keyset.py#L139-L155
28,280
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/keyset.py
KeySet._to_dict
def _to_dict(self): """Return keyset's state as a dict. The result can be used to serialize the instance and reconstitute it later using :meth:`_from_dict`. :rtype: dict :returns: state of this instance. """ if self.all_: return {"all": True} return { "keys": self.keys, "ranges": [keyrange._to_dict() for keyrange in self.ranges], }
python
def _to_dict(self): """Return keyset's state as a dict. The result can be used to serialize the instance and reconstitute it later using :meth:`_from_dict`. :rtype: dict :returns: state of this instance. """ if self.all_: return {"all": True} return { "keys": self.keys, "ranges": [keyrange._to_dict() for keyrange in self.ranges], }
[ "def", "_to_dict", "(", "self", ")", ":", "if", "self", ".", "all_", ":", "return", "{", "\"all\"", ":", "True", "}", "return", "{", "\"keys\"", ":", "self", ".", "keys", ",", "\"ranges\"", ":", "[", "keyrange", ".", "_to_dict", "(", ")", "for", "keyrange", "in", "self", ".", "ranges", "]", ",", "}" ]
Return keyset's state as a dict. The result can be used to serialize the instance and reconstitute it later using :meth:`_from_dict`. :rtype: dict :returns: state of this instance.
[ "Return", "keyset", "s", "state", "as", "a", "dict", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/keyset.py#L157-L172
28,281
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/keyset.py
KeySet._from_dict
def _from_dict(cls, mapping): """Create an instance from the corresponding state mapping. :type mapping: dict :param mapping: the instance state. """ if mapping.get("all"): return cls(all_=True) r_mappings = mapping.get("ranges", ()) ranges = [KeyRange(**r_mapping) for r_mapping in r_mappings] return cls(keys=mapping.get("keys", ()), ranges=ranges)
python
def _from_dict(cls, mapping): """Create an instance from the corresponding state mapping. :type mapping: dict :param mapping: the instance state. """ if mapping.get("all"): return cls(all_=True) r_mappings = mapping.get("ranges", ()) ranges = [KeyRange(**r_mapping) for r_mapping in r_mappings] return cls(keys=mapping.get("keys", ()), ranges=ranges)
[ "def", "_from_dict", "(", "cls", ",", "mapping", ")", ":", "if", "mapping", ".", "get", "(", "\"all\"", ")", ":", "return", "cls", "(", "all_", "=", "True", ")", "r_mappings", "=", "mapping", ".", "get", "(", "\"ranges\"", ",", "(", ")", ")", "ranges", "=", "[", "KeyRange", "(", "*", "*", "r_mapping", ")", "for", "r_mapping", "in", "r_mappings", "]", "return", "cls", "(", "keys", "=", "mapping", ".", "get", "(", "\"keys\"", ",", "(", ")", ")", ",", "ranges", "=", "ranges", ")" ]
Create an instance from the corresponding state mapping. :type mapping: dict :param mapping: the instance state.
[ "Create", "an", "instance", "from", "the", "corresponding", "state", "mapping", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/keyset.py#L181-L193
28,282
googleapis/google-cloud-python
api_core/google/api_core/grpc_helpers.py
_wrap_unary_errors
def _wrap_unary_errors(callable_): """Map errors for Unary-Unary and Stream-Unary gRPC callables.""" _patch_callable_name(callable_) @six.wraps(callable_) def error_remapped_callable(*args, **kwargs): try: return callable_(*args, **kwargs) except grpc.RpcError as exc: six.raise_from(exceptions.from_grpc_error(exc), exc) return error_remapped_callable
python
def _wrap_unary_errors(callable_): """Map errors for Unary-Unary and Stream-Unary gRPC callables.""" _patch_callable_name(callable_) @six.wraps(callable_) def error_remapped_callable(*args, **kwargs): try: return callable_(*args, **kwargs) except grpc.RpcError as exc: six.raise_from(exceptions.from_grpc_error(exc), exc) return error_remapped_callable
[ "def", "_wrap_unary_errors", "(", "callable_", ")", ":", "_patch_callable_name", "(", "callable_", ")", "@", "six", ".", "wraps", "(", "callable_", ")", "def", "error_remapped_callable", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "callable_", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "grpc", ".", "RpcError", "as", "exc", ":", "six", ".", "raise_from", "(", "exceptions", ".", "from_grpc_error", "(", "exc", ")", ",", "exc", ")", "return", "error_remapped_callable" ]
Map errors for Unary-Unary and Stream-Unary gRPC callables.
[ "Map", "errors", "for", "Unary", "-", "Unary", "and", "Stream", "-", "Unary", "gRPC", "callables", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/grpc_helpers.py#L50-L61
28,283
googleapis/google-cloud-python
api_core/google/api_core/grpc_helpers.py
_wrap_stream_errors
def _wrap_stream_errors(callable_): """Wrap errors for Unary-Stream and Stream-Stream gRPC callables. The callables that return iterators require a bit more logic to re-map errors when iterating. This wraps both the initial invocation and the iterator of the return value to re-map errors. """ _patch_callable_name(callable_) @general_helpers.wraps(callable_) def error_remapped_callable(*args, **kwargs): try: result = callable_(*args, **kwargs) return _StreamingResponseIterator(result) except grpc.RpcError as exc: six.raise_from(exceptions.from_grpc_error(exc), exc) return error_remapped_callable
python
def _wrap_stream_errors(callable_): """Wrap errors for Unary-Stream and Stream-Stream gRPC callables. The callables that return iterators require a bit more logic to re-map errors when iterating. This wraps both the initial invocation and the iterator of the return value to re-map errors. """ _patch_callable_name(callable_) @general_helpers.wraps(callable_) def error_remapped_callable(*args, **kwargs): try: result = callable_(*args, **kwargs) return _StreamingResponseIterator(result) except grpc.RpcError as exc: six.raise_from(exceptions.from_grpc_error(exc), exc) return error_remapped_callable
[ "def", "_wrap_stream_errors", "(", "callable_", ")", ":", "_patch_callable_name", "(", "callable_", ")", "@", "general_helpers", ".", "wraps", "(", "callable_", ")", "def", "error_remapped_callable", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "result", "=", "callable_", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_StreamingResponseIterator", "(", "result", ")", "except", "grpc", ".", "RpcError", "as", "exc", ":", "six", ".", "raise_from", "(", "exceptions", ".", "from_grpc_error", "(", "exc", ")", ",", "exc", ")", "return", "error_remapped_callable" ]
Wrap errors for Unary-Stream and Stream-Stream gRPC callables. The callables that return iterators require a bit more logic to re-map errors when iterating. This wraps both the initial invocation and the iterator of the return value to re-map errors.
[ "Wrap", "errors", "for", "Unary", "-", "Stream", "and", "Stream", "-", "Stream", "gRPC", "callables", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/grpc_helpers.py#L113-L130
28,284
googleapis/google-cloud-python
api_core/google/api_core/grpc_helpers.py
create_channel
def create_channel( target, credentials=None, scopes=None, ssl_credentials=None, **kwargs ): """Create a secure channel with credentials. Args: target (str): The target service address in the format 'hostname:port'. credentials (google.auth.credentials.Credentials): The credentials. If not specified, then this function will attempt to ascertain the credentials from the environment using :func:`google.auth.default`. scopes (Sequence[str]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. ssl_credentials (grpc.ChannelCredentials): Optional SSL channel credentials. This can be used to specify different certificates. kwargs: Additional key-word args passed to :func:`grpc_gcp.secure_channel` or :func:`grpc.secure_channel`. Returns: grpc.Channel: The created channel. """ if credentials is None: credentials, _ = google.auth.default(scopes=scopes) else: credentials = google.auth.credentials.with_scopes_if_required( credentials, scopes ) request = google.auth.transport.requests.Request() # Create the metadata plugin for inserting the authorization header. metadata_plugin = google.auth.transport.grpc.AuthMetadataPlugin( credentials, request ) # Create a set of grpc.CallCredentials using the metadata plugin. google_auth_credentials = grpc.metadata_call_credentials(metadata_plugin) if ssl_credentials is None: ssl_credentials = grpc.ssl_channel_credentials() # Combine the ssl credentials and the authorization credentials. composite_credentials = grpc.composite_channel_credentials( ssl_credentials, google_auth_credentials ) if HAS_GRPC_GCP: # If grpc_gcp module is available use grpc_gcp.secure_channel, # otherwise, use grpc.secure_channel to create grpc channel. return grpc_gcp.secure_channel(target, composite_credentials, **kwargs) else: return grpc.secure_channel(target, composite_credentials, **kwargs)
python
def create_channel( target, credentials=None, scopes=None, ssl_credentials=None, **kwargs ): """Create a secure channel with credentials. Args: target (str): The target service address in the format 'hostname:port'. credentials (google.auth.credentials.Credentials): The credentials. If not specified, then this function will attempt to ascertain the credentials from the environment using :func:`google.auth.default`. scopes (Sequence[str]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. ssl_credentials (grpc.ChannelCredentials): Optional SSL channel credentials. This can be used to specify different certificates. kwargs: Additional key-word args passed to :func:`grpc_gcp.secure_channel` or :func:`grpc.secure_channel`. Returns: grpc.Channel: The created channel. """ if credentials is None: credentials, _ = google.auth.default(scopes=scopes) else: credentials = google.auth.credentials.with_scopes_if_required( credentials, scopes ) request = google.auth.transport.requests.Request() # Create the metadata plugin for inserting the authorization header. metadata_plugin = google.auth.transport.grpc.AuthMetadataPlugin( credentials, request ) # Create a set of grpc.CallCredentials using the metadata plugin. google_auth_credentials = grpc.metadata_call_credentials(metadata_plugin) if ssl_credentials is None: ssl_credentials = grpc.ssl_channel_credentials() # Combine the ssl credentials and the authorization credentials. composite_credentials = grpc.composite_channel_credentials( ssl_credentials, google_auth_credentials ) if HAS_GRPC_GCP: # If grpc_gcp module is available use grpc_gcp.secure_channel, # otherwise, use grpc.secure_channel to create grpc channel. return grpc_gcp.secure_channel(target, composite_credentials, **kwargs) else: return grpc.secure_channel(target, composite_credentials, **kwargs)
[ "def", "create_channel", "(", "target", ",", "credentials", "=", "None", ",", "scopes", "=", "None", ",", "ssl_credentials", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "credentials", "is", "None", ":", "credentials", ",", "_", "=", "google", ".", "auth", ".", "default", "(", "scopes", "=", "scopes", ")", "else", ":", "credentials", "=", "google", ".", "auth", ".", "credentials", ".", "with_scopes_if_required", "(", "credentials", ",", "scopes", ")", "request", "=", "google", ".", "auth", ".", "transport", ".", "requests", ".", "Request", "(", ")", "# Create the metadata plugin for inserting the authorization header.", "metadata_plugin", "=", "google", ".", "auth", ".", "transport", ".", "grpc", ".", "AuthMetadataPlugin", "(", "credentials", ",", "request", ")", "# Create a set of grpc.CallCredentials using the metadata plugin.", "google_auth_credentials", "=", "grpc", ".", "metadata_call_credentials", "(", "metadata_plugin", ")", "if", "ssl_credentials", "is", "None", ":", "ssl_credentials", "=", "grpc", ".", "ssl_channel_credentials", "(", ")", "# Combine the ssl credentials and the authorization credentials.", "composite_credentials", "=", "grpc", ".", "composite_channel_credentials", "(", "ssl_credentials", ",", "google_auth_credentials", ")", "if", "HAS_GRPC_GCP", ":", "# If grpc_gcp module is available use grpc_gcp.secure_channel,", "# otherwise, use grpc.secure_channel to create grpc channel.", "return", "grpc_gcp", ".", "secure_channel", "(", "target", ",", "composite_credentials", ",", "*", "*", "kwargs", ")", "else", ":", "return", "grpc", ".", "secure_channel", "(", "target", ",", "composite_credentials", ",", "*", "*", "kwargs", ")" ]
Create a secure channel with credentials. Args: target (str): The target service address in the format 'hostname:port'. credentials (google.auth.credentials.Credentials): The credentials. If not specified, then this function will attempt to ascertain the credentials from the environment using :func:`google.auth.default`. scopes (Sequence[str]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. ssl_credentials (grpc.ChannelCredentials): Optional SSL channel credentials. This can be used to specify different certificates. kwargs: Additional key-word args passed to :func:`grpc_gcp.secure_channel` or :func:`grpc.secure_channel`. Returns: grpc.Channel: The created channel.
[ "Create", "a", "secure", "channel", "with", "credentials", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/grpc_helpers.py#L155-L206
28,285
googleapis/google-cloud-python
api_core/google/api_core/grpc_helpers.py
_StreamingResponseIterator.next
def next(self): """Get the next response from the stream. Returns: protobuf.Message: A single response from the stream. """ try: return six.next(self._wrapped) except grpc.RpcError as exc: six.raise_from(exceptions.from_grpc_error(exc), exc)
python
def next(self): """Get the next response from the stream. Returns: protobuf.Message: A single response from the stream. """ try: return six.next(self._wrapped) except grpc.RpcError as exc: six.raise_from(exceptions.from_grpc_error(exc), exc)
[ "def", "next", "(", "self", ")", ":", "try", ":", "return", "six", ".", "next", "(", "self", ".", "_wrapped", ")", "except", "grpc", ".", "RpcError", "as", "exc", ":", "six", ".", "raise_from", "(", "exceptions", ".", "from_grpc_error", "(", "exc", ")", ",", "exc", ")" ]
Get the next response from the stream. Returns: protobuf.Message: A single response from the stream.
[ "Get", "the", "next", "response", "from", "the", "stream", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/grpc_helpers.py#L72-L81
28,286
googleapis/google-cloud-python
api_core/google/api_core/general_helpers.py
wraps
def wraps(wrapped): """A functools.wraps helper that handles partial objects on Python 2.""" if isinstance(wrapped, functools.partial): return six.wraps(wrapped, assigned=_PARTIAL_VALID_ASSIGNMENTS) else: return six.wraps(wrapped)
python
def wraps(wrapped): """A functools.wraps helper that handles partial objects on Python 2.""" if isinstance(wrapped, functools.partial): return six.wraps(wrapped, assigned=_PARTIAL_VALID_ASSIGNMENTS) else: return six.wraps(wrapped)
[ "def", "wraps", "(", "wrapped", ")", ":", "if", "isinstance", "(", "wrapped", ",", "functools", ".", "partial", ")", ":", "return", "six", ".", "wraps", "(", "wrapped", ",", "assigned", "=", "_PARTIAL_VALID_ASSIGNMENTS", ")", "else", ":", "return", "six", ".", "wraps", "(", "wrapped", ")" ]
A functools.wraps helper that handles partial objects on Python 2.
[ "A", "functools", ".", "wraps", "helper", "that", "handles", "partial", "objects", "on", "Python", "2", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/general_helpers.py#L27-L32
28,287
googleapis/google-cloud-python
datastore/google/cloud/datastore/client.py
_determine_default_project
def _determine_default_project(project=None): """Determine default project explicitly or implicitly as fall-back. In implicit case, supports four environments. In order of precedence, the implicit environments are: * DATASTORE_DATASET environment variable (for ``gcd`` / emulator testing) * GOOGLE_CLOUD_PROJECT environment variable * Google App Engine application ID * Google Compute Engine project ID (from metadata server) :type project: str :param project: Optional. The project to use as default. :rtype: str or ``NoneType`` :returns: Default project if it can be determined. """ if project is None: project = _get_gcd_project() if project is None: project = _base_default_project(project=project) return project
python
def _determine_default_project(project=None): """Determine default project explicitly or implicitly as fall-back. In implicit case, supports four environments. In order of precedence, the implicit environments are: * DATASTORE_DATASET environment variable (for ``gcd`` / emulator testing) * GOOGLE_CLOUD_PROJECT environment variable * Google App Engine application ID * Google Compute Engine project ID (from metadata server) :type project: str :param project: Optional. The project to use as default. :rtype: str or ``NoneType`` :returns: Default project if it can be determined. """ if project is None: project = _get_gcd_project() if project is None: project = _base_default_project(project=project) return project
[ "def", "_determine_default_project", "(", "project", "=", "None", ")", ":", "if", "project", "is", "None", ":", "project", "=", "_get_gcd_project", "(", ")", "if", "project", "is", "None", ":", "project", "=", "_base_default_project", "(", "project", "=", "project", ")", "return", "project" ]
Determine default project explicitly or implicitly as fall-back. In implicit case, supports four environments. In order of precedence, the implicit environments are: * DATASTORE_DATASET environment variable (for ``gcd`` / emulator testing) * GOOGLE_CLOUD_PROJECT environment variable * Google App Engine application ID * Google Compute Engine project ID (from metadata server) :type project: str :param project: Optional. The project to use as default. :rtype: str or ``NoneType`` :returns: Default project if it can be determined.
[ "Determine", "default", "project", "explicitly", "or", "implicitly", "as", "fall", "-", "back", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/client.py#L54-L77
28,288
googleapis/google-cloud-python
datastore/google/cloud/datastore/client.py
Client._datastore_api
def _datastore_api(self): """Getter for a wrapped API object.""" if self._datastore_api_internal is None: if self._use_grpc: self._datastore_api_internal = make_datastore_api(self) else: self._datastore_api_internal = HTTPDatastoreAPI(self) return self._datastore_api_internal
python
def _datastore_api(self): """Getter for a wrapped API object.""" if self._datastore_api_internal is None: if self._use_grpc: self._datastore_api_internal = make_datastore_api(self) else: self._datastore_api_internal = HTTPDatastoreAPI(self) return self._datastore_api_internal
[ "def", "_datastore_api", "(", "self", ")", ":", "if", "self", ".", "_datastore_api_internal", "is", "None", ":", "if", "self", ".", "_use_grpc", ":", "self", ".", "_datastore_api_internal", "=", "make_datastore_api", "(", "self", ")", "else", ":", "self", ".", "_datastore_api_internal", "=", "HTTPDatastoreAPI", "(", "self", ")", "return", "self", ".", "_datastore_api_internal" ]
Getter for a wrapped API object.
[ "Getter", "for", "a", "wrapped", "API", "object", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/client.py#L241-L248
28,289
googleapis/google-cloud-python
datastore/google/cloud/datastore/client.py
Client.get_multi
def get_multi( self, keys, missing=None, deferred=None, transaction=None, eventual=False ): """Retrieve entities, along with their attributes. :type keys: list of :class:`google.cloud.datastore.key.Key` :param keys: The keys to be retrieved from the datastore. :type missing: list :param missing: (Optional) If a list is passed, the key-only entities returned by the backend as "missing" will be copied into it. If the list is not empty, an error will occur. :type deferred: list :param deferred: (Optional) If a list is passed, the keys returned by the backend as "deferred" will be copied into it. If the list is not empty, an error will occur. :type transaction: :class:`~google.cloud.datastore.transaction.Transaction` :param transaction: (Optional) Transaction to use for read consistency. If not passed, uses current transaction, if set. :type eventual: bool :param eventual: (Optional) Defaults to strongly consistent (False). Setting True will use eventual consistency, but cannot be used inside a transaction or will raise ValueError. :rtype: list of :class:`google.cloud.datastore.entity.Entity` :returns: The requested entities. :raises: :class:`ValueError` if one or more of ``keys`` has a project which does not match our project. :raises: :class:`ValueError` if eventual is True and in a transaction. """ if not keys: return [] ids = set(key.project for key in keys) for current_id in ids: if current_id != self.project: raise ValueError("Keys do not match project") if transaction is None: transaction = self.current_transaction entity_pbs = _extended_lookup( datastore_api=self._datastore_api, project=self.project, key_pbs=[key.to_protobuf() for key in keys], eventual=eventual, missing=missing, deferred=deferred, transaction_id=transaction and transaction.id, ) if missing is not None: missing[:] = [ helpers.entity_from_protobuf(missed_pb) for missed_pb in missing ] if deferred is not None: deferred[:] = [ helpers.key_from_protobuf(deferred_pb) for deferred_pb in deferred ] return [helpers.entity_from_protobuf(entity_pb) for entity_pb in entity_pbs]
python
def get_multi( self, keys, missing=None, deferred=None, transaction=None, eventual=False ): """Retrieve entities, along with their attributes. :type keys: list of :class:`google.cloud.datastore.key.Key` :param keys: The keys to be retrieved from the datastore. :type missing: list :param missing: (Optional) If a list is passed, the key-only entities returned by the backend as "missing" will be copied into it. If the list is not empty, an error will occur. :type deferred: list :param deferred: (Optional) If a list is passed, the keys returned by the backend as "deferred" will be copied into it. If the list is not empty, an error will occur. :type transaction: :class:`~google.cloud.datastore.transaction.Transaction` :param transaction: (Optional) Transaction to use for read consistency. If not passed, uses current transaction, if set. :type eventual: bool :param eventual: (Optional) Defaults to strongly consistent (False). Setting True will use eventual consistency, but cannot be used inside a transaction or will raise ValueError. :rtype: list of :class:`google.cloud.datastore.entity.Entity` :returns: The requested entities. :raises: :class:`ValueError` if one or more of ``keys`` has a project which does not match our project. :raises: :class:`ValueError` if eventual is True and in a transaction. """ if not keys: return [] ids = set(key.project for key in keys) for current_id in ids: if current_id != self.project: raise ValueError("Keys do not match project") if transaction is None: transaction = self.current_transaction entity_pbs = _extended_lookup( datastore_api=self._datastore_api, project=self.project, key_pbs=[key.to_protobuf() for key in keys], eventual=eventual, missing=missing, deferred=deferred, transaction_id=transaction and transaction.id, ) if missing is not None: missing[:] = [ helpers.entity_from_protobuf(missed_pb) for missed_pb in missing ] if deferred is not None: deferred[:] = [ helpers.key_from_protobuf(deferred_pb) for deferred_pb in deferred ] return [helpers.entity_from_protobuf(entity_pb) for entity_pb in entity_pbs]
[ "def", "get_multi", "(", "self", ",", "keys", ",", "missing", "=", "None", ",", "deferred", "=", "None", ",", "transaction", "=", "None", ",", "eventual", "=", "False", ")", ":", "if", "not", "keys", ":", "return", "[", "]", "ids", "=", "set", "(", "key", ".", "project", "for", "key", "in", "keys", ")", "for", "current_id", "in", "ids", ":", "if", "current_id", "!=", "self", ".", "project", ":", "raise", "ValueError", "(", "\"Keys do not match project\"", ")", "if", "transaction", "is", "None", ":", "transaction", "=", "self", ".", "current_transaction", "entity_pbs", "=", "_extended_lookup", "(", "datastore_api", "=", "self", ".", "_datastore_api", ",", "project", "=", "self", ".", "project", ",", "key_pbs", "=", "[", "key", ".", "to_protobuf", "(", ")", "for", "key", "in", "keys", "]", ",", "eventual", "=", "eventual", ",", "missing", "=", "missing", ",", "deferred", "=", "deferred", ",", "transaction_id", "=", "transaction", "and", "transaction", ".", "id", ",", ")", "if", "missing", "is", "not", "None", ":", "missing", "[", ":", "]", "=", "[", "helpers", ".", "entity_from_protobuf", "(", "missed_pb", ")", "for", "missed_pb", "in", "missing", "]", "if", "deferred", "is", "not", "None", ":", "deferred", "[", ":", "]", "=", "[", "helpers", ".", "key_from_protobuf", "(", "deferred_pb", ")", "for", "deferred_pb", "in", "deferred", "]", "return", "[", "helpers", ".", "entity_from_protobuf", "(", "entity_pb", ")", "for", "entity_pb", "in", "entity_pbs", "]" ]
Retrieve entities, along with their attributes. :type keys: list of :class:`google.cloud.datastore.key.Key` :param keys: The keys to be retrieved from the datastore. :type missing: list :param missing: (Optional) If a list is passed, the key-only entities returned by the backend as "missing" will be copied into it. If the list is not empty, an error will occur. :type deferred: list :param deferred: (Optional) If a list is passed, the keys returned by the backend as "deferred" will be copied into it. If the list is not empty, an error will occur. :type transaction: :class:`~google.cloud.datastore.transaction.Transaction` :param transaction: (Optional) Transaction to use for read consistency. If not passed, uses current transaction, if set. :type eventual: bool :param eventual: (Optional) Defaults to strongly consistent (False). Setting True will use eventual consistency, but cannot be used inside a transaction or will raise ValueError. :rtype: list of :class:`google.cloud.datastore.entity.Entity` :returns: The requested entities. :raises: :class:`ValueError` if one or more of ``keys`` has a project which does not match our project. :raises: :class:`ValueError` if eventual is True and in a transaction.
[ "Retrieve", "entities", "along", "with", "their", "attributes", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/client.py#L342-L407
28,290
googleapis/google-cloud-python
datastore/google/cloud/datastore/client.py
Client.put_multi
def put_multi(self, entities): """Save entities in the Cloud Datastore. :type entities: list of :class:`google.cloud.datastore.entity.Entity` :param entities: The entities to be saved to the datastore. :raises: :class:`ValueError` if ``entities`` is a single entity. """ if isinstance(entities, Entity): raise ValueError("Pass a sequence of entities") if not entities: return current = self.current_batch in_batch = current is not None if not in_batch: current = self.batch() current.begin() for entity in entities: current.put(entity) if not in_batch: current.commit()
python
def put_multi(self, entities): """Save entities in the Cloud Datastore. :type entities: list of :class:`google.cloud.datastore.entity.Entity` :param entities: The entities to be saved to the datastore. :raises: :class:`ValueError` if ``entities`` is a single entity. """ if isinstance(entities, Entity): raise ValueError("Pass a sequence of entities") if not entities: return current = self.current_batch in_batch = current is not None if not in_batch: current = self.batch() current.begin() for entity in entities: current.put(entity) if not in_batch: current.commit()
[ "def", "put_multi", "(", "self", ",", "entities", ")", ":", "if", "isinstance", "(", "entities", ",", "Entity", ")", ":", "raise", "ValueError", "(", "\"Pass a sequence of entities\"", ")", "if", "not", "entities", ":", "return", "current", "=", "self", ".", "current_batch", "in_batch", "=", "current", "is", "not", "None", "if", "not", "in_batch", ":", "current", "=", "self", ".", "batch", "(", ")", "current", ".", "begin", "(", ")", "for", "entity", "in", "entities", ":", "current", ".", "put", "(", "entity", ")", "if", "not", "in_batch", ":", "current", ".", "commit", "(", ")" ]
Save entities in the Cloud Datastore. :type entities: list of :class:`google.cloud.datastore.entity.Entity` :param entities: The entities to be saved to the datastore. :raises: :class:`ValueError` if ``entities`` is a single entity.
[ "Save", "entities", "in", "the", "Cloud", "Datastore", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/client.py#L423-L448
28,291
googleapis/google-cloud-python
datastore/google/cloud/datastore/client.py
Client.delete_multi
def delete_multi(self, keys): """Delete keys from the Cloud Datastore. :type keys: list of :class:`google.cloud.datastore.key.Key` :param keys: The keys to be deleted from the Datastore. """ if not keys: return # We allow partial keys to attempt a delete, the backend will fail. current = self.current_batch in_batch = current is not None if not in_batch: current = self.batch() current.begin() for key in keys: current.delete(key) if not in_batch: current.commit()
python
def delete_multi(self, keys): """Delete keys from the Cloud Datastore. :type keys: list of :class:`google.cloud.datastore.key.Key` :param keys: The keys to be deleted from the Datastore. """ if not keys: return # We allow partial keys to attempt a delete, the backend will fail. current = self.current_batch in_batch = current is not None if not in_batch: current = self.batch() current.begin() for key in keys: current.delete(key) if not in_batch: current.commit()
[ "def", "delete_multi", "(", "self", ",", "keys", ")", ":", "if", "not", "keys", ":", "return", "# We allow partial keys to attempt a delete, the backend will fail.", "current", "=", "self", ".", "current_batch", "in_batch", "=", "current", "is", "not", "None", "if", "not", "in_batch", ":", "current", "=", "self", ".", "batch", "(", ")", "current", ".", "begin", "(", ")", "for", "key", "in", "keys", ":", "current", ".", "delete", "(", "key", ")", "if", "not", "in_batch", ":", "current", ".", "commit", "(", ")" ]
Delete keys from the Cloud Datastore. :type keys: list of :class:`google.cloud.datastore.key.Key` :param keys: The keys to be deleted from the Datastore.
[ "Delete", "keys", "from", "the", "Cloud", "Datastore", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/client.py#L464-L485
28,292
googleapis/google-cloud-python
datastore/google/cloud/datastore/client.py
Client.allocate_ids
def allocate_ids(self, incomplete_key, num_ids): """Allocate a list of IDs from a partial key. :type incomplete_key: :class:`google.cloud.datastore.key.Key` :param incomplete_key: Partial key to use as base for allocated IDs. :type num_ids: int :param num_ids: The number of IDs to allocate. :rtype: list of :class:`google.cloud.datastore.key.Key` :returns: The (complete) keys allocated with ``incomplete_key`` as root. :raises: :class:`ValueError` if ``incomplete_key`` is not a partial key. """ if not incomplete_key.is_partial: raise ValueError(("Key is not partial.", incomplete_key)) incomplete_key_pb = incomplete_key.to_protobuf() incomplete_key_pbs = [incomplete_key_pb] * num_ids response_pb = self._datastore_api.allocate_ids( incomplete_key.project, incomplete_key_pbs ) allocated_ids = [ allocated_key_pb.path[-1].id for allocated_key_pb in response_pb.keys ] return [ incomplete_key.completed_key(allocated_id) for allocated_id in allocated_ids ]
python
def allocate_ids(self, incomplete_key, num_ids): """Allocate a list of IDs from a partial key. :type incomplete_key: :class:`google.cloud.datastore.key.Key` :param incomplete_key: Partial key to use as base for allocated IDs. :type num_ids: int :param num_ids: The number of IDs to allocate. :rtype: list of :class:`google.cloud.datastore.key.Key` :returns: The (complete) keys allocated with ``incomplete_key`` as root. :raises: :class:`ValueError` if ``incomplete_key`` is not a partial key. """ if not incomplete_key.is_partial: raise ValueError(("Key is not partial.", incomplete_key)) incomplete_key_pb = incomplete_key.to_protobuf() incomplete_key_pbs = [incomplete_key_pb] * num_ids response_pb = self._datastore_api.allocate_ids( incomplete_key.project, incomplete_key_pbs ) allocated_ids = [ allocated_key_pb.path[-1].id for allocated_key_pb in response_pb.keys ] return [ incomplete_key.completed_key(allocated_id) for allocated_id in allocated_ids ]
[ "def", "allocate_ids", "(", "self", ",", "incomplete_key", ",", "num_ids", ")", ":", "if", "not", "incomplete_key", ".", "is_partial", ":", "raise", "ValueError", "(", "(", "\"Key is not partial.\"", ",", "incomplete_key", ")", ")", "incomplete_key_pb", "=", "incomplete_key", ".", "to_protobuf", "(", ")", "incomplete_key_pbs", "=", "[", "incomplete_key_pb", "]", "*", "num_ids", "response_pb", "=", "self", ".", "_datastore_api", ".", "allocate_ids", "(", "incomplete_key", ".", "project", ",", "incomplete_key_pbs", ")", "allocated_ids", "=", "[", "allocated_key_pb", ".", "path", "[", "-", "1", "]", ".", "id", "for", "allocated_key_pb", "in", "response_pb", ".", "keys", "]", "return", "[", "incomplete_key", ".", "completed_key", "(", "allocated_id", ")", "for", "allocated_id", "in", "allocated_ids", "]" ]
Allocate a list of IDs from a partial key. :type incomplete_key: :class:`google.cloud.datastore.key.Key` :param incomplete_key: Partial key to use as base for allocated IDs. :type num_ids: int :param num_ids: The number of IDs to allocate. :rtype: list of :class:`google.cloud.datastore.key.Key` :returns: The (complete) keys allocated with ``incomplete_key`` as root. :raises: :class:`ValueError` if ``incomplete_key`` is not a partial key.
[ "Allocate", "a", "list", "of", "IDs", "from", "a", "partial", "key", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/client.py#L487-L516
28,293
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/batcher.py
MutationsBatcher.mutate
def mutate(self, row): """ Add a row to the batch. If the current batch meets one of the size limits, the batch is sent synchronously. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_batcher_mutate] :end-before: [END bigtable_batcher_mutate] :type row: class :param row: class:`~google.cloud.bigtable.row.DirectRow`. :raises: One of the following: * :exc:`~.table._BigtableRetryableError` if any row returned a transient error. * :exc:`RuntimeError` if the number of responses doesn't match the number of rows that were retried * :exc:`.batcher.MaxMutationsError` if any row exceeds max mutations count. """ mutation_count = len(row._get_mutations()) if mutation_count > MAX_MUTATIONS: raise MaxMutationsError( "The row key {} exceeds the number of mutations {}.".format( row.row_key, mutation_count ) ) if (self.total_mutation_count + mutation_count) >= MAX_MUTATIONS: self.flush() self.rows.append(row) self.total_mutation_count += mutation_count self.total_size += row.get_mutations_size() if self.total_size >= self.max_row_bytes or len(self.rows) >= self.flush_count: self.flush()
python
def mutate(self, row): """ Add a row to the batch. If the current batch meets one of the size limits, the batch is sent synchronously. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_batcher_mutate] :end-before: [END bigtable_batcher_mutate] :type row: class :param row: class:`~google.cloud.bigtable.row.DirectRow`. :raises: One of the following: * :exc:`~.table._BigtableRetryableError` if any row returned a transient error. * :exc:`RuntimeError` if the number of responses doesn't match the number of rows that were retried * :exc:`.batcher.MaxMutationsError` if any row exceeds max mutations count. """ mutation_count = len(row._get_mutations()) if mutation_count > MAX_MUTATIONS: raise MaxMutationsError( "The row key {} exceeds the number of mutations {}.".format( row.row_key, mutation_count ) ) if (self.total_mutation_count + mutation_count) >= MAX_MUTATIONS: self.flush() self.rows.append(row) self.total_mutation_count += mutation_count self.total_size += row.get_mutations_size() if self.total_size >= self.max_row_bytes or len(self.rows) >= self.flush_count: self.flush()
[ "def", "mutate", "(", "self", ",", "row", ")", ":", "mutation_count", "=", "len", "(", "row", ".", "_get_mutations", "(", ")", ")", "if", "mutation_count", ">", "MAX_MUTATIONS", ":", "raise", "MaxMutationsError", "(", "\"The row key {} exceeds the number of mutations {}.\"", ".", "format", "(", "row", ".", "row_key", ",", "mutation_count", ")", ")", "if", "(", "self", ".", "total_mutation_count", "+", "mutation_count", ")", ">=", "MAX_MUTATIONS", ":", "self", ".", "flush", "(", ")", "self", ".", "rows", ".", "append", "(", "row", ")", "self", ".", "total_mutation_count", "+=", "mutation_count", "self", ".", "total_size", "+=", "row", ".", "get_mutations_size", "(", ")", "if", "self", ".", "total_size", ">=", "self", ".", "max_row_bytes", "or", "len", "(", "self", ".", "rows", ")", ">=", "self", ".", "flush_count", ":", "self", ".", "flush", "(", ")" ]
Add a row to the batch. If the current batch meets one of the size limits, the batch is sent synchronously. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_batcher_mutate] :end-before: [END bigtable_batcher_mutate] :type row: class :param row: class:`~google.cloud.bigtable.row.DirectRow`. :raises: One of the following: * :exc:`~.table._BigtableRetryableError` if any row returned a transient error. * :exc:`RuntimeError` if the number of responses doesn't match the number of rows that were retried * :exc:`.batcher.MaxMutationsError` if any row exceeds max mutations count.
[ "Add", "a", "row", "to", "the", "batch", ".", "If", "the", "current", "batch", "meets", "one", "of", "the", "size", "limits", "the", "batch", "is", "sent", "synchronously", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/batcher.py#L67-L104
28,294
googleapis/google-cloud-python
storage/google/cloud/storage/notification.py
_parse_topic_path
def _parse_topic_path(topic_path): """Verify that a topic path is in the correct format. .. _resource manager docs: https://cloud.google.com/resource-manager/\ reference/rest/v1beta1/projects#\ Project.FIELDS.project_id .. _topic spec: https://cloud.google.com/storage/docs/json_api/v1/\ notifications/insert#topic Expected to be of the form: //pubsub.googleapis.com/projects/{project}/topics/{topic} where the ``project`` value must be "6 to 30 lowercase letters, digits, or hyphens. It must start with a letter. Trailing hyphens are prohibited." (see `resource manager docs`_) and ``topic`` must have length at least two, must start with a letter and may only contain alphanumeric characters or ``-``, ``_``, ``.``, ``~``, ``+`` or ``%`` (i.e characters used for URL encoding, see `topic spec`_). Args: topic_path (str): The topic path to be verified. Returns: Tuple[str, str]: The ``project`` and ``topic`` parsed from the ``topic_path``. Raises: ValueError: If the topic path is invalid. """ match = _TOPIC_REF_RE.match(topic_path) if match is None: raise ValueError(_BAD_TOPIC.format(topic_path)) return match.group("name"), match.group("project")
python
def _parse_topic_path(topic_path): """Verify that a topic path is in the correct format. .. _resource manager docs: https://cloud.google.com/resource-manager/\ reference/rest/v1beta1/projects#\ Project.FIELDS.project_id .. _topic spec: https://cloud.google.com/storage/docs/json_api/v1/\ notifications/insert#topic Expected to be of the form: //pubsub.googleapis.com/projects/{project}/topics/{topic} where the ``project`` value must be "6 to 30 lowercase letters, digits, or hyphens. It must start with a letter. Trailing hyphens are prohibited." (see `resource manager docs`_) and ``topic`` must have length at least two, must start with a letter and may only contain alphanumeric characters or ``-``, ``_``, ``.``, ``~``, ``+`` or ``%`` (i.e characters used for URL encoding, see `topic spec`_). Args: topic_path (str): The topic path to be verified. Returns: Tuple[str, str]: The ``project`` and ``topic`` parsed from the ``topic_path``. Raises: ValueError: If the topic path is invalid. """ match = _TOPIC_REF_RE.match(topic_path) if match is None: raise ValueError(_BAD_TOPIC.format(topic_path)) return match.group("name"), match.group("project")
[ "def", "_parse_topic_path", "(", "topic_path", ")", ":", "match", "=", "_TOPIC_REF_RE", ".", "match", "(", "topic_path", ")", "if", "match", "is", "None", ":", "raise", "ValueError", "(", "_BAD_TOPIC", ".", "format", "(", "topic_path", ")", ")", "return", "match", ".", "group", "(", "\"name\"", ")", ",", "match", ".", "group", "(", "\"project\"", ")" ]
Verify that a topic path is in the correct format. .. _resource manager docs: https://cloud.google.com/resource-manager/\ reference/rest/v1beta1/projects#\ Project.FIELDS.project_id .. _topic spec: https://cloud.google.com/storage/docs/json_api/v1/\ notifications/insert#topic Expected to be of the form: //pubsub.googleapis.com/projects/{project}/topics/{topic} where the ``project`` value must be "6 to 30 lowercase letters, digits, or hyphens. It must start with a letter. Trailing hyphens are prohibited." (see `resource manager docs`_) and ``topic`` must have length at least two, must start with a letter and may only contain alphanumeric characters or ``-``, ``_``, ``.``, ``~``, ``+`` or ``%`` (i.e characters used for URL encoding, see `topic spec`_). Args: topic_path (str): The topic path to be verified. Returns: Tuple[str, str]: The ``project`` and ``topic`` parsed from the ``topic_path``. Raises: ValueError: If the topic path is invalid.
[ "Verify", "that", "a", "topic", "path", "is", "in", "the", "correct", "format", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/notification.py#L355-L389
28,295
googleapis/google-cloud-python
storage/google/cloud/storage/notification.py
BucketNotification.from_api_repr
def from_api_repr(cls, resource, bucket): """Construct an instance from the JSON repr returned by the server. See: https://cloud.google.com/storage/docs/json_api/v1/notifications :type resource: dict :param resource: JSON repr of the notification :type bucket: :class:`google.cloud.storage.bucket.Bucket` :param bucket: Bucket to which the notification is bound. :rtype: :class:`BucketNotification` :returns: the new notification instance """ topic_path = resource.get("topic") if topic_path is None: raise ValueError("Resource has no topic") name, project = _parse_topic_path(topic_path) instance = cls(bucket, name, topic_project=project) instance._properties = resource return instance
python
def from_api_repr(cls, resource, bucket): """Construct an instance from the JSON repr returned by the server. See: https://cloud.google.com/storage/docs/json_api/v1/notifications :type resource: dict :param resource: JSON repr of the notification :type bucket: :class:`google.cloud.storage.bucket.Bucket` :param bucket: Bucket to which the notification is bound. :rtype: :class:`BucketNotification` :returns: the new notification instance """ topic_path = resource.get("topic") if topic_path is None: raise ValueError("Resource has no topic") name, project = _parse_topic_path(topic_path) instance = cls(bucket, name, topic_project=project) instance._properties = resource return instance
[ "def", "from_api_repr", "(", "cls", ",", "resource", ",", "bucket", ")", ":", "topic_path", "=", "resource", ".", "get", "(", "\"topic\"", ")", "if", "topic_path", "is", "None", ":", "raise", "ValueError", "(", "\"Resource has no topic\"", ")", "name", ",", "project", "=", "_parse_topic_path", "(", "topic_path", ")", "instance", "=", "cls", "(", "bucket", ",", "name", ",", "topic_project", "=", "project", ")", "instance", ".", "_properties", "=", "resource", "return", "instance" ]
Construct an instance from the JSON repr returned by the server. See: https://cloud.google.com/storage/docs/json_api/v1/notifications :type resource: dict :param resource: JSON repr of the notification :type bucket: :class:`google.cloud.storage.bucket.Bucket` :param bucket: Bucket to which the notification is bound. :rtype: :class:`BucketNotification` :returns: the new notification instance
[ "Construct", "an", "instance", "from", "the", "JSON", "repr", "returned", "by", "the", "server", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/notification.py#L111-L133
28,296
googleapis/google-cloud-python
storage/google/cloud/storage/notification.py
BucketNotification.exists
def exists(self, client=None): """Test whether this notification exists. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/get If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the current bucket. :rtype: bool :returns: True, if the notification exists, else False. :raises ValueError: if the notification has no ID. """ if self.notification_id is None: raise ValueError("Notification not intialized by server") client = self._require_client(client) query_params = {} if self.bucket.user_project is not None: query_params["userProject"] = self.bucket.user_project try: client._connection.api_request( method="GET", path=self.path, query_params=query_params ) except NotFound: return False else: return True
python
def exists(self, client=None): """Test whether this notification exists. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/get If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the current bucket. :rtype: bool :returns: True, if the notification exists, else False. :raises ValueError: if the notification has no ID. """ if self.notification_id is None: raise ValueError("Notification not intialized by server") client = self._require_client(client) query_params = {} if self.bucket.user_project is not None: query_params["userProject"] = self.bucket.user_project try: client._connection.api_request( method="GET", path=self.path, query_params=query_params ) except NotFound: return False else: return True
[ "def", "exists", "(", "self", ",", "client", "=", "None", ")", ":", "if", "self", ".", "notification_id", "is", "None", ":", "raise", "ValueError", "(", "\"Notification not intialized by server\"", ")", "client", "=", "self", ".", "_require_client", "(", "client", ")", "query_params", "=", "{", "}", "if", "self", ".", "bucket", ".", "user_project", "is", "not", "None", ":", "query_params", "[", "\"userProject\"", "]", "=", "self", ".", "bucket", ".", "user_project", "try", ":", "client", ".", "_connection", ".", "api_request", "(", "method", "=", "\"GET\"", ",", "path", "=", "self", ".", "path", ",", "query_params", "=", "query_params", ")", "except", "NotFound", ":", "return", "False", "else", ":", "return", "True" ]
Test whether this notification exists. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/get If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the current bucket. :rtype: bool :returns: True, if the notification exists, else False. :raises ValueError: if the notification has no ID.
[ "Test", "whether", "this", "notification", "exists", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/notification.py#L255-L289
28,297
googleapis/google-cloud-python
storage/google/cloud/storage/notification.py
BucketNotification.reload
def reload(self, client=None): """Update this notification from the server configuration. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/get If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the current bucket. :rtype: bool :returns: True, if the notification exists, else False. :raises ValueError: if the notification has no ID. """ if self.notification_id is None: raise ValueError("Notification not intialized by server") client = self._require_client(client) query_params = {} if self.bucket.user_project is not None: query_params["userProject"] = self.bucket.user_project response = client._connection.api_request( method="GET", path=self.path, query_params=query_params ) self._set_properties(response)
python
def reload(self, client=None): """Update this notification from the server configuration. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/get If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the current bucket. :rtype: bool :returns: True, if the notification exists, else False. :raises ValueError: if the notification has no ID. """ if self.notification_id is None: raise ValueError("Notification not intialized by server") client = self._require_client(client) query_params = {} if self.bucket.user_project is not None: query_params["userProject"] = self.bucket.user_project response = client._connection.api_request( method="GET", path=self.path, query_params=query_params ) self._set_properties(response)
[ "def", "reload", "(", "self", ",", "client", "=", "None", ")", ":", "if", "self", ".", "notification_id", "is", "None", ":", "raise", "ValueError", "(", "\"Notification not intialized by server\"", ")", "client", "=", "self", ".", "_require_client", "(", "client", ")", "query_params", "=", "{", "}", "if", "self", ".", "bucket", ".", "user_project", "is", "not", "None", ":", "query_params", "[", "\"userProject\"", "]", "=", "self", ".", "bucket", ".", "user_project", "response", "=", "client", ".", "_connection", ".", "api_request", "(", "method", "=", "\"GET\"", ",", "path", "=", "self", ".", "path", ",", "query_params", "=", "query_params", ")", "self", ".", "_set_properties", "(", "response", ")" ]
Update this notification from the server configuration. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/get If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the current bucket. :rtype: bool :returns: True, if the notification exists, else False. :raises ValueError: if the notification has no ID.
[ "Update", "this", "notification", "from", "the", "server", "configuration", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/notification.py#L291-L321
28,298
googleapis/google-cloud-python
storage/google/cloud/storage/notification.py
BucketNotification.delete
def delete(self, client=None): """Delete this notification. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/delete If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the current bucket. :raises: :class:`google.api_core.exceptions.NotFound`: if the notification does not exist. :raises ValueError: if the notification has no ID. """ if self.notification_id is None: raise ValueError("Notification not intialized by server") client = self._require_client(client) query_params = {} if self.bucket.user_project is not None: query_params["userProject"] = self.bucket.user_project client._connection.api_request( method="DELETE", path=self.path, query_params=query_params )
python
def delete(self, client=None): """Delete this notification. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/delete If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the current bucket. :raises: :class:`google.api_core.exceptions.NotFound`: if the notification does not exist. :raises ValueError: if the notification has no ID. """ if self.notification_id is None: raise ValueError("Notification not intialized by server") client = self._require_client(client) query_params = {} if self.bucket.user_project is not None: query_params["userProject"] = self.bucket.user_project client._connection.api_request( method="DELETE", path=self.path, query_params=query_params )
[ "def", "delete", "(", "self", ",", "client", "=", "None", ")", ":", "if", "self", ".", "notification_id", "is", "None", ":", "raise", "ValueError", "(", "\"Notification not intialized by server\"", ")", "client", "=", "self", ".", "_require_client", "(", "client", ")", "query_params", "=", "{", "}", "if", "self", ".", "bucket", ".", "user_project", "is", "not", "None", ":", "query_params", "[", "\"userProject\"", "]", "=", "self", ".", "bucket", ".", "user_project", "client", ".", "_connection", ".", "api_request", "(", "method", "=", "\"DELETE\"", ",", "path", "=", "self", ".", "path", ",", "query_params", "=", "query_params", ")" ]
Delete this notification. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/delete If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the current bucket. :raises: :class:`google.api_core.exceptions.NotFound`: if the notification does not exist. :raises ValueError: if the notification has no ID.
[ "Delete", "this", "notification", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/notification.py#L323-L352
28,299
googleapis/google-cloud-python
redis/google/cloud/redis_v1/gapic/cloud_redis_client.py
CloudRedisClient.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 a Redis instance based on the specified tier and memory size. By default, the instance is accessible from the project's `default network <https://cloud.google.com/compute/docs/networks-and-firewalls#networks>`__. The creation is executed asynchronously and callers may check the returned operation to track its progress. Once the operation is completed the Redis instance will be fully functional. Completed longrunning.Operation will contain the new instance object in the response field. The returned operation is automatically deleted after a few hours, so there is no need to call DeleteOperation. Example: >>> from google.cloud import redis_v1 >>> from google.cloud.redis_v1 import enums >>> >>> client = redis_v1.CloudRedisClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> instance_id = 'test_instance' >>> tier = enums.Instance.Tier.BASIC >>> memory_size_gb = 1 >>> instance = {'tier': tier, 'memory_size_gb': memory_size_gb} >>> >>> 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 resource name of the instance location using the form: ``projects/{project_id}/locations/{location_id}`` where ``location_id`` refers to a GCP region instance_id (str): Required. The logical name of the Redis instance in the customer project with the following restrictions: - Must contain only lowercase letters, numbers, and hyphens. - Must start with a letter. - Must be between 1-40 characters. - Must end with a number or a letter. - Must be unique within the customer project / location instance (Union[dict, ~google.cloud.redis_v1.types.Instance]): Required. A Redis [Instance] resource If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.redis_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.redis_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 = cloud_redis_pb2.CreateInstanceRequest( parent=parent, instance_id=instance_id, instance=instance ) 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, cloud_redis_pb2.Instance, metadata_type=cloud_redis_pb2.OperationMetadata, )
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 a Redis instance based on the specified tier and memory size. By default, the instance is accessible from the project's `default network <https://cloud.google.com/compute/docs/networks-and-firewalls#networks>`__. The creation is executed asynchronously and callers may check the returned operation to track its progress. Once the operation is completed the Redis instance will be fully functional. Completed longrunning.Operation will contain the new instance object in the response field. The returned operation is automatically deleted after a few hours, so there is no need to call DeleteOperation. Example: >>> from google.cloud import redis_v1 >>> from google.cloud.redis_v1 import enums >>> >>> client = redis_v1.CloudRedisClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> instance_id = 'test_instance' >>> tier = enums.Instance.Tier.BASIC >>> memory_size_gb = 1 >>> instance = {'tier': tier, 'memory_size_gb': memory_size_gb} >>> >>> 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 resource name of the instance location using the form: ``projects/{project_id}/locations/{location_id}`` where ``location_id`` refers to a GCP region instance_id (str): Required. The logical name of the Redis instance in the customer project with the following restrictions: - Must contain only lowercase letters, numbers, and hyphens. - Must start with a letter. - Must be between 1-40 characters. - Must end with a number or a letter. - Must be unique within the customer project / location instance (Union[dict, ~google.cloud.redis_v1.types.Instance]): Required. A Redis [Instance] resource If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.redis_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.redis_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 = cloud_redis_pb2.CreateInstanceRequest( parent=parent, instance_id=instance_id, instance=instance ) 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, cloud_redis_pb2.Instance, metadata_type=cloud_redis_pb2.OperationMetadata, )
[ "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", "=", "cloud_redis_pb2", ".", "CreateInstanceRequest", "(", "parent", "=", "parent", ",", "instance_id", "=", "instance_id", ",", "instance", "=", "instance", ")", "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", ",", "cloud_redis_pb2", ".", "Instance", ",", "metadata_type", "=", "cloud_redis_pb2", ".", "OperationMetadata", ",", ")" ]
Creates a Redis instance based on the specified tier and memory size. By default, the instance is accessible from the project's `default network <https://cloud.google.com/compute/docs/networks-and-firewalls#networks>`__. The creation is executed asynchronously and callers may check the returned operation to track its progress. Once the operation is completed the Redis instance will be fully functional. Completed longrunning.Operation will contain the new instance object in the response field. The returned operation is automatically deleted after a few hours, so there is no need to call DeleteOperation. Example: >>> from google.cloud import redis_v1 >>> from google.cloud.redis_v1 import enums >>> >>> client = redis_v1.CloudRedisClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> instance_id = 'test_instance' >>> tier = enums.Instance.Tier.BASIC >>> memory_size_gb = 1 >>> instance = {'tier': tier, 'memory_size_gb': memory_size_gb} >>> >>> 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 resource name of the instance location using the form: ``projects/{project_id}/locations/{location_id}`` where ``location_id`` refers to a GCP region instance_id (str): Required. The logical name of the Redis instance in the customer project with the following restrictions: - Must contain only lowercase letters, numbers, and hyphens. - Must start with a letter. - Must be between 1-40 characters. - Must end with a number or a letter. - Must be unique within the customer project / location instance (Union[dict, ~google.cloud.redis_v1.types.Instance]): Required. A Redis [Instance] resource If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.redis_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.redis_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", "a", "Redis", "instance", "based", "on", "the", "specified", "tier", "and", "memory", "size", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/redis/google/cloud/redis_v1/gapic/cloud_redis_client.py#L367-L471