text
stringlengths
81
112k
Construct a reference to a dataset. :type dataset_id: str :param dataset_id: ID of the dataset. :type project: str :param project: (Optional) project ID for the dataset (defaults to the project of the client). :rtype: :class:`google.cloud.bigquery.datas...
API call: create the dataset via a POST request. See https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert Args: dataset (Union[ \ :class:`~google.cloud.bigquery.dataset.Dataset`, \ :class:`~google.cloud.bigquery.dataset.DatasetRefer...
API call: create a table via a PUT request See https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert Args: table (Union[ \ :class:`~google.cloud.bigquery.table.Table`, \ :class:`~google.cloud.bigquery.table.TableReference`, \ ...
Fetch the dataset referenced by ``dataset_ref`` Args: dataset_ref (Union[ \ :class:`~google.cloud.bigquery.dataset.DatasetReference`, \ str, \ ]): A reference to the dataset to fetch from the BigQuery API. If a string is pa...
[Beta] Fetch the model referenced by ``model_ref``. Args: model_ref (Union[ \ :class:`~google.cloud.bigquery.model.ModelReference`, \ str, \ ]): A reference to the model to fetch from the BigQuery API. If a string is passe...
Fetch the table referenced by ``table``. Args: table (Union[ \ :class:`~google.cloud.bigquery.table.Table`, \ :class:`~google.cloud.bigquery.table.TableReference`, \ str, \ ]): A reference to the table to fetch from the Big...
Change some fields of a dataset. Use ``fields`` to specify which fields to update. At least one field must be provided. If a field is listed in ``fields`` and is ``None`` in ``dataset``, it will be deleted. If ``dataset.etag`` is not ``None``, the update will only succeed if th...
[Beta] Change some fields of a model. Use ``fields`` to specify which fields to update. At least one field must be provided. If a field is listed in ``fields`` and is ``None`` in ``model``, it will be deleted. If ``model.etag`` is not ``None``, the update will only succeed if t...
Change some fields of a table. Use ``fields`` to specify which fields to update. At least one field must be provided. If a field is listed in ``fields`` and is ``None`` in ``table``, it will be deleted. If ``table.etag`` is not ``None``, the update will only succeed if the tabl...
[Beta] List models in the dataset. See https://cloud.google.com/bigquery/docs/reference/rest/v2/models/list Args: dataset (Union[ \ :class:`~google.cloud.bigquery.dataset.Dataset`, \ :class:`~google.cloud.bigquery.dataset.DatasetReference`, \ ...
Delete a dataset. See https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/delete Args dataset (Union[ \ :class:`~google.cloud.bigquery.dataset.Dataset`, \ :class:`~google.cloud.bigquery.dataset.DatasetReference`, \ str, ...
[Beta] Delete a model See https://cloud.google.com/bigquery/docs/reference/rest/v2/models/delete Args: model (Union[ \ :class:`~google.cloud.bigquery.model.Model`, \ :class:`~google.cloud.bigquery.model.ModelReference`, \ str, \ ...
Delete a table See https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/delete Args: table (Union[ \ :class:`~google.cloud.bigquery.table.Table`, \ :class:`~google.cloud.bigquery.table.TableReference`, \ str, \ ...
Get the query results object for a query job. Arguments: job_id (str): Name of the query job. retry (google.api_core.retry.Retry): (Optional) How to retry the RPC. project (str): (Optional) project ID for the query job (defaults to the ...
Detect correct job type from resource and instantiate. :type resource: dict :param resource: one job resource from API response :rtype: One of: :class:`google.cloud.bigquery.job.LoadJob`, :class:`google.cloud.bigquery.job.CopyJob`, :class:`google...
Attempt to cancel a job from a job ID. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel Arguments: job_id (str): Unique job identifier. Keyword Arguments: project (str): (Optional) ID of the project which owns the job (de...
List jobs for the project associated with this client. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/list Args: project (str, optional): Project ID to use for retreiving datasets. Defaults to the client's project. max_...
Starts a job for loading data into a table from CloudStorage. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load Arguments: source_uris (Union[str, Sequence[str]]): URIs of data files to be loaded; in format ``gs://<...
Upload the contents of this table from a file-like object. Similar to :meth:`load_table_from_uri`, this method creates, starts and returns a :class:`~google.cloud.bigquery.job.LoadJob`. Arguments: file_obj (file): A file handle opened in binary mode for reading. destina...
Upload the contents of a table from a pandas DataFrame. Similar to :meth:`load_table_from_uri`, this method creates, starts and returns a :class:`~google.cloud.bigquery.job.LoadJob`. Arguments: dataframe (pandas.DataFrame): A :class:`~pandas.DataFrame` containing th...
Perform a resumable upload. :type stream: IO[bytes] :param stream: A bytes IO object open for reading. :type metadata: dict :param metadata: The metadata associated with the upload. :type num_retries: int :param num_retries: Number of upload retries. (Deprecated: This ...
Initiate a resumable upload. :type stream: IO[bytes] :param stream: A bytes IO object open for reading. :type metadata: dict :param metadata: The metadata associated with the upload. :type num_retries: int :param num_retries: Number of upload retries. (Deprecated: This...
Perform a multipart upload. :type stream: IO[bytes] :param stream: A bytes IO object open for reading. :type metadata: dict :param metadata: The metadata associated with the upload. :type size: int :param size: The number of bytes to be uploaded (which will be read ...
Copy one or more tables to another table. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.copy Arguments: sources (Union[ \ :class:`~google.cloud.bigquery.table.Table`, \ :class:`~google.cloud.bigquery.table.TableRefer...
Start a job to extract a table into Cloud Storage files. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.extract Arguments: source (Union[ \ :class:`google.cloud.bigquery.table.Table`, \ :class:`google.cloud.bigquery.t...
Run a SQL query. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query Arguments: query (str): SQL query to be executed. Defaults to the standard SQL dialect. Use the ``job_config`` parameter to change dialects. ...
Insert rows into a table via the streaming API. See https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/insertAll Args: table (Union[ \ :class:`~google.cloud.bigquery.table.Table`, \ :class:`~google.cloud.bigquery.table.TableReference`...
Insert rows into a table without applying local type conversions. See https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/insertAll table (Union[ \ :class:`~google.cloud.bigquery.table.Table` \ :class:`~google.cloud.bigquery.table.TableReference`, \ ...
List the partitions in a table. Arguments: table (Union[ \ :class:`~google.cloud.bigquery.table.Table`, \ :class:`~google.cloud.bigquery.table.TableReference`, \ str, \ ]): The table or reference from which to get partition...
List the rows of the table. See https://cloud.google.com/bigquery/docs/reference/rest/v2/tabledata/list .. note:: This method assumes that the provided schema is up-to-date with the schema as defined on the back-end: if the two schemas are not identical, the v...
Helper function for schema_from_json that takes a file object that describes a table schema. Returns: List of schema field objects. def _schema_from_json_file_object(self, file_obj): """Helper function for schema_from_json that takes a file object that describes a table schema...
Helper function for schema_to_json that takes a schema list and file object and writes the schema list to the file object with json.dump def _schema_to_json_file_object(self, schema_list, file_obj): """Helper function for schema_to_json that takes a schema list and file object and writes the sc...
Takes a file object or file path that contains json that describes a table schema. Returns: List of schema field objects. def schema_from_json(self, file_or_path): """Takes a file object or file path that contains json that describes a table schema. Returns: ...
Takes a list of schema field objects. Serializes the list of schema field objects as json to a file. Destination is a file path or a file object. def schema_to_json(self, schema_list, destination): """Takes a list of schema field objects. Serializes the list of schema field objects a...
Refresh self from the server-provided protobuf. Helper for :meth:`from_pb` and :meth:`reload`. def _update_from_pb(self, instance_pb): """Refresh self from the server-provided protobuf. Helper for :meth:`from_pb` and :meth:`reload`. """ if not instance_pb.display_name: # Simp...
Creates an instance from a protobuf. :type instance_pb: :class:`google.spanner.v2.spanner_instance_admin_pb2.Instance` :param instance_pb: A instance protobuf object. :type client: :class:`~google.cloud.spanner_v1.client.Client` :param client: The client that owns the insta...
Make a copy of this instance. Copies the local data stored as simple types and copies the client attached to this instance. :rtype: :class:`~google.cloud.spanner_v1.instance.Instance` :returns: A copy of the current instance. def copy(self): """Make a copy of this instance. ...
Create this instance. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance .. note:: Uses the ``project`` and ``instance_id`` on the current :class:`Instance` in addition to the ...
Test whether this instance exists. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig :rtype: bool :returns: True if the instance exists, else false def exists(self): """Test whet...
Reload the metadata for this instance. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig :raises NotFound: if the instance does not exist def reload(self): """Reload the metadata for thi...
Update this instance. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance .. note:: Updates the ``display_name`` and ``node_count``. To change those values before updating, set ...
Mark an instance and all of its databases for permanent deletion. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstance Immediately upon completion of the request: * Billing will cease for all ...
Factory to create a database within this instance. :type database_id: str :param database_id: The ID of the instance. :type ddl_statements: list of string :param ddl_statements: (Optional) DDL statements, excluding the 'CREATE DATABSE' statement. ...
List databases for the instance. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases :type page_size: int :param page_size: Optional. The maximum number of databases in each page of...
Convert a database protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type database_pb: :class:`~google.spanner.admin.database.v1.Database` :param database_pb: A database returned from...
Poll and wait for the Future to be resolved. Args: timeout (int): How long (in seconds) to wait for the operation to complete. If None, wait indefinitely. def _blocking_poll(self, timeout=None): """Poll and wait for the Future to be resolved. Args: ...
Get the result of the operation, blocking if necessary. Args: timeout (int): How long (in seconds) to wait for the operation to complete. If None, wait indefinitely. Returns: google.protobuf.Message: The Operation's result. Raises: ...
Add a callback to be executed when the operation is complete. If the operation is not already complete, this will start a helper thread to poll for the status of the operation in the background. Args: fn (Callable[Future]): The callback to execute when the operation ...
Invoke all done callbacks. def _invoke_callbacks(self, *args, **kwargs): """Invoke all done callbacks.""" for callback in self._done_callbacks: _helpers.safe_invoke_callback(callback, *args, **kwargs)
Set the Future's result. def set_result(self, result): """Set the Future's result.""" self._result = result self._result_set = True self._invoke_callbacks(self)
Set the Future's exception. def set_exception(self, exception): """Set the Future's exception.""" self._exception = exception self._result_set = True self._invoke_callbacks(self)
Builds an HTTP context object from a Flask (Werkzeug) request object. This helper method extracts the relevant HTTP context from a Flask request object into an object ready to be sent to Error Reporting. .. code-block:: python >>> @app.errorhandler(HTTPException) ... def handle_error(ex...
Instantiate client. def instantiate_client(_unused_client, _unused_to_delete): """Instantiate client.""" # [START client_create_default] from google.cloud import logging client = logging.Client() # [END client_create_default] credentials = object() # [START client_create_explicit] fr...
List entries via client. def client_list_entries(client, to_delete): # pylint: disable=unused-argument """List entries via client.""" # [START client_list_entries_default] for entry in client.list_entries(): # API call(s) do_something_with(entry) # [END client_list_entries_default] # [S...
List entries via client across multiple projects. def client_list_entries_multi_project( client, to_delete ): # pylint: disable=unused-argument """List entries via client across multiple projects.""" # [START client_list_entries_multi_project] PROJECT_IDS = ["one-project", "another-project"] for ...
Logger usage. def logger_usage(client, to_delete): """Logger usage.""" LOG_NAME = "logger_usage_%d" % (_millis()) # [START logger_create] logger = client.logger(LOG_NAME) # [END logger_create] to_delete.append(logger) # [START logger_log_text] logger.log_text("A simple entry") # API ...
Metric CRUD. def metric_crud(client, to_delete): """Metric CRUD.""" METRIC_NAME = "robots-%d" % (_millis(),) DESCRIPTION = "Robots all up in your server" FILTER = "logName:apache-access AND textPayload:robot" UPDATED_FILTER = "textPayload:robot" UPDATED_DESCRIPTION = "Danger, Will Robinson!" ...
Sink log entries to storage. def sink_storage(client, to_delete): """Sink log entries to storage.""" bucket = _sink_storage_setup(client) to_delete.append(bucket) SINK_NAME = "robots-storage-%d" % (_millis(),) FILTER = "textPayload:robot" # [START sink_storage_create] DESTINATION = "storag...
Sink log entries to bigquery. def sink_bigquery(client, to_delete): """Sink log entries to bigquery.""" dataset = _sink_bigquery_setup(client) to_delete.append(dataset) SINK_NAME = "robots-bigquery-%d" % (_millis(),) FILTER = "textPayload:robot" # [START sink_bigquery_create] DESTINATION =...
Sink log entries to pubsub. def sink_pubsub(client, to_delete): """Sink log entries to pubsub.""" topic = _sink_pubsub_setup(client) to_delete.append(topic) SINK_NAME = "robots-pubsub-%d" % (_millis(),) FILTER = "logName:apache-access AND textPayload:robot" UPDATED_FILTER = "textPayload:robot" ...
Issue a warning if `distribution_name` is installed. In a future release, this method will be updated to raise ImportError rather than just send a warning. Args: distribution_name (str): The name of the obsolete distribution. def complain(distribution_name): """Issue a warning if `distributio...
Builds customer encryption key headers :type key: bytes :param key: 32 byte key to build request key and hash. :type source: bool :param source: If true, return headers for the "source" blob; otherwise, return headers for the "destination" blob. :rtype: dict :returns: dict ...
Re-wrap and raise an ``InvalidResponse`` exception. :type error: :exc:`google.resumable_media.InvalidResponse` :param error: A caught exception from the ``google-resumable-media`` library. :raises: :class:`~google.cloud.exceptions.GoogleCloudError` corresponding to the faile...
Add one query parameter to a base URL. :type base_url: string :param base_url: Base URL (may already contain query parameters) :type name_value_pairs: list of (string, string) tuples. :param name_value_pairs: Names and values of the query parameters to add :rtype: string :returns: URL with ad...
Set the blob's default chunk size. :type value: int :param value: (Optional) The current blob's chunk size, if it is set. :raises: :class:`ValueError` if ``value`` is not ``None`` and is not a multiple of 256 KB. def chunk_size(self, value): """Set the blob's default ...
Getter property for the URL path to this Blob. :rtype: str :returns: The URL path to this Blob. def path(self): """Getter property for the URL path to this Blob. :rtype: str :returns: The URL path to this Blob. """ if not self.name: raise ValueError...
Default query parameters. def _query_params(self): """Default query parameters.""" params = {} if self.generation is not None: params["generation"] = self.generation if self.user_project is not None: params["userProject"] = self.user_project return params
The public URL for this blob. Use :meth:`make_public` to enable anonymous access via the returned URL. :rtype: `string` :returns: The public URL for this blob. def public_url(self): """The public URL for this blob. Use :meth:`make_public` to enable anonymous access vi...
Generates a signed URL for this blob. .. note:: If you are on Google Compute Engine, you can't generate a signed URL using GCE service account. Follow `Issue 50`_ for updates on this. If you'd like to be able to generate a signed URL from GCE, you can use a stan...
Determines whether or not this blob exists. 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, ...
Deletes a blob from Cloud Storage. 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 bac...
Get the download URL for the current blob. If the ``media_link`` has been loaded, it will be used, otherwise the URL will be constructed from the current blob's path (and possibly generation) to avoid a round trip. :rtype: str :returns: The download URL for the current blob. d...
Perform a download without any error handling. This is intended to be called by :meth:`download_to_file` so it can be wrapped with error handling / remapping. :type transport: :class:`~google.auth.transport.requests.AuthorizedSession` :param transport: The transport (with c...
Download the contents of this blob into a file-like object. .. note:: If the server-set property, :attr:`media_link`, is not yet initialized, makes an additional API request to load it. Downloading a file that has been encrypted with a `customer-supplied`_ encryption key...
Download the contents of this blob into a named file. If :attr:`user_project` is set on the bucket, bills the API request to that project. :type filename: str :param filename: A filename to be passed to ``open``. :type client: :class:`~google.cloud.storage.client.Client` or ...
Download the contents of this blob as a string. 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 pass...
Determine the content type from the current object. The return value will be determined in order of precedence: - The value passed in to this method (if not :data:`None`) - The value stored on the current blob - The default value ('application/octet-stream') :type content_type...
Get the object / blob metadata which is writable. This is intended to be used when creating a new object / blob. See the `API reference docs`_ for more information, the fields marked as writable are: * ``acl`` * ``cacheControl`` * ``contentDisposition`` * ``con...
Get required arguments for performing an upload. The content type returned will be determined in order of precedence: - The value passed in to this method (if not :data:`None`) - The value stored on the current blob - The default value ('application/octet-stream') :type conten...
Perform a multipart upload. The content type of the upload will be determined in order of precedence: - The value passed in to this method (if not :data:`None`) - The value stored on the current blob - The default value ('application/octet-stream') :type client: :class...
Initiate a resumable upload. The content type of the upload will be determined in order of precedence: - The value passed in to this method (if not :data:`None`) - The value stored on the current blob - The default value ('application/octet-stream') :type client: :clas...
Perform a resumable upload. Assumes ``chunk_size`` is not :data:`None` on the current blob. The content type of the upload will be determined in order of precedence: - The value passed in to this method (if not :data:`None`) - The value stored on the current blob - The...
Determine an upload strategy and then perform the upload. If the size of the data to be uploaded exceeds 5 MB a resumable media request will be used, otherwise the content and the metadata will be uploaded in a single multipart upload request. The content type of the upload will be det...
Upload the contents of this blob from a file-like object. The content type of the upload will be determined in order of precedence: - The value passed in to this method (if not :data:`None`) - The value stored on the current blob - The default value ('application/octet-stream')...
Upload this blob's contents from the content of a named file. The content type of the upload will be determined in order of precedence: - The value passed in to this method (if not :data:`None`) - The value stored on the current blob - The value given by ``mimetypes.guess_type`...
Upload contents of this blob from the provided string. .. note:: The effect of uploading to an existing blob depends on the "versioning" and "lifecycle" policies defined on the blob's bucket. In the absence of those policies, upload will overwrite any existing conte...
Create a resumable upload session. Resumable upload sessions allow you to start an upload session from one client and complete the session in another. This method is called by the initiator to set the metadata and limits. The initiator then passes the session URL to the client that will...
Update blob's ACL, granting read access to anonymous users. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the blob's bucket. def ...
Update blob's ACL, revoking read access for anonymous users. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the blob's bucket. def...
Concatenate source blobs into this one. If :attr:`user_project` is set on the bucket, bills the API request to that project. :type sources: list of :class:`Blob` :param sources: blobs whose contents will be composed into this blob. :type client: :class:`~google.cloud.storage.c...
Rewrite source blob into this one. If :attr:`user_project` is set on the bucket, bills the API request to that project. :type source: :class:`Blob` :param source: blob whose contents will be rewritten into this blob. :type token: str :param token: Optional. Token retur...
Update blob's storage class via a rewrite-in-place. This helper will wait for the rewrite to complete before returning, so it may take some time for large files. See https://cloud.google.com/storage/docs/per-object-storage-class If :attr:`user_project` is set on the bucket, bil...
Verifies that a ``path`` has the correct form. Checks that all of the elements in ``path`` are strings. Args: path (Tuple[str, ...]): The components in a collection or document path. is_collection (bool): Indicates if the ``path`` represents a document or a collection. ...
Converts a native Python value into a Firestore protobuf ``Value``. Args: value (Union[NoneType, bool, int, float, datetime.datetime, \ str, bytes, dict, ~google.cloud.Firestore.GeoPoint]): A native Python value to convert to a protobuf field. Returns: ~google.cloud.fir...
Encode a dictionary into protobuf ``Value``-s. Args: values_dict (dict): The dictionary to encode as protobuf fields. Returns: Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A dictionary of string keys and ``Value`` protobufs as dictionary values. def encode_dict(valu...
Convert a reference value string to a document. Args: reference_value (str): A document reference value. client (~.firestore_v1beta1.client.Client): A client that has a document factory. Returns: ~.firestore_v1beta1.document.DocumentReference: The document correspon...
Converts a Firestore protobuf ``Value`` to a native Python value. Args: value (google.cloud.firestore_v1beta1.types.Value): A Firestore protobuf to be decoded / parsed / converted. client (~.firestore_v1beta1.client.Client): A client that has a document factory. Returns...
Converts a protobuf map of Firestore ``Value``-s. Args: value_fields (google.protobuf.pyext._message.MessageMapContainer): A protobuf map of Firestore ``Value``-s. client (~.firestore_v1beta1.client.Client): A client that has a document factory. Returns: Dict[st...
Parse a document ID from a document protobuf. Args: document_pb (google.cloud.proto.firestore.v1beta1.\ document_pb2.Document): A protobuf for a document that was created in a ``CreateDocument`` RPC. expected_prefix (str): The expected collection prefix for the f...
Do depth-first walk of tree, yielding field_path, value def extract_fields(document_data, prefix_path, expand_dots=False): """Do depth-first walk of tree, yielding field_path, value""" if not document_data: yield prefix_path, _EmptyDict else: for key, value in sorted(six.iteritems(document_...