INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Helper for :meth:`__iter__`.
def _create_retry_request(self): """Helper for :meth:`__iter__`.""" req_manager = _ReadRowsRequestManager( self.request, self.last_scanned_row_key, self._counter ) return req_manager.build_updated_request()
Helper for :meth:`__iter__`.
def _on_error(self, exc): """Helper for :meth:`__iter__`.""" # restart the read scan from AFTER the last successfully read row retry_request = self.request if self.last_scanned_row_key: retry_request = self._create_retry_request() self.response_iterator = self.read_m...
Helper for :meth:`consume_next`.
def _save_current_cell(self): """Helper for :meth:`consume_next`.""" row, cell = self._row, self._cell family = row._cells.setdefault(cell.family_name, {}) qualified = family.setdefault(cell.qualifier, []) complete = Cell.from_pb(cell) qualified.append(complete) s...
Helper for :meth:`consume_next`.
def _copy_from_previous(self, cell): """Helper for :meth:`consume_next`.""" previous = self._previous_cell if previous is not None: if not cell.row_key: cell.row_key = previous.row_key if not cell.family_name: cell.family_name = pre...
Updates the given message request as per last scanned key
def build_updated_request(self): """ Updates the given message request as per last scanned key """ r_kwargs = { "table_name": self.message.table_name, "filter": self.message.filter, } if self.message.rows_limit != 0: r_kwargs["rows_limit"] = m...
Helper for :meth:`build_updated_request`
def _filter_rows_keys(self): """ Helper for :meth:`build_updated_request`""" return [ row_key for row_key in self.message.rows.row_keys if row_key > self.last_scanned_key ]
Helper for :meth:`build_updated_request`
def _filter_row_ranges(self): """ Helper for :meth:`build_updated_request`""" new_row_ranges = [] for row_range in self.message.rows.row_ranges: # if current end_key (open or closed) is set, return its value, # if not, set to empty string (''). # NOTE: Empty ...
Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you send matches that of an existing trace, any fields in the existing trace and its spans are overwritten by the provided values, and any new fields provided are merged with the existing trace data. If t...
def patch_traces( self, project_id, traces, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a t...
Gets a single trace by its ID. Example: >>> from google.cloud import trace_v1 >>> >>> client = trace_v1.TraceServiceClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `t...
def get_trace( self, project_id, trace_id, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets a single trace by its ID. Example: >>> from google.cloud import t...
Gets the details of a specific Redis instance. Example: >>> from google.cloud import redis_v1beta1 >>> >>> client = redis_v1beta1.CloudRedisClient() >>> >>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]') >>> ...
def get_instance( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the details of a specific Redis instance. Example: >>> from google.cloud import redis_...
Updates the metadata and configuration of a specific Redis instance. Completed longrunning.Operation will contain the new instance object in the response field. The returned operation is automatically deleted after a few hours, so there is no need to call DeleteOperation. Example: ...
def update_instance( self, update_mask, instance, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates the metadata and configuration of a specific Redis instance. Comple...
Deletes a specific Redis instance. Instance stops serving and data is deleted. Example: >>> from google.cloud import redis_v1beta1 >>> >>> client = redis_v1beta1.CloudRedisClient() >>> >>> name = client.instance_path('[PROJECT]', '[LOCATION]'...
def delete_instance( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a specific Redis instance. Instance stops serving and data is deleted. Example: ...
Performs synchronous speech recognition: receive results after all audio has been sent and processed. Example: >>> from google.cloud import speech_v1p1beta1 >>> from google.cloud.speech_v1p1beta1 import enums >>> >>> client = speech_v1p1beta1.SpeechClient...
def recognize( self, config, audio, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Performs synchronous speech recognition: receive results after all audio has been sent and...
Performs asynchronous speech recognition: receive results via the google.longrunning.Operations interface. Returns either an ``Operation.error`` or an ``Operation.response`` which contains a ``LongRunningRecognizeResponse`` message. Example: >>> from google.cloud import spee...
def long_running_recognize( self, config, audio, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Performs asynchronous speech recognition: receive results via the google.long...
Return a fully-qualified region string.
def region_path(cls, project, region): """Return a fully-qualified region string.""" return google.api_core.path_template.expand( "projects/{project}/regions/{region}", project=project, region=region )
Return a fully-qualified workflow_template string.
def workflow_template_path(cls, project, region, workflow_template): """Return a fully-qualified workflow_template string.""" return google.api_core.path_template.expand( "projects/{project}/regions/{region}/workflowTemplates/{workflow_template}", project=project, reg...
Creates new workflow template. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.WorkflowTemplateServiceClient() >>> >>> parent = client.region_path('[PROJECT]', '[REGION]') >>> >>> # TODO...
def create_workflow_template( self, parent, template, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates new workflow template. Example: >>> from google.clo...
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() ...
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 instanti...
Instantiates a template and begins execution. The returned Operation can be used to track execution of workflow by polling ``operations.get``. The Operation will complete when entire workflow is finished. The running workflow can be aborted via ``operations.cancel``. This will ...
def instantiate_workflow_template( self, name, version=None, instance_id=None, request_id=None, parameters=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ ...
Instantiates a template and begins execution. This method is equivalent to executing the sequence ``CreateWorkflowTemplate``, ``InstantiateWorkflowTemplate``, ``DeleteWorkflowTemplate``. The returned Operation can be used to track execution of workflow by polling ``operations.g...
def instantiate_inline_workflow_template( self, parent, template, instance_id=None, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Instantiates a te...
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.
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...
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:...
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: ...
Return a dictionary representing this schema field. Returns: dict: A dictionary representing the SchemaField in a serialized form.
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 = { ...
A tuple key that uniquely describes this field. Used to compute this instance's hashcode and evaluate equality. Returns: tuple: The contents of this :class:`~google.cloud.bigquery.schema.SchemaField`.
def _key(self): """A tuple key that uniquely describes this field. Used to compute this instance's hashcode and evaluate equality. Returns: tuple: The contents of this :class:`~google.cloud.bigquery.schema.SchemaField`. """ return ( se...
Parses 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...
Opens a database specified by the parameters from parse_options().
def open_database(parameters): """Opens a database specified by the parameters from parse_options().""" spanner_client = spanner.Client() instance_id = parameters['cloudspanner.instance'] instance = spanner_client.instance(instance_id) database_id = parameters['cloudspanner.database'] pool = spa...
Does a single read operation.
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(...
Loads keys from database.
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
Does a single update operation.
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...
Does a single operation and records latency.
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) ...
Aggregates 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('[O...
Runs workload against the database.
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...
Run a single thread of the workload.
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)): ...
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 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 m...
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 produc...
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 erro...
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 ...
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``, ``descrip...
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.
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 en...
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` fo...
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 ...
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.
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.Mutatio...
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.
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 w...
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.
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._muta...
Remember an entity's state to be saved during :meth:`commit`. .. note:: Any existing properties for the entity will be replaced by those currently set on this instance. Already-stored properties which do not correspond to keys set on this instance will be removed from ...
def put(self, entity): """Remember an entity's state to be saved during :meth:`commit`. .. note:: Any existing properties for the entity will be replaced by those currently set on this instance. Already-stored properties which do not correspond to keys set on this inst...
Remember a key to be deleted during :meth:`commit`. :type key: :class:`google.cloud.datastore.key.Key` :param key: the key to be deleted. :raises: :class:`~exceptions.ValueError` if the batch is not in progress, if key is not complete, or if the key's ``projec...
def delete(self, key): """Remember a key to be deleted during :meth:`commit`. :type key: :class:`google.cloud.datastore.key.Key` :param key: the key to be deleted. :raises: :class:`~exceptions.ValueError` if the batch is not in progress, if key is not complete, or if t...
Begins a batch. This method is called automatically when entering a with statement, however it can be called explicitly if you don't want to use a context manager. Overridden by :class:`google.cloud.datastore.transaction.Transaction`. :raises: :class:`ValueError` if the batch ...
def begin(self): """Begins a batch. This method is called automatically when entering a with statement, however it can be called explicitly if you don't want to use a context manager. Overridden by :class:`google.cloud.datastore.transaction.Transaction`. :raises: :clas...
Commits the batch. This is called by :meth:`commit`.
def _commit(self): """Commits the batch. This is called by :meth:`commit`. """ if self._id is None: mode = _datastore_pb2.CommitRequest.NON_TRANSACTIONAL else: mode = _datastore_pb2.CommitRequest.TRANSACTIONAL commit_response_pb = self._client._d...
Commits the batch. This is called automatically upon exiting a with statement, however it can be called explicitly if you don't want to use a context manager. :raises: :class:`~exceptions.ValueError` if the batch is not in progress.
def commit(self): """Commits the batch. This is called automatically upon exiting a with statement, however it can be called explicitly if you don't want to use a context manager. :raises: :class:`~exceptions.ValueError` if the batch is not in progress. ...
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.
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. """ ...
Return a fully-qualified snapshot string.
def snapshot_path(cls, project, instance, cluster, snapshot): """Return a fully-qualified snapshot string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}", project=project, instance=inst...
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()...
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. ...
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 fe...
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 ...
Permanently drop/delete a row range from a specified table. The request can specify whether to delete all rows in a table, or only those that match a particular prefix. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2...
def drop_row_range( self, name, row_key_prefix=None, delete_all_data_from_table=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Permanently drop/delete a row range from...
Return a fully-qualified company string.
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 )
Creates a new company entity. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompanyServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `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 ta...
Updates specified company. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompanyServiceClient() >>> >>> # TODO: Initialize `company`: >>> company = {} >>> >>> response = client...
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 im...
Deletes specified company. Prerequisite: The company has no jobs associated with it. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompanyServiceClient() >>> >>> name = client.company_path('[PROJECT]', '[...
def delete_company( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes specified company. Prerequisite: The company has no jobs associated with it. Example:...
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.
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. ...
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 ...
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 ...
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 :para...
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:`zon...
Sends new traces to Stackdriver Trace or updates existing traces. Args: traces (dict): Required. The traces to be patched in the API call. project_id (Optional[str]): ID of the Cloud project where the trace data is stored.
def patch_traces(self, traces, project_id=None): """Sends new traces to Stackdriver Trace or updates existing traces. Args: traces (dict): Required. The traces to be patched in the API call. project_id (Optional[str]): ID of the Cloud project where the trace dat...
Gets a single trace by its ID. Args: trace_id (str): ID of the trace to return. project_id (str): Required. ID of the Cloud project where the trace data is stored. Returns: A Trace dict.
def get_trace(self, trace_id, project_id=None): """ Gets a single trace by its ID. Args: trace_id (str): ID of the trace to return. project_id (str): Required. ID of the Cloud project where the trace data is stored. Returns: A Trace ...
Returns of a list of traces that match the filter conditions. Args: project_id (Optional[str]): ID of the Cloud project where the trace data is stored. view (Optional[~google.cloud.trace_v1.gapic.enums. ListTracesRequest.ViewType]): Type of data returned...
def list_traces( self, project_id=None, view=None, page_size=None, start_time=None, end_time=None, filter_=None, order_by=None, page_token=None, ): """ Returns of a list of traces that match the filter conditions. Args:...
Parses a resume into a ``Profile``. The API attempts to fill out the following profile fields if present within the resume: - personNames - addresses - emailAddress - phoneNumbers - personalUris - employmentRecords - educationRecords - ski...
def parse_resume( self, parent, resume, region_code=None, language_code=None, options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Parses a resume i...
Sample ID: go/samples-tracker/1533
def update_model(client, model_id): """Sample ID: go/samples-tracker/1533""" # [START bigquery_update_model_description] from google.cloud import bigquery # TODO(developer): Construct a BigQuery client object. # client = bigquery.Client() # TODO(developer): Set model_id to the ID of the model...
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 ...
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" fi...
Update the query's namespace. :type value: str
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
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...
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...
Set the ancestor for the query :type value: :class:`~google.cloud.datastore.key.Key` :param value: the new ancestor key
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
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, ``=``, ``<``, ``<=``,...
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 op...
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.
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(proje...
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 hyp...
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 prec...
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.
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): ...
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()) ...
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 ...
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.
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._qu...
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...
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 r...
Get the next page in the iterator. :rtype: :class:`~google.cloud.iterator.Page` :returns: The next page in the iterator (or :data:`None` if there are no pages left).
def _next_page(self): """Get the next page in the iterator. :rtype: :class:`~google.cloud.iterator.Page` :returns: The next page in the iterator (or :data:`None` if there are no pages left). """ if not self._more_results: return None query_...
Helper for :meth:`Batch.insert` et aliae. :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. :rtype: :class:`google.cloud.s...
def _make_write_pb(table, columns, values): """Helper for :meth:`Batch.insert` et aliae. :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 ...
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.
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 ...
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.
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 = ...
Commit mutations to the database. :rtype: datetime :returns: timestamp of the committed changes.
def commit(self): """Commit mutations to the database. :rtype: datetime :returns: timestamp of the committed changes. """ self._check_state() database = self._session._database api = database.spanner_api metadata = _metadata_with_prefix(database.name) ...
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 da...
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 lo...
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...
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. R...
Queries for entities. Example: >>> from google.cloud import datastore_v1 >>> >>> client = datastore_v1.DatastoreClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `parti...
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 enti...
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() >>> ...
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 ...
Return the GAE resource using the environment variables. :rtype: :class:`~google.cloud.logging.resource.Resource` :returns: Monitored resource for GAE.
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={ "p...
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.
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(...
Actually log the specified logging record. Overrides the default emit behavior of ``StreamHandler``. See https://docs.python.org/2/library/logging.html#handler-objects :type record: :class:`logging.LogRecord` :param record: The record to be logged.
def emit(self, record): """Actually log the specified logging record. Overrides the default emit behavior of ``StreamHandler``. See https://docs.python.org/2/library/logging.html#handler-objects :type record: :class:`logging.LogRecord` :param record: The record to be logged. ...
Return a fully-qualified service_account string.
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, ...
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]')...
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...
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]'...
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 ...
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_AC...
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. ...
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(...
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 ...
Return a fully-qualified entry string.
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=locatio...
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...
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 u...
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. ...
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 configurati...
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`` ...
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 itera...
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...
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: ...
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.
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: ...
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 do...
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 wr...
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 ...
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. ...
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 ...
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 i...