INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Trigger all callbacks registered to this Future. This method is called internally by the batch once the batch completes. Args: message_id (str): The message ID, as a string.
def _trigger(self): """Trigger all callbacks registered to this Future. This method is called internally by the batch once the batch completes. Args: message_id (str): The message ID, as a string. """ self._completed.set() for callback in self._callb...
Overrides transport.send(). :type record: :class:`logging.LogRecord` :param record: Python log record that the handler was called with. :type message: str :param message: The message from the ``LogRecord`` after being formatted by the associated log formatters. ...
def send( self, record, message, resource=None, labels=None, trace=None, span_id=None ): """Overrides transport.send(). :type record: :class:`logging.LogRecord` :param record: Python log record that the handler was called with. :type message: str :param message: The...
Creates a new read session. A read session divides the contents of a BigQuery table into one or more streams, which can then be used to read data from the table. The read session also specifies properties of the data to be read, such as a list of columns or a push-down filter describing ...
def create_read_session( self, table_reference, parent, table_modifiers=None, requested_streams=None, read_options=None, format_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=...
Reads rows from the table in the format prescribed by the read session. Each response contains one or more table rows, up to a maximum of 10 MiB per response; read requests which attempt to read individual rows larger than this will fail. Each request also returns a set of stream statis...
def read_rows( self, read_position, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Reads rows from the table in the format prescribed by the read session. Each response contains one...
Creates additional streams for a ReadSession. This API can be used to dynamically adjust the parallelism of a batch processing task upwards by adding additional workers. Example: >>> from google.cloud import bigquery_storage_v1beta1 >>> >>> client = bigquery_...
def batch_create_read_session_streams( self, session, requested_streams, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates additional streams for a ReadSession. This API can be...
Union[str, bytes]: The qualifier encoded in binary. The type is ``str`` (Python 2.x) or ``bytes`` (Python 3.x). The module will handle base64 encoding for you. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions.%28key%29.bigtableOptio...
def qualifier_encoded(self): """Union[str, bytes]: The qualifier encoded in binary. The type is ``str`` (Python 2.x) or ``bytes`` (Python 3.x). The module will handle base64 encoding for you. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query....
List[:class:`~.external_config.BigtableColumn`]: Lists of columns that should be exposed as individual fields. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions.(key).bigtableOptions.columnFamilies.columns https://cloud.google.com/big...
def columns(self): """List[:class:`~.external_config.BigtableColumn`]: Lists of columns that should be exposed as individual fields. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions.(key).bigtableOptions.columnFamilies.columns ...
List[:class:`~.external_config.BigtableColumnFamily`]: List of column families to expose in the table schema along with their types. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions.(key).bigtableOptions.columnFamilies https://cloud....
def column_families(self): """List[:class:`~.external_config.BigtableColumnFamily`]: List of column families to expose in the table schema along with their types. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions.(key).bigtableOptions...
List[:class:`~google.cloud.bigquery.schema.SchemaField`]: The schema for the data. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions.(key).schema https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#externalDataConfiguratio...
def schema(self): """List[:class:`~google.cloud.bigquery.schema.SchemaField`]: The schema for the data. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions.(key).schema https://cloud.google.com/bigquery/docs/reference/rest/v2/ta...
Build an API representation of this object. Returns: Dict[str, Any]: A dictionary in the format used by the BigQuery API.
def to_api_repr(self): """Build an API representation of this object. Returns: Dict[str, Any]: A dictionary in the format used by the BigQuery API. """ config = copy.deepcopy(self._properties) if self.options is not None: r = self.options....
Factory: construct an :class:`~.external_config.ExternalConfig` instance given its API representation. Args: resource (Dict[str, Any]): Definition of an :class:`~.external_config.ExternalConfig` instance in the same representation as is returned from the ...
def from_api_repr(cls, resource): """Factory: construct an :class:`~.external_config.ExternalConfig` instance given its API representation. Args: resource (Dict[str, Any]): Definition of an :class:`~.external_config.ExternalConfig` instance in the sam...
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('flake8', *LOCAL_DEPS) session.install('-e', '.') session.run( 'flake8', os.path.join('google', 'cloud', 'bigquery_storage_v1beta1...
Run the system test suite.
def system(session): """Run the system test suite.""" # Sanity check: Only run system tests if the environment variable is set. if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''): session.skip('Credentials must be set via environment variable.') # Install all test dependencies, then i...
Build the docs.
def docs(session): """Build the docs.""" session.install('sphinx', 'sphinx_rtd_theme') session.install('-e', '.[pandas,fastavro]') shutil.rmtree(os.path.join('docs', '_build'), ignore_errors=True) session.run( 'sphinx-build', '-W', # warnings as errors '-T', # show full t...
Convert a string representation of a binary operator to an enum. These enums come from the protobuf message definition ``StructuredQuery.FieldFilter.Operator``. Args: op_string (str): A comparison operation in the form of a string. Acceptable values are ``<``, ``<=``, ``==``, ``>=`` ...
def _enum_from_op_string(op_string): """Convert a string representation of a binary operator to an enum. These enums come from the protobuf message definition ``StructuredQuery.FieldFilter.Operator``. Args: op_string (str): A comparison operation in the form of a string. Acceptable...
Convert a string representation of a direction to an enum. Args: direction (str): A direction to order by. Must be one of :attr:`~.firestore.Query.ASCENDING` or :attr:`~.firestore.Query.DESCENDING`. Returns: int: The enum corresponding to ``direction``. Raises: ...
def _enum_from_direction(direction): """Convert a string representation of a direction to an enum. Args: direction (str): A direction to order by. Must be one of :attr:`~.firestore.Query.ASCENDING` or :attr:`~.firestore.Query.DESCENDING`. Returns: int: The enum corr...
Convert a specific protobuf filter to the generic filter type. Args: field_or_unary (Union[google.cloud.proto.firestore.v1beta1.\ query_pb2.StructuredQuery.FieldFilter, google.cloud.proto.\ firestore.v1beta1.query_pb2.StructuredQuery.FieldFilter]): A field or unary filte...
def _filter_pb(field_or_unary): """Convert a specific protobuf filter to the generic filter type. Args: field_or_unary (Union[google.cloud.proto.firestore.v1beta1.\ query_pb2.StructuredQuery.FieldFilter, google.cloud.proto.\ firestore.v1beta1.query_pb2.StructuredQuery.FieldFilte...
Convert a cursor pair to a protobuf. If ``cursor_pair`` is :data:`None`, just returns :data:`None`. Args: cursor_pair (Optional[Tuple[list, bool]]): Two-tuple of * a list of field values. * a ``before`` flag Returns: Optional[google.cloud.firestore_v1beta1.types.C...
def _cursor_pb(cursor_pair): """Convert a cursor pair to a protobuf. If ``cursor_pair`` is :data:`None`, just returns :data:`None`. Args: cursor_pair (Optional[Tuple[list, bool]]): Two-tuple of * a list of field values. * a ``before`` flag Returns: Optional[go...
Parse a query response protobuf to a document snapshot. Args: response_pb (google.cloud.proto.firestore.v1beta1.\ firestore_pb2.RunQueryResponse): A collection (~.firestore_v1beta1.collection.CollectionReference): A reference to the collection that initiated the query. ...
def _query_response_to_snapshot(response_pb, collection, expected_prefix): """Parse a query response protobuf to a document snapshot. Args: response_pb (google.cloud.proto.firestore.v1beta1.\ firestore_pb2.RunQueryResponse): A collection (~.firestore_v1beta1.collection.CollectionRef...
Project documents matching query to a limited set of fields. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. If the current query already has a projection set (i.e. has already called :meth:`~.firestore_v1beta1.query.Query.select`), thi...
def select(self, field_paths): """Project documents matching query to a limited set of fields. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. If the current query already has a projection set (i.e. has already called :meth:`~.f...
Filter the query on a field. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. Returns a new :class:`~.firestore_v1beta1.query.Query` that filters on a specific field path, according to an operation (e.g. ``==`` or "equals") and a...
def where(self, field_path, op_string, value): """Filter the query on a field. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. Returns a new :class:`~.firestore_v1beta1.query.Query` that filters on a specific field path, accordi...
Helper for :meth:`order_by`.
def _make_order(field_path, direction): """Helper for :meth:`order_by`.""" return query_pb2.StructuredQuery.Order( field=query_pb2.StructuredQuery.FieldReference(field_path=field_path), direction=_enum_from_direction(direction), )
Modify the query to add an order clause on a specific field. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. Successive :meth:`~.firestore_v1beta1.query.Query.order_by` calls will further refine the ordering of results returned by the q...
def order_by(self, field_path, direction=ASCENDING): """Modify the query to add an order clause on a specific field. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. Successive :meth:`~.firestore_v1beta1.query.Query.order_by` calls ...
Limit a query to return a fixed number of results. If the current query already has a limit set, this will overwrite it. Args: count (int): Maximum number of documents to return that match the query. Returns: ~.firestore_v1beta1.query.Query: A limited q...
def limit(self, count): """Limit a query to return a fixed number of results. If the current query already has a limit set, this will overwrite it. Args: count (int): Maximum number of documents to return that match the query. Returns: ~.firesto...
Skip to an offset in a query. If the current query already has specified an offset, this will overwrite it. Args: num_to_skip (int): The number of results to skip at the beginning of query results. (Must be non-negative.) Returns: ~.firestore_v1...
def offset(self, num_to_skip): """Skip to an offset in a query. If the current query already has specified an offset, this will overwrite it. Args: num_to_skip (int): The number of results to skip at the beginning of query results. (Must be non-negative.) ...
Set values to be used for a ``start_at`` or ``end_at`` cursor. The values will later be used in a query protobuf. When the query is sent to the server, the ``document_fields`` will be used in the order given by fields set by :meth:`~.firestore_v1beta1.query.Query.order_by`. Ar...
def _cursor_helper(self, document_fields, before, start): """Set values to be used for a ``start_at`` or ``end_at`` cursor. The values will later be used in a query protobuf. When the query is sent to the server, the ``document_fields`` will be used in the order given by fields set by ...
Start query results at a particular document value. The result set will **include** the document specified by ``document_fields``. If the current query already has specified a start cursor -- either via this method or :meth:`~.firestore_v1beta1.query.Query.start_after` -- this ...
def start_at(self, document_fields): """Start query results at a particular document value. The result set will **include** the document specified by ``document_fields``. If the current query already has specified a start cursor -- either via this method or :meth:`~.fir...
Start query results after a particular document value. The result set will **exclude** the document specified by ``document_fields``. If the current query already has specified a start cursor -- either via this method or :meth:`~.firestore_v1beta1.query.Query.start_at` -- this ...
def start_after(self, document_fields): """Start query results after a particular document value. The result set will **exclude** the document specified by ``document_fields``. If the current query already has specified a start cursor -- either via this method or :meth:...
End query results before a particular document value. The result set will **exclude** the document specified by ``document_fields``. If the current query already has specified an end cursor -- either via this method or :meth:`~.firestore_v1beta1.query.Query.end_at` -- this will...
def end_before(self, document_fields): """End query results before a particular document value. The result set will **exclude** the document specified by ``document_fields``. If the current query already has specified an end cursor -- either via this method or :meth:`~....
End query results at a particular document value. The result set will **include** the document specified by ``document_fields``. If the current query already has specified an end cursor -- either via this method or :meth:`~.firestore_v1beta1.query.Query.end_before` -- this will...
def end_at(self, document_fields): """End query results at a particular document value. The result set will **include** the document specified by ``document_fields``. If the current query already has specified an end cursor -- either via this method or :meth:`~.firestor...
Convert all the filters into a single generic Filter protobuf. This may be a lone field filter or unary filter, may be a composite filter or may be :data:`None`. Returns: google.cloud.firestore_v1beta1.types.\ StructuredQuery.Filter: A "generic" filter representing the ...
def _filters_pb(self): """Convert all the filters into a single generic Filter protobuf. This may be a lone field filter or unary filter, may be a composite filter or may be :data:`None`. Returns: google.cloud.firestore_v1beta1.types.\ StructuredQuery.Filter: A ...
Helper: convert field paths to message.
def _normalize_projection(projection): """Helper: convert field paths to message.""" if projection is not None: fields = list(projection.fields) if not fields: field_ref = query_pb2.StructuredQuery.FieldReference( field_path="__name__" ...
Helper: adjust orders based on cursors, where clauses.
def _normalize_orders(self): """Helper: adjust orders based on cursors, where clauses.""" orders = list(self._orders) _has_snapshot_cursor = False if self._start_at: if isinstance(self._start_at[0], document.DocumentSnapshot): _has_snapshot_cursor = True ...
Helper: convert cursor to a list of values based on orders.
def _normalize_cursor(self, cursor, orders): """Helper: convert cursor to a list of values based on orders.""" if cursor is None: return if not orders: raise ValueError(_NO_ORDERS_FOR_CURSOR) document_fields, before = cursor order_keys = [order.field.fi...
Convert the current query into the equivalent protobuf. Returns: google.cloud.firestore_v1beta1.types.StructuredQuery: The query protobuf.
def _to_protobuf(self): """Convert the current query into the equivalent protobuf. Returns: google.cloud.firestore_v1beta1.types.StructuredQuery: The query protobuf. """ projection = self._normalize_projection(self._projection) orders = self._normalize_or...
Deprecated alias for :meth:`stream`.
def get(self, transaction=None): """Deprecated alias for :meth:`stream`.""" warnings.warn( "'Query.get' is deprecated: please use 'Query.stream' instead.", DeprecationWarning, stacklevel=2, ) return self.stream(transaction=transaction)
Read the documents in the collection that match this query. This sends a ``RunQuery`` RPC and then returns an iterator which consumes each document returned in the stream of ``RunQueryResponse`` messages. .. note:: The underlying stream of responses will time out after ...
def stream(self, transaction=None): """Read the documents in the collection that match this query. This sends a ``RunQuery`` RPC and then returns an iterator which consumes each document returned in the stream of ``RunQueryResponse`` messages. .. note:: The underlyi...
Monitor the documents in this collection that match this query. This starts a watch on this query using a background thread. The provided callback is run on the snapshot of the documents. Args: callback(~.firestore.query.QuerySnapshot): a callback to run when a chan...
def on_snapshot(self, callback): """Monitor the documents in this collection that match this query. This starts a watch on this query using a background thread. The provided callback is run on the snapshot of the documents. Args: callback(~.firestore.query.QuerySnapshot): a...
Constructs a ModelReference. Args: model_id (str): the ID of the model. Returns: google.cloud.bigquery.model.ModelReference: A ModelReference for a model in this dataset.
def _get_model_reference(self, model_id): """Constructs a ModelReference. Args: model_id (str): the ID of the model. Returns: google.cloud.bigquery.model.ModelReference: A ModelReference for a model in this dataset. """ return ModelReference.from_api_repr( {"pro...
Construct the API resource representation of this access entry Returns: Dict[str, object]: Access entry represented as an API resource
def to_api_repr(self): """Construct the API resource representation of this access entry Returns: Dict[str, object]: Access entry represented as an API resource """ resource = {self.entity_type: self.entity_id} if self.role is not None: resource["role"] =...
Factory: construct an access entry given its API representation Args: resource (Dict[str, object]): Access entry resource representation returned from the API Returns: google.cloud.bigquery.dataset.AccessEntry: Access entry parsed from ``resource...
def from_api_repr(cls, resource): """Factory: construct an access entry given its API representation Args: resource (Dict[str, object]): Access entry resource representation returned from the API Returns: google.cloud.bigquery.dataset.AccessEntry: ...
Factory: construct a dataset reference given its API representation Args: resource (Dict[str, str]): Dataset reference resource representation returned from the API Returns: google.cloud.bigquery.dataset.DatasetReference: Dataset reference parsed...
def from_api_repr(cls, resource): """Factory: construct a dataset reference given its API representation Args: resource (Dict[str, str]): Dataset reference resource representation returned from the API Returns: google.cloud.bigquery.dataset.DatasetRefere...
List[google.cloud.bigquery.dataset.AccessEntry]: Dataset's access entries. ``role`` augments the entity type and must be present **unless** the entity type is ``view``. Raises: TypeError: If 'value' is not a sequence ValueError: If any item in th...
def access_entries(self): """List[google.cloud.bigquery.dataset.AccessEntry]: Dataset's access entries. ``role`` augments the entity type and must be present **unless** the entity type is ``view``. Raises: TypeError: If 'value' is not a sequence ValueErr...
Union[datetime.datetime, None]: Datetime at which the dataset was created (:data:`None` until set from the server).
def created(self): """Union[datetime.datetime, None]: Datetime at which the dataset was created (:data:`None` until set from the server). """ creation_time = self._properties.get("creationTime") if creation_time is not None: # creation_time will be in milliseconds. ...
Union[datetime.datetime, None]: Datetime at which the dataset was last modified (:data:`None` until set from the server).
def modified(self): """Union[datetime.datetime, None]: Datetime at which the dataset was last modified (:data:`None` until set from the server). """ modified_time = self._properties.get("lastModifiedTime") if modified_time is not None: # modified_time will be in milli...
Factory: construct a dataset given its API representation Args: resource (Dict[str: object]): Dataset resource representation returned from the API Returns: google.cloud.bigquery.dataset.Dataset: Dataset parsed from ``resource``.
def from_api_repr(cls, resource): """Factory: construct a dataset given its API representation Args: resource (Dict[str: object]): Dataset resource representation returned from the API Returns: google.cloud.bigquery.dataset.Dataset: Datas...
Grab prefixes after a :class:`~google.cloud.iterator.Page` started. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type page: :class:`~google.cloud.api.core.page_iterator.Page` :param page: The page that was just created. ...
def _blobs_page_start(iterator, page, response): """Grab prefixes after a :class:`~google.cloud.iterator.Page` started. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type page: :class:`~google.cloud.api.core.page_iterator.Page...
Convert a JSON blob to the native object. .. note:: This assumes that the ``bucket`` attribute has been added to the iterator after being created. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that has retrieved the item. :type item: d...
def _item_to_blob(iterator, item): """Convert a JSON blob to the native object. .. note:: This assumes that the ``bucket`` attribute has been added to the iterator after being created. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that ...
Factory: construct instance from resource. :type resource: dict :param resource: mapping as returned from API call. :rtype: :class:`LifecycleRuleDelete` :returns: Instance created from resource.
def from_api_repr(cls, resource): """Factory: construct instance from resource. :type resource: dict :param resource: mapping as returned from API call. :rtype: :class:`LifecycleRuleDelete` :returns: Instance created from resource. """ action = resource["action...
Factory: construct instance from resource. :type bucket: :class:`Bucket` :params bucket: Bucket for which this instance is the policy. :type resource: dict :param resource: mapping as returned from API call. :rtype: :class:`IAMConfiguration` :returns: Instance created...
def from_api_repr(cls, resource, bucket): """Factory: construct instance from resource. :type bucket: :class:`Bucket` :params bucket: Bucket for which this instance is the policy. :type resource: dict :param resource: mapping as returned from API call. :rtype: :class:...
Deadline for changing :attr:`bucket_policy_only_enabled` from true to false. If the bucket's :attr:`bucket_policy_only_enabled` is true, this property is time time after which that setting becomes immutable. If the bucket's :attr:`bucket_policy_only_enabled` is false, this property is ...
def bucket_policy_only_locked_time(self): """Deadline for changing :attr:`bucket_policy_only_enabled` from true to false. If the bucket's :attr:`bucket_policy_only_enabled` is true, this property is time time after which that setting becomes immutable. If the bucket's :attr:`bucket_pol...
Set the properties for the current object. :type value: dict or :class:`google.cloud.storage.batch._FutureDict` :param value: The properties to be set.
def _set_properties(self, value): """Set the properties for the current object. :type value: dict or :class:`google.cloud.storage.batch._FutureDict` :param value: The properties to be set. """ self._label_removals.clear() return super(Bucket, self)._set_properties(value)
Factory constructor for blob object. .. note:: This will not make an HTTP request; it simply instantiates a blob object owned by this bucket. :type blob_name: str :param blob_name: The name of the blob to be instantiated. :type chunk_size: int :param chunk_...
def blob( self, blob_name, chunk_size=None, encryption_key=None, kms_key_name=None, generation=None, ): """Factory constructor for blob object. .. note:: This will not make an HTTP request; it simply instantiates a blob object owne...
Factory: create a notification resource for the bucket. See: :class:`.BucketNotification` for parameters. :rtype: :class:`.BucketNotification`
def notification( self, topic_name, topic_project=None, custom_attributes=None, event_types=None, blob_name_prefix=None, payload_format=NONE_PAYLOAD_FORMAT, ): """Factory: create a notification resource for the bucket. See: :class:`.BucketNot...
Creates current bucket. If the bucket already exists, will raise :class:`google.cloud.exceptions.Conflict`. This implements "storage.buckets.insert". If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Clie...
def create(self, client=None, project=None, location=None): """Creates current bucket. If the bucket already exists, will raise :class:`google.cloud.exceptions.Conflict`. This implements "storage.buckets.insert". If :attr:`user_project` is set, bills the API request to that pr...
Sends all changed properties in a PATCH request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :par...
def patch(self, client=None): """Sends all changed properties in a PATCH request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ...
Get a blob object by name. This will return None if the blob doesn't exist: .. literalinclude:: snippets.py :start-after: [START get_blob] :end-before: [END get_blob] If :attr:`user_project` is set, bills the API request to that project. :type blob_name: str ...
def get_blob( self, blob_name, client=None, encryption_key=None, generation=None, **kwargs ): """Get a blob object by name. This will return None if the blob doesn't exist: .. literalinclude:: snippets.py :start-after: [START get_blob] :end-before: [END get_blob...
Return an iterator used to find blobs in the bucket. If :attr:`user_project` is set, bills the API request to that project. :type max_results: int :param max_results: (Optional) The maximum number of blobs in each page of results from this request. Non-positive values a...
def list_blobs( self, max_results=None, page_token=None, prefix=None, delimiter=None, versions=None, projection="noAcl", fields=None, client=None, ): """Return an iterator used to find blobs in the bucket. If :attr:`user_projec...
List Pub / Sub notifications for this bucket. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/list If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType...
def list_notifications(self, client=None): """List Pub / Sub notifications for this bucket. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/list If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.stor...
Delete this bucket. The bucket **must** be empty in order to submit a delete request. If ``force=True`` is passed, this will first attempt to delete all the objects / blobs in the bucket (i.e. try to empty the bucket). If the bucket doesn't exist, this will raise :class:`google...
def delete(self, force=False, client=None): """Delete this bucket. The bucket **must** be empty in order to submit a delete request. If ``force=True`` is passed, this will first attempt to delete all the objects / blobs in the bucket (i.e. try to empty the bucket). If the bucke...
Deletes a blob from the current bucket. If the blob isn't found (backend 404), raises a :class:`google.cloud.exceptions.NotFound`. For example: .. literalinclude:: snippets.py :start-after: [START delete_blob] :end-before: [END delete_blob] If :attr:`user_...
def delete_blob(self, blob_name, client=None, generation=None): """Deletes a blob from the current bucket. If the blob isn't found (backend 404), raises a :class:`google.cloud.exceptions.NotFound`. For example: .. literalinclude:: snippets.py :start-after: [START del...
Deletes a list of blobs from the current bucket. Uses :meth:`delete_blob` to delete each individual blob. If :attr:`user_project` is set, bills the API request to that project. :type blobs: list :param blobs: A list of :class:`~google.cloud.storage.blob.Blob`-s or ...
def delete_blobs(self, blobs, on_error=None, client=None): """Deletes a list of blobs from the current bucket. Uses :meth:`delete_blob` to delete each individual blob. If :attr:`user_project` is set, bills the API request to that project. :type blobs: list :param blobs: A list...
Copy the given blob to the given bucket, optionally with a new name. If :attr:`user_project` is set, bills the API request to that project. :type blob: :class:`google.cloud.storage.blob.Blob` :param blob: The blob to be copied. :type destination_bucket: :class:`google.cloud.storage.bu...
def copy_blob( self, blob, destination_bucket, new_name=None, client=None, preserve_acl=True, source_generation=None, ): """Copy the given blob to the given bucket, optionally with a new name. If :attr:`user_project` is set, bills the API requ...
Rename the given blob using copy and delete operations. If :attr:`user_project` is set, bills the API request to that project. Effectively, copies blob to the same bucket with a new name, then deletes the blob. .. warning:: This method will first duplicate the data and then...
def rename_blob(self, blob, new_name, client=None): """Rename the given blob using copy and delete operations. If :attr:`user_project` is set, bills the API request to that project. Effectively, copies blob to the same bucket with a new name, then deletes the blob. .. warning:...
Set default KMS encryption key for objects in the bucket. :type value: str or None :param value: new KMS key name (None to clear any existing key).
def default_kms_key_name(self, value): """Set default KMS encryption key for objects in the bucket. :type value: str or None :param value: new KMS key name (None to clear any existing key). """ encryption_config = self._properties.get("encryption", {}) encryption_config[...
Retrieve or set labels assigned to this bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets#labels .. note:: The getter for this property returns a dict which is a *copy* of the bucket's labels. Mutating that dict has no effect unless you th...
def labels(self): """Retrieve or set labels assigned to this bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets#labels .. note:: The getter for this property returns a dict which is a *copy* of the bucket's labels. Mutating that dict has no ef...
Set labels assigned to this bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets#labels :type mapping: :class:`dict` :param mapping: Name-value pairs (string->string) labelling the bucket.
def labels(self, mapping): """Set labels assigned to this bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets#labels :type mapping: :class:`dict` :param mapping: Name-value pairs (string->string) labelling the bucket. """ # If any labels have b...
Retrieve IAM configuration for this bucket. :rtype: :class:`IAMConfiguration` :returns: an instance for managing the bucket's IAM configuration.
def iam_configuration(self): """Retrieve IAM configuration for this bucket. :rtype: :class:`IAMConfiguration` :returns: an instance for managing the bucket's IAM configuration. """ info = self._properties.get("iamConfiguration", {}) return IAMConfiguration.from_api_repr(...
Retrieve or set lifecycle rules configured for this bucket. See https://cloud.google.com/storage/docs/lifecycle and https://cloud.google.com/storage/docs/json_api/v1/buckets .. note:: The getter for this property returns a list which contains *copies* of the bucket'...
def lifecycle_rules(self): """Retrieve or set lifecycle rules configured for this bucket. See https://cloud.google.com/storage/docs/lifecycle and https://cloud.google.com/storage/docs/json_api/v1/buckets .. note:: The getter for this property returns a list which conta...
Set lifestyle rules configured for this bucket. See https://cloud.google.com/storage/docs/lifecycle and https://cloud.google.com/storage/docs/json_api/v1/buckets :type entries: list of dictionaries :param entries: A sequence of mappings describing each lifecycle rule.
def lifecycle_rules(self, rules): """Set lifestyle rules configured for this bucket. See https://cloud.google.com/storage/docs/lifecycle and https://cloud.google.com/storage/docs/json_api/v1/buckets :type entries: list of dictionaries :param entries: A sequence of mappings...
Add a "delete" rule to lifestyle rules configured for this bucket. See https://cloud.google.com/storage/docs/lifecycle and https://cloud.google.com/storage/docs/json_api/v1/buckets .. literalinclude:: snippets.py :start-after: [START add_lifecycle_delete_rule] :end-bef...
def add_lifecycle_delete_rule(self, **kw): """Add a "delete" rule to lifestyle rules configured for this bucket. See https://cloud.google.com/storage/docs/lifecycle and https://cloud.google.com/storage/docs/json_api/v1/buckets .. literalinclude:: snippets.py :start-after...
Add a "delete" rule to lifestyle rules configured for this bucket. See https://cloud.google.com/storage/docs/lifecycle and https://cloud.google.com/storage/docs/json_api/v1/buckets .. literalinclude:: snippets.py :start-after: [START add_lifecycle_set_storage_class_rule] ...
def add_lifecycle_set_storage_class_rule(self, storage_class, **kw): """Add a "delete" rule to lifestyle rules configured for this bucket. See https://cloud.google.com/storage/docs/lifecycle and https://cloud.google.com/storage/docs/json_api/v1/buckets .. literalinclude:: snippets...
(Deprecated) Set `Bucket.location` This can only be set at bucket **creation** time. See https://cloud.google.com/storage/docs/json_api/v1/buckets and https://cloud.google.com/storage/docs/bucket-locations .. warning:: Assignment to 'Bucket.location' is deprecated, as it ...
def location(self, value): """(Deprecated) Set `Bucket.location` This can only be set at bucket **creation** time. See https://cloud.google.com/storage/docs/json_api/v1/buckets and https://cloud.google.com/storage/docs/bucket-locations .. warning:: Assignment to '...
Enable access logging for this bucket. See https://cloud.google.com/storage/docs/access-logs :type bucket_name: str :param bucket_name: name of bucket in which to store access logs :type object_prefix: str :param object_prefix: prefix for access log filenames
def enable_logging(self, bucket_name, object_prefix=""): """Enable access logging for this bucket. See https://cloud.google.com/storage/docs/access-logs :type bucket_name: str :param bucket_name: name of bucket in which to store access logs :type object_prefix: str :pa...
Retrieve the effective time of the bucket's retention policy. :rtype: datetime.datetime or ``NoneType`` :returns: point-in time at which the bucket's retention policy is effective, or ``None`` if the property is not set locally.
def retention_policy_effective_time(self): """Retrieve the effective time of the bucket's retention policy. :rtype: datetime.datetime or ``NoneType`` :returns: point-in time at which the bucket's retention policy is effective, or ``None`` if the property is not ...
Retrieve or set the retention period for items in the bucket. :rtype: int or ``NoneType`` :returns: number of seconds to retain items after upload or release from event-based lock, or ``None`` if the property is not set locally.
def retention_period(self): """Retrieve or set the retention period for items in the bucket. :rtype: int or ``NoneType`` :returns: number of seconds to retain items after upload or release from event-based lock, or ``None`` if the property is not set locally....
Set the retention period for items in the bucket. :type value: int :param value: number of seconds to retain items after upload or release from event-based lock. :raises ValueError: if the bucket's retention policy is locked.
def retention_period(self, value): """Set the retention period for items in the bucket. :type value: int :param value: number of seconds to retain items after upload or release from event-based lock. :raises ValueError: if the bucket's retention policy is locked...
Set the storage class for the bucket. See https://cloud.google.com/storage/docs/storage-classes :type value: str :param value: one of "MULTI_REGIONAL", "REGIONAL", "NEARLINE", "COLDLINE", "STANDARD", or "DURABLE_REDUCED_AVAILABILITY"
def storage_class(self, value): """Set the storage class for the bucket. See https://cloud.google.com/storage/docs/storage-classes :type value: str :param value: one of "MULTI_REGIONAL", "REGIONAL", "NEARLINE", "COLDLINE", "STANDARD", or "DURABLE_REDUCED_AVAILABIL...
Configure website-related properties. See https://cloud.google.com/storage/docs/hosting-static-website .. note:: This (apparently) only works if your bucket name is a domain name (and to do that, you need to get approved somehow...). If you want this bucket to ho...
def configure_website(self, main_page_suffix=None, not_found_page=None): """Configure website-related properties. See https://cloud.google.com/storage/docs/hosting-static-website .. note:: This (apparently) only works if your bucket name is a domain name (and to d...
Retrieve the IAM policy for the bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` ...
def get_iam_policy(self, client=None): """Retrieve the IAM policy for the bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.clien...
Update the IAM policy for the bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy If :attr:`user_project` is set, bills the API request to that project. :type policy: :class:`google.api_core.iam.Policy` :param policy: policy instance used to upda...
def set_iam_policy(self, policy, client=None): """Update the IAM policy for the bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy If :attr:`user_project` is set, bills the API request to that project. :type policy: :class:`google.api_core.iam.P...
Update bucket's ACL, revoking read access for anonymous users. :type recursive: bool :param recursive: If True, this will make all blobs inside the bucket private as well. :type future: bool :param future: If True, this will make all objects created in the ...
def make_private(self, recursive=False, future=False, client=None): """Update bucket's ACL, revoking read access for anonymous users. :type recursive: bool :param recursive: If True, this will make all blobs inside the bucket private as well. :type future: boo...
Create a signed upload policy for uploading objects. This method generates and signs a policy document. You can use `policy documents`_ to allow visitors to a website to upload files to Google Cloud Storage without giving them direct write access. For example: .. literalinclud...
def generate_upload_policy(self, conditions, expiration=None, client=None): """Create a signed upload policy for uploading objects. This method generates and signs a policy document. You can use `policy documents`_ to allow visitors to a website to upload files to Google Cloud Storage w...
Lock the bucket's retention policy. :raises ValueError: if the bucket has no metageneration (i.e., new or never reloaded); if the bucket has no retention policy assigned; if the bucket's retention policy is already locked.
def lock_retention_policy(self, client=None): """Lock the bucket's retention policy. :raises ValueError: if the bucket has no metageneration (i.e., new or never reloaded); if the bucket has no retention policy assigned; if the bucket's retention policy is already loc...
Generates a signed URL for this bucket. .. 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 st...
def generate_signed_url( self, expiration=None, api_access_endpoint=_API_ACCESS_ENDPOINT, method="GET", headers=None, query_parameters=None, client=None, credentials=None, version=None, ): """Generates a signed URL for this bucket. ...
Convert a datetime to microseconds since the unix epoch. Args: value (datetime.datetime): The datetime to covert. Returns: int: Microseconds since the unix epoch.
def to_microseconds(value): """Convert a datetime to microseconds since the unix epoch. Args: value (datetime.datetime): The datetime to covert. Returns: int: Microseconds since the unix epoch. """ if not value.tzinfo: value = value.replace(tzinfo=pytz.utc) # Regardless...
Convert a microsecond-precision timestamp to datetime. Args: value (str): The RFC3339 string to convert. Returns: datetime.datetime: The datetime object equivalent to the timestamp in UTC.
def from_rfc3339(value): """Convert a microsecond-precision timestamp to datetime. Args: value (str): The RFC3339 string to convert. Returns: datetime.datetime: The datetime object equivalent to the timestamp in UTC. """ return datetime.datetime.strptime(value, _RFC3339...
Convert a nanosecond-precision timestamp to a native datetime. .. note:: Python datetimes do not support nanosecond precision; this function therefore truncates such values to microseconds. Args: value (str): The RFC3339 string to convert. Returns: datetime.datetime: The d...
def from_rfc3339_nanos(value): """Convert a nanosecond-precision timestamp to a native datetime. .. note:: Python datetimes do not support nanosecond precision; this function therefore truncates such values to microseconds. Args: value (str): The RFC3339 string to convert. Ret...
Return an RFC 3339-compliant timestamp. Returns: (str): Timestamp string according to RFC 3339 spec.
def rfc3339(self): """Return an RFC 3339-compliant timestamp. Returns: (str): Timestamp string according to RFC 3339 spec. """ if self._nanosecond == 0: return to_rfc3339(self) nanos = str(self._nanosecond).rjust(9, '0').rstrip("0") return "{}.{}Z...
Parse RFC 3339-compliant timestamp, preserving nanoseconds. Args: stamp (str): RFC 3339 stamp, with up to nanosecond precision Returns: :class:`DatetimeWithNanoseconds`: an instance matching the timestamp string Raises: ValueError: if `stamp...
def from_rfc3339(cls, stamp): """Parse RFC 3339-compliant timestamp, preserving nanoseconds. Args: stamp (str): RFC 3339 stamp, with up to nanosecond precision Returns: :class:`DatetimeWithNanoseconds`: an instance matching the timestamp string ...
Return a timestamp message. Returns: (:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message
def timestamp_pb(self): """Return a timestamp message. Returns: (:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message """ inst = self if self.tzinfo is not None else self.replace(tzinfo=pytz.UTC) delta = inst - _UTC_EPOCH seconds = int(delta....
Parse RFC 3339-compliant timestamp, preserving nanoseconds. Args: stamp (:class:`~google.protobuf.timestamp_pb2.Timestamp`): timestamp message Returns: :class:`DatetimeWithNanoseconds`: an instance matching the timestamp message
def from_timestamp_pb(cls, stamp): """Parse RFC 3339-compliant timestamp, preserving nanoseconds. Args: stamp (:class:`~google.protobuf.timestamp_pb2.Timestamp`): timestamp message Returns: :class:`DatetimeWithNanoseconds`: an instance matching the times...
Creates a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>>...
def create_cluster( self, project_id, region, cluster, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a cluster in a project. Examp...
Deletes a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>>...
def delete_cluster( self, project_id, region, cluster_name, cluster_uuid=None, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a clus...
Gets the resource representation for a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' ...
def get_cluster( self, project_id, region, cluster_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the resource representation for a cluster in a project. ...
Lists all regions/{region}/clusters in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >...
def list_clusters( self, project_id, region, filter_=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists all regions/{region}/clusters in a pr...
Gets cluster diagnostic information. After the operation completes, the Operation.response field contains ``DiagnoseClusterOutputLocation``. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() ...
def diagnose_cluster( self, project_id, region, cluster_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets cluster diagnostic information. After the operation complet...
Actually publish all of the messages on the active batch. .. note:: This method is non-blocking. It opens a new thread, which calls :meth:`_commit`, which does block. This synchronously sets the batch status to "starting", and then opens a new thread, which handles act...
def commit(self): """Actually publish all of the messages on the active batch. .. note:: This method is non-blocking. It opens a new thread, which calls :meth:`_commit`, which does block. This synchronously sets the batch status to "starting", and then opens a ...
Actually publish all of the messages on the active batch. This moves the batch out from being the active batch to an in progress batch on the publisher, and then the batch is discarded upon completion. .. note:: This method blocks. The :meth:`commit` method is the non-bloc...
def _commit(self): """Actually publish all of the messages on the active batch. This moves the batch out from being the active batch to an in progress batch on the publisher, and then the batch is discarded upon completion. .. note:: This method blocks. The :meth:`...
Commit this batch after sufficient time has elapsed. This simply sleeps for ``self._settings.max_latency`` seconds, and then calls commit unless the batch has already been committed.
def monitor(self): """Commit this batch after sufficient time has elapsed. This simply sleeps for ``self._settings.max_latency`` seconds, and then calls commit unless the batch has already been committed. """ # NOTE: This blocks; it is up to the calling code to call it #...