text
stringlengths
81
112k
Generate a V2 signed URL to provide query-string auth'n to a resource. .. note:: Assumes ``credentials`` implements the :class:`google.auth.credentials.Signing` interface. Also assumes ``credentials`` has a ``service_account_email`` property which identifies the credentials. ....
Generate a V4 signed URL to provide query-string auth'n to a resource. .. note:: Assumes ``credentials`` implements the :class:`google.auth.credentials.Signing` interface. Also assumes ``credentials`` has a ``service_account_email`` property which identifies the credentials. ....
Return a fully-qualified glossary string. def glossary_path(cls, project, location, glossary): """Return a fully-qualified glossary string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/glossaries/{glossary}", project=project, ...
Translates input text and returns translated text. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> # TODO: Initialize `contents`: >>> contents = [] >...
Detects the language of text within a request. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> response = client.detect_language() Args: parent (str): O...
Returns a list of supported languages for translation. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> response = client.get_supported_languages() Args: ...
Translates a large volume of text in asynchronous batch mode. This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location. Thi...
Creates a glossary and returns the long-running operation. Returns NOT\_FOUND, if the project doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> parent =...
Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns NOT\_FOUND, if the glossary doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() ...
Return a copy of time_series with the points removed. def _extract_header(time_series): """Return a copy of time_series with the points removed.""" return TimeSeries( metric=time_series.metric, resource=time_series.resource, metric_kind=time_series.metric_kind, value_type=time_s...
Build the combined resource and metric labels, with resource_type. def _extract_labels(time_series): """Build the combined resource and metric labels, with resource_type.""" labels = {"resource_type": time_series.resource.type} labels.update(time_series.resource.labels) labels.update(time_series.metric...
Build a :mod:`pandas` dataframe out of time series. :type time_series_iterable: iterable over :class:`~google.cloud.monitoring_v3.types.TimeSeries` :param time_series_iterable: An iterable (e.g., a query object) yielding time series. :type label: str :param label: (Optional) Th...
Sort label names, putting well-known resource labels first. def _sorted_resource_labels(labels): """Sort label names, putting well-known resource labels first.""" head = [label for label in TOP_RESOURCE_LABELS if label in labels] tail = sorted(label for label in labels if label not in TOP_RESOURCE_LABELS) ...
Starts a thread and marks it as a daemon thread. def start_daemon_thread(*args, **kwargs): """Starts a thread and marks it as a daemon thread.""" thread = threading.Thread(*args, **kwargs) thread.daemon = True thread.start() return thread
Invoke a callback, swallowing and logging any exceptions. def safe_invoke_callback(callback, *args, **kwargs): """Invoke a callback, swallowing and logging any exceptions.""" # pylint: disable=bare-except # We intentionally want to swallow all exceptions. try: return callback(*args, **kwargs) ...
Create a project bound to the current client. Use :meth:`Project.reload() \ <google.cloud.resource_manager.project.Project.reload>` to retrieve project metadata after creating a :class:`~google.cloud.resource_manager.project.Project` instance. .. note: This does no...
Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: The ID for this project. :rtype: :class:...
List the projects visible to this client. Example:: >>> from google.cloud import resource_manager >>> client = resource_manager.Client() >>> for project in client.list_projects(): ... print(project.project_id) List all projects with label ``'environ...
Return a fully-qualified session string. def session_path(cls, project, instance, database, session): """Return a fully-qualified session string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/databases/{database}/sessions/{session}", pr...
Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions. Sessions can only execute one transaction at a time. To execute multiple concurrent read-writ...
Like ``ExecuteSql``, except returns the result set as a stream. Unlike ``ExecuteSql``, there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB. Example: >>> from google.c...
Executes a batch of SQL DML statements. This method allows many statements to be run with lower latency than submitting them sequentially with ``ExecuteSql``. Statements are executed in order, sequentially. ``ExecuteBatchDmlResponse`` will contain a ``ResultSet`` for each DML st...
Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ``ExecuteSql``. This method cannot be used to return a result set larger than 10 MiB; if the read matches more data than that, the read fails with a ``FAILED_PRECONDITION`` error. Reads ...
Commits a transaction. The request includes the mutations to be applied to rows in the database. ``Commit`` might return an ``ABORTED`` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other re...
Creates a set of partition tokens that can be used to execute a query operation in parallel. Each of the returned partition tokens can be used by ``ExecuteStreamingSql`` to specify a subset of the query result to read. The same session and read-only transaction must be used by the Partit...
Creates a set of partition tokens that can be used to execute a read operation in parallel. Each of the returned partition tokens can be used by ``StreamingRead`` to specify a subset of the read result to read. The same session and read-only transaction must be used by the PartitionReadR...
Report events issued when end user interacts with customer's application that uses Cloud Talent Solution. You may inspect the created events in `self service tools <https://console.cloud.google.com/talent-solution/overview>`__. `Learn more <https://cloud.google.com/talent-solutio...
Create an instance of the GAPIC Datastore API. :type client: :class:`~google.cloud.datastore.client.Client` :param client: The client that holds configuration details. :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient` :returns: A datastore API instance with the proper credentials. def m...
Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of Python corresponding to the ``nox`` binary the ``PATH`` can run the tests. def default(session): """Default unit test session. This is inten...
Run the snippets test suite. def snippets(session): """Run the snippets test suite.""" # Sanity check: Only run snippets tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable.") # I...
Run linters. Returns a failure if the linters find linting errors or sufficiently serious code quality issues. def lint(session): """Run linters. Returns a failure if the linters find linting errors or sufficiently serious code quality issues. """ session.install("black", "flake8", *LOCA...
Indent some text. Note that this is present as ``textwrap.indent``, but not in Python 2. Args: lines (str): The newline delimited string to be indented. prefix (Optional[str]): The prefix to indent each line with. Default to two spaces. Returns: str: The newly indented...
Return the time that the message was originally published. Returns: datetime: The date and time that the message was published. def publish_time(self): """Return the time that the message was originally published. Returns: datetime: The date and time that the message w...
Acknowledge the given message. Acknowledging a message in Pub/Sub means that you are done with it, and it will not be delivered to this subscription again. You should avoid acknowledging messages until you have *finished* processing them, so that in the event of a failure, you r...
Release the message from lease management. This informs the policy to no longer hold on to the lease for this message. Pub/Sub will re-deliver the message if it is not acknowledged before the existing lease expires. .. warning:: For most use cases, the only reason to drop a...
Inform the policy to lease this message continually. .. note:: This method is called by the constructor, and you should never need to call it manually. def lease(self): """Inform the policy to lease this message continually. .. note:: This method is called ...
Resets the deadline for acknowledgement. New deadline will be the given value of seconds from now. The default implementation handles this for you; you should not need to manually deal with setting ack deadlines. The exception case is if you are implementing your own custom subclass of...
Decline to acknowldge the given message. This will cause the message to be re-delivered to the subscription. def nack(self): """Decline to acknowldge the given message. This will cause the message to be re-delivered to the subscription. """ self._request_queue.put( ...
Runs a query while printing status updates Args: client (google.cloud.bigquery.client.Client): Client to bundle configuration needed for API requests. query (str): SQL query to be executed. Defaults to the standard SQL dialect. Use the ``job_config`` parameter to...
Underlying function for bigquery cell magic Note: This function contains the underlying logic for the 'bigquery' cell magic. This function is not meant to be called directly. Args: line (str): "%%bigquery" followed by arguments as required query (str): SQL query to run Ret...
google.auth.credentials.Credentials: Credentials to use for queries performed through IPython magics Note: These credentials do not need to be explicitly defined if you are using Application Default Credentials. If you are not using Application Default Credentials, m...
str: Default project to use for queries performed through IPython magics Note: The project does not need to be explicitly defined if you have an environment default project set. If you do not have a default project set in your environment, manually assign the project...
Return a fully-qualified database_root string. def database_root_path(cls, project, database): """Return a fully-qualified database_root string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}", project=project, database=datab...
Return a fully-qualified document_root string. def document_root_path(cls, project, database): """Return a fully-qualified document_root string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents", project=project, data...
Return a fully-qualified document_path string. def document_path_path(cls, project, database, document_path): """Return a fully-qualified document_path string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents/{document_path=**}", ...
Return a fully-qualified any_path string. def any_path_path(cls, project, database, document, any_path): """Return a fully-qualified any_path string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents/{document}/{any_path=**}", pro...
Gets a single document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> ...
Lists documents. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> ...
Creates a new document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> ...
Updates or inserts a document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> # TODO: Initialize `document`: >>> document = {} >>> >>> # TODO: In...
Deletes a document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>>...
Gets multiple documents. Documents returned by this method are not guaranteed to be returned in the same order that they were requested. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() ...
Starts a new transaction. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> >>> response = c...
Runs a query. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> for...
Streams batches of document updates and deletes, in order. EXPERIMENTAL: This method interface might change in the future. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> da...
Return a fully-qualified log string. def log_path(cls, project, log): """Return a fully-qualified log string.""" return google.api_core.path_template.expand( "projects/{project}/logs/{log}", project=project, log=log )
Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServi...
Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent (fluentd) and all logging libraries configured to use Logging. A single request may contain log entries for a maximum of 1000 ...
Lists log entries. Use this method to retrieve log entries from Logging. For ways to export log entries, see `Exporting Logs <https://cloud.google.com/logging/docs/export>`__. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.Loggin...
Expand a matched variable with its value. Args: positional_vars (list): A list of positonal variables. This list will be modified. named_vars (dict): A dictionary of named variables. match (re.Match): A regular expression match. Returns: str: The expanded variable t...
Expand a path template with the given variables. ..code-block:: python >>> expand('users/*/messages/*', 'me', '123') users/me/messages/123 >>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3') /v1/shelves/1/books/3 Args: tmpl (str): The path template. ...
Replace a variable match with a pattern that can be used to validate it. Args: match (re.Match): A regular expression match Returns: str: A regular expression pattern that can be used to validate the variable in an expanded path. Raises: ValueError: If an unexpected te...
Validate a path against the path template. .. code-block:: python >>> validate('users/*/messages/*', 'users/me/messages/123') True >>> validate('users/*/messages/*', 'users/me/drafts/123') False >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/books/3) Tru...
Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of Python corresponding to the ``nox`` binary the ``PATH`` can run the tests. def default(session): """Default unit test session. This is inten...
Create and return a gRPC channel object. Args: address (str): The host for the channel to use. credentials (~.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If ...
AppProfile name used in requests. .. note:: This property will not change if ``app_profile_id`` does not, but the return value is not cached. The AppProfile name is of the form ``"projects/../instances/../app_profile/{app_profile_id}"`` :rtype: str :re...
Creates an instance app_profile from a protobuf. :type app_profile_pb: :class:`instance_pb2.app_profile_pb` :param app_profile_pb: An instance protobuf object. :type instance: :class:`google.cloud.bigtable.instance.Instance` :param instance: The instance that owns the cluster. ...
Refresh self from the server-provided protobuf. Helper for :meth:`from_pb` and :meth:`reload`. def _update_from_pb(self, app_profile_pb): """Refresh self from the server-provided protobuf. Helper for :meth:`from_pb` and :meth:`reload`. """ self.routing_policy_type = None ...
Create an AppProfile proto buff message for API calls :rtype: :class:`.instance_pb2.AppProfile` :returns: The converted current object. :raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile routing_policy_type is not set def _to_pb(self): """Create an ...
Reload the metadata for this cluster def reload(self): """Reload the metadata for this cluster""" app_profile_pb = self.instance_admin_client.get_app_profile(self.name) # NOTE: _update_from_pb does not check that the project and # app_profile ID on the response match the request...
Check whether the AppProfile already exists. :rtype: bool :returns: True if the AppProfile exists, else False. def exists(self): """Check whether the AppProfile already exists. :rtype: bool :returns: True if the AppProfile exists, else False. """ try: ...
Create this AppProfile. .. note:: Uses the ``instance`` and ``app_profile_id`` on the current :class:`AppProfile` in addition to the ``routing_policy_type``, ``description``, ``cluster_id`` and ``allow_transactional_writes``. To change them before creating, rese...
Update this app_profile. .. note:: Update any or all of the following values: ``routing_policy_type`` ``description`` ``cluster_id`` ``allow_transactional_writes`` def update(self, ignore_warnings=None): """Update this app_profile. ...
Return a fully-qualified sink string. def sink_path(cls, project, sink): """Return a fully-qualified sink string.""" return google.api_core.path_template.expand( "projects/{project}/sinks/{sink}", project=project, sink=sink )
Return a fully-qualified exclusion string. def exclusion_path(cls, project, exclusion): """Return a fully-qualified exclusion string.""" return google.api_core.path_template.expand( "projects/{project}/exclusions/{exclusion}", project=project, exclusion=exclusion, ...
Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink. Exam...
Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. The updated sink might also have a new ``writer_identity``; see the ``unique_writer_identity`` field. Example: >>> from google.cloud...
Creates a new exclusion in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Cl...
Helper for :func:`_make_list_value_pbs`. :type value: scalar value :param value: value to convert :rtype: :class:`~google.protobuf.struct_pb2.Value` :returns: value protobufs :raises ValueError: if value is not of a known scalar type. def _make_value_pb(value): """Helper for :func:`_make_list...
Convert a Value protobuf to cell data. :type value_pb: :class:`~google.protobuf.struct_pb2.Value` :param value_pb: protobuf to convert :type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type` :param field_type: type code for the value :rtype: varies on field_type :returns: valu...
Convert a list of ListValue protobufs into a list of list of cell data. :type rows: list of :class:`~google.protobuf.struct_pb2.ListValue` :param rows: row data returned from a read/query :type row_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.StructType` :param row_type: row schema specificat...
Exports assets with time and resource types to a given Cloud Storage location. The output format is newline-delimited JSON. This API implements the ``google.longrunning.Operation`` API allowing you to keep track of the export. Example: >>> from google.cloud import asset_v1 ...
Batch gets the update history of assets that overlap a time window. For RESOURCE content, this API outputs history with asset in both non-delete or deleted status. For IAM\_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can create gap...
Extract and parse Avro schema from a read session. Args: read_session ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \ ): The read session associated with this read rows stream. This contains the schema, which is required to parse the data ...
Parse all rows in a stream block. Args: block ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \ ): A block containing Avro bytes to parse into rows. avro_schema (fastavro.schema): A parsed Avro schema, used to deserialized the bytes in t...
Copy a StreamPosition. Args: position (Union[ \ dict, \ ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \ ]): StreamPostion (or dictionary in StreamPosition format) to copy. Returns: ~google.cloud.bigquery_storage_v1beta1.types.StreamPosi...
Reconnect to the ReadRows stream using the most recent offset. def _reconnect(self): """Reconnect to the ReadRows stream using the most recent offset.""" self._wrapped = self._client.read_rows( _copy_stream_position(self._position), **self._read_rows_kwargs )
Create a :class:`pandas.DataFrame` of all rows in the stream. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavr...
A generator of all pages in the stream. Returns: types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]: A generator of pages. def pages(self): """A generator of all pages in the stream. Returns: types.GeneratorType[google.cloud.bigquer...
Create a :class:`pandas.DataFrame` of all rows in the stream. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavr...
Parse metadata and rows from the block only once. def _parse_block(self): """Parse metadata and rows from the block only once.""" if self._iter_rows is not None: return rows = _avro_rows(self._block, self._avro_schema) self._num_items = self._block.avro_rows.row_count ...
Get the next row in the page. def next(self): """Get the next row in the page.""" self._parse_block() if self._remaining > 0: self._remaining -= 1 return six.next(self._iter_rows)
Create a :class:`pandas.DataFrame` of rows in the page. This method requires the pandas libary to create a data frame and the fastavro library to parse row blocks. .. warning:: DATETIME columns are not supported. They are currently parsed as strings in the fastavro libr...
Return a fully-qualified instance_config string. def instance_config_path(cls, project, instance_config): """Return a fully-qualified instance_config string.""" return google.api_core.path_template.expand( "projects/{project}/instanceConfigs/{instance_config}", project=project, ...
Creates an instance and begins preparing it to begin serving. The returned ``long-running operation`` can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, ``CreateInstance`` returns ``ALREADY_E...
Updates an instance, and begins allocating or releasing resources as requested. The returned ``long-running operation`` can be used to track the progress of updating the instance. If the named instance does not exist, returns ``NOT_FOUND``. Immediately upon completion of this request: ...
Return a fully-qualified finding string. def finding_path(cls, project, scan_config, scan_run, finding): """Return a fully-qualified finding string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}", ...
Return a fully-qualified scan_config string. def scan_config_path(cls, project, scan_config): """Return a fully-qualified scan_config string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}", project=project, scan_config=...
Return a fully-qualified scan_run string. def scan_run_path(cls, project, scan_config, scan_run): """Return a fully-qualified scan_run string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}", project=project, ...
Helper for session-related API calls. def instance_admin_api(self): """Helper for session-related API calls.""" if self._instance_admin_api is None: self._instance_admin_api = InstanceAdminClient( credentials=self.credentials, client_info=_CLIENT_INFO ) r...