Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _query_response_to_snapshot(response_pb, collection, expected_prefix): if not response_pb.HasField("document"): return None document_id = _helpers.get_doc_id(response_pb.document, expected_prefix) reference = collection.document(document_id) ...
[ "Parse a query response protobuf to a document snapshot.\n\n Args:\n response_pb (google.cloud.proto.firestore.v1beta1.\\\n firestore_pb2.RunQueryResponse): A\n collection (~.firestore_v1beta1.collection.CollectionReference): A\n reference to the collection that initiated the ...
Please provide a description of the function:def select(self, field_paths): field_paths = list(field_paths) for field_path in field_paths: field_path_module.split_field_path(field_path) # raises new_projection = query_pb2.StructuredQuery.Projection( fields=[ ...
[ "Project documents matching query to a limited set of fields.\n\n See :meth:`~.firestore_v1beta1.client.Client.field_path` for\n more information on **field paths**.\n\n If the current query already has a projection set (i.e. has already\n called :meth:`~.firestore_v1beta1.query.Query.se...
Please provide a description of the function:def where(self, field_path, op_string, value): field_path_module.split_field_path(field_path) # raises if value is None: if op_string != _EQ_OP: raise ValueError(_BAD_OP_NAN_NULL) filter_pb = query_pb2.Struct...
[ "Filter the query on a field.\n\n See :meth:`~.firestore_v1beta1.client.Client.field_path` for\n more information on **field paths**.\n\n Returns a new :class:`~.firestore_v1beta1.query.Query` that\n filters on a specific field path, according to an operation (e.g.\n ``==`` or \"e...
Please provide a description of the function:def _make_order(field_path, direction): return query_pb2.StructuredQuery.Order( field=query_pb2.StructuredQuery.FieldReference(field_path=field_path), direction=_enum_from_direction(direction), )
[ "Helper for :meth:`order_by`." ]
Please provide a description of the function:def order_by(self, field_path, direction=ASCENDING): field_path_module.split_field_path(field_path) # raises order_pb = self._make_order(field_path, direction) new_orders = self._orders + (order_pb,) return self.__class__( ...
[ "Modify the query to add an order clause on a specific field.\n\n See :meth:`~.firestore_v1beta1.client.Client.field_path` for\n more information on **field paths**.\n\n Successive :meth:`~.firestore_v1beta1.query.Query.order_by` calls\n will further refine the ordering of results return...
Please provide a description of the function:def limit(self, count): return self.__class__( self._parent, projection=self._projection, field_filters=self._field_filters, orders=self._orders, limit=count, offset=self._offset, ...
[ "Limit a query to return a fixed number of results.\n\n If the current query already has a limit set, this will overwrite it.\n\n Args:\n count (int): Maximum number of documents to return that match\n the query.\n\n Returns:\n ~.firestore_v1beta1.query.Quer...
Please provide a description of the function:def offset(self, num_to_skip): return self.__class__( self._parent, projection=self._projection, field_filters=self._field_filters, orders=self._orders, limit=self._limit, offset=num_to_...
[ "Skip to an offset in a query.\n\n If the current query already has specified an offset, this will\n overwrite it.\n\n Args:\n num_to_skip (int): The number of results to skip at the beginning\n of query results. (Must be non-negative.)\n\n Returns:\n ...
Please provide a description of the function:def _cursor_helper(self, document_fields, before, start): if isinstance(document_fields, tuple): document_fields = list(document_fields) elif isinstance(document_fields, document.DocumentSnapshot): if document_fields.reference...
[ "Set values to be used for a ``start_at`` or ``end_at`` cursor.\n\n The values will later be used in a query protobuf.\n\n When the query is sent to the server, the ``document_fields`` will\n be used in the order given by fields set by\n :meth:`~.firestore_v1beta1.query.Query.order_by`.\...
Please provide a description of the function:def start_at(self, document_fields): return self._cursor_helper(document_fields, before=True, start=True)
[ "Start query results at a particular document value.\n\n The result set will **include** the document specified by\n ``document_fields``.\n\n If the current query already has specified a start cursor -- either\n via this method or\n :meth:`~.firestore_v1beta1.query.Query.start_aft...
Please provide a description of the function:def start_after(self, document_fields): return self._cursor_helper(document_fields, before=False, start=True)
[ "Start query results after a particular document value.\n\n The result set will **exclude** the document specified by\n ``document_fields``.\n\n If the current query already has specified a start cursor -- either\n via this method or\n :meth:`~.firestore_v1beta1.query.Query.start_...
Please provide a description of the function:def end_before(self, document_fields): return self._cursor_helper(document_fields, before=True, start=False)
[ "End query results before a particular document value.\n\n The result set will **exclude** the document specified by\n ``document_fields``.\n\n If the current query already has specified an end cursor -- either\n via this method or\n :meth:`~.firestore_v1beta1.query.Query.end_at` ...
Please provide a description of the function:def end_at(self, document_fields): return self._cursor_helper(document_fields, before=False, start=False)
[ "End query results at a particular document value.\n\n The result set will **include** the document specified by\n ``document_fields``.\n\n If the current query already has specified an end cursor -- either\n via this method or\n :meth:`~.firestore_v1beta1.query.Query.end_before` ...
Please provide a description of the function:def _filters_pb(self): num_filters = len(self._field_filters) if num_filters == 0: return None elif num_filters == 1: return _filter_pb(self._field_filters[0]) else: composite_filter = query_pb2.Str...
[ "Convert all the filters into a single generic Filter protobuf.\n\n This may be a lone field filter or unary filter, may be a composite\n filter or may be :data:`None`.\n\n Returns:\n google.cloud.firestore_v1beta1.types.\\\n StructuredQuery.Filter: A \"generic\" filter re...
Please provide a description of the function:def _normalize_projection(projection): if projection is not None: fields = list(projection.fields) if not fields: field_ref = query_pb2.StructuredQuery.FieldReference( field_path="__name__" ...
[ "Helper: convert field paths to message." ]
Please provide a description of the function:def _normalize_orders(self): orders = list(self._orders) _has_snapshot_cursor = False if self._start_at: if isinstance(self._start_at[0], document.DocumentSnapshot): _has_snapshot_cursor = True if self._e...
[ "Helper: adjust orders based on cursors, where clauses." ]
Please provide a description of the function:def _normalize_cursor(self, cursor, orders): if cursor is None: return if not orders: raise ValueError(_NO_ORDERS_FOR_CURSOR) document_fields, before = cursor order_keys = [order.field.field_path for order i...
[ "Helper: convert cursor to a list of values based on orders." ]
Please provide a description of the function:def _to_protobuf(self): projection = self._normalize_projection(self._projection) orders = self._normalize_orders() start_at = self._normalize_cursor(self._start_at, orders) end_at = self._normalize_cursor(self._end_at, orders) ...
[ "Convert the current query into the equivalent protobuf.\n\n Returns:\n google.cloud.firestore_v1beta1.types.StructuredQuery: The\n query protobuf.\n " ]
Please provide a description of the function:def get(self, transaction=None): warnings.warn( "'Query.get' is deprecated: please use 'Query.stream' instead.", DeprecationWarning, stacklevel=2, ) return self.stream(transaction=transaction)
[ "Deprecated alias for :meth:`stream`." ]
Please provide a description of the function:def stream(self, transaction=None): parent_path, expected_prefix = self._parent._parent_info() response_iterator = self._client._firestore_api.run_query( parent_path, self._to_protobuf(), transaction=_helpers.get_t...
[ "Read the documents in the collection that match this query.\n\n This sends a ``RunQuery`` RPC and then returns an iterator which\n consumes each document returned in the stream of ``RunQueryResponse``\n messages.\n\n .. note::\n\n The underlying stream of responses will time o...
Please provide a description of the function:def on_snapshot(self, callback): return Watch.for_query( self, callback, document.DocumentSnapshot, document.DocumentReference )
[ "Monitor the documents in this collection that match this query.\n\n This starts a watch on this query using a background thread. The\n provided callback is run on the snapshot of the documents.\n\n Args:\n callback(~.firestore.query.QuerySnapshot): a callback to run when\n ...
Please provide a description of the function:def _get_model_reference(self, model_id): return ModelReference.from_api_repr( {"projectId": self.project, "datasetId": self.dataset_id, "modelId": model_id} )
[ "Constructs a ModelReference.\n\n Args:\n model_id (str): the ID of the model.\n\n Returns:\n google.cloud.bigquery.model.ModelReference:\n A ModelReference for a model in this dataset.\n " ]
Please provide a description of the function:def to_api_repr(self): resource = {self.entity_type: self.entity_id} if self.role is not None: resource["role"] = self.role return resource
[ "Construct the API resource representation of this access entry\n\n Returns:\n Dict[str, object]: Access entry represented as an API resource\n " ]
Please provide a description of the function:def from_api_repr(cls, resource): entry = resource.copy() role = entry.pop("role", None) entity_type, entity_id = entry.popitem() if len(entry) != 0: raise ValueError("Entry has unexpected keys remaining.", entry) ...
[ "Factory: construct an access entry given its API representation\n\n Args:\n resource (Dict[str, object]):\n Access entry resource representation returned from the API\n\n Returns:\n google.cloud.bigquery.dataset.AccessEntry:\n Access entry parsed fr...
Please provide a description of the function:def from_api_repr(cls, resource): project = resource["projectId"] dataset_id = resource["datasetId"] return cls(project, dataset_id)
[ "Factory: construct a dataset reference given its API representation\n\n Args:\n resource (Dict[str, str]):\n Dataset reference resource representation returned from the API\n\n Returns:\n google.cloud.bigquery.dataset.DatasetReference:\n Dataset ref...
Please provide a description of the function:def from_string(cls, dataset_id, default_project=None): output_dataset_id = dataset_id output_project_id = default_project parts = dataset_id.split(".") if len(parts) == 1 and not default_project: raise ValueError( ...
[ "Construct a dataset reference from dataset ID string.\n\n Args:\n dataset_id (str):\n A dataset ID in standard SQL format. If ``default_project``\n is not specified, this must included both the project ID and\n the dataset ID, separated by ``.``.\n ...
Please provide a description of the function:def access_entries(self): entries = self._properties.get("access", []) return [AccessEntry.from_api_repr(entry) for entry in entries]
[ "List[google.cloud.bigquery.dataset.AccessEntry]: Dataset's access\n entries.\n\n ``role`` augments the entity type and must be present **unless** the\n entity type is ``view``.\n\n Raises:\n TypeError: If 'value' is not a sequence\n ValueError:\n If ...
Please provide a description of the function:def created(self): creation_time = self._properties.get("creationTime") if creation_time is not None: # creation_time will be in milliseconds. return google.cloud._helpers._datetime_from_microseconds( 1000.0 * ...
[ "Union[datetime.datetime, None]: Datetime at which the dataset was\n created (:data:`None` until set from the server).\n " ]
Please provide a description of the function:def modified(self): modified_time = self._properties.get("lastModifiedTime") if modified_time is not None: # modified_time will be in milliseconds. return google.cloud._helpers._datetime_from_microseconds( 1000...
[ "Union[datetime.datetime, None]: Datetime at which the dataset was\n last modified (:data:`None` until set from the server).\n " ]
Please provide a description of the function:def from_api_repr(cls, resource): if ( "datasetReference" not in resource or "datasetId" not in resource["datasetReference"] ): raise KeyError( "Resource lacks required identity information:" ...
[ "Factory: construct a dataset given its API representation\n\n Args:\n resource (Dict[str: object]):\n Dataset resource representation returned from the API\n\n Returns:\n google.cloud.bigquery.dataset.Dataset:\n Dataset parsed from ``resource``.\n ...
Please provide a description of the function:def _blobs_page_start(iterator, page, response): page.prefixes = tuple(response.get("prefixes", ())) iterator.prefixes.update(page.prefixes)
[ "Grab prefixes after a :class:`~google.cloud.iterator.Page` started.\n\n :type iterator: :class:`~google.api_core.page_iterator.Iterator`\n :param iterator: The iterator that is currently in use.\n\n :type page: :class:`~google.cloud.api.core.page_iterator.Page`\n :param page: The page that was just cre...
Please provide a description of the function:def _item_to_blob(iterator, item): name = item.get("name") blob = Blob(name, bucket=iterator.bucket) blob._set_properties(item) return blob
[ "Convert a JSON blob to the native object.\n\n .. note::\n\n This assumes that the ``bucket`` attribute has been\n added to the iterator after being created.\n\n :type iterator: :class:`~google.api_core.page_iterator.Iterator`\n :param iterator: The iterator that has retrieved the item.\n\n ...
Please provide a description of the function:def from_api_repr(cls, resource): action = resource["action"] instance = cls(action["storageClass"], _factory=True) instance.update(resource) return instance
[ "Factory: construct instance from resource.\n\n :type resource: dict\n :param resource: mapping as returned from API call.\n\n :rtype: :class:`LifecycleRuleDelete`\n :returns: Instance created from resource.\n " ]
Please provide a description of the function:def from_api_repr(cls, resource, bucket): instance = cls(bucket) instance.update(resource) return instance
[ "Factory: construct instance from resource.\n\n :type bucket: :class:`Bucket`\n :params bucket: Bucket for which this instance is the policy.\n\n :type resource: dict\n :param resource: mapping as returned from API call.\n\n :rtype: :class:`IAMConfiguration`\n :returns: In...
Please provide a description of the function:def bucket_policy_only_locked_time(self): bpo = self.get("bucketPolicyOnly", {}) stamp = bpo.get("lockedTime") if stamp is not None: stamp = _rfc3339_to_datetime(stamp) return stamp
[ "Deadline for changing :attr:`bucket_policy_only_enabled` from true to false.\n\n If the bucket's :attr:`bucket_policy_only_enabled` is true, this property\n is time time after which that setting becomes immutable.\n\n If the bucket's :attr:`bucket_policy_only_enabled` is false, this property\n...
Please provide a description of the function:def _set_properties(self, value): self._label_removals.clear() return super(Bucket, self)._set_properties(value)
[ "Set the properties for the current object.\n\n :type value: dict or :class:`google.cloud.storage.batch._FutureDict`\n :param value: The properties to be set.\n " ]
Please provide a description of the function:def blob( self, blob_name, chunk_size=None, encryption_key=None, kms_key_name=None, generation=None, ): return Blob( name=blob_name, bucket=self, chunk_size=chunk_size, ...
[ "Factory constructor for blob object.\n\n .. note::\n This will not make an HTTP request; it simply instantiates\n a blob object owned by this bucket.\n\n :type blob_name: str\n :param blob_name: The name of the blob to be instantiated.\n\n :type chunk_size: int\n ...
Please provide a description of the function:def notification( self, topic_name, topic_project=None, custom_attributes=None, event_types=None, blob_name_prefix=None, payload_format=NONE_PAYLOAD_FORMAT, ): return BucketNotification( ...
[ "Factory: create a notification resource for the bucket.\n\n See: :class:`.BucketNotification` for parameters.\n\n :rtype: :class:`.BucketNotification`\n " ]
Please provide a description of the function:def create(self, client=None, project=None, location=None): if self.user_project is not None: raise ValueError("Cannot create bucket with 'user_project' set.") client = self._require_client(client) if project is None: ...
[ "Creates current bucket.\n\n If the bucket already exists, will raise\n :class:`google.cloud.exceptions.Conflict`.\n\n This implements \"storage.buckets.insert\".\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type client: :class:`~google.cloud.sto...
Please provide a description of the function:def patch(self, client=None): # Special case: For buckets, it is possible that labels are being # removed; this requires special handling. if self._label_removals: self._changes.add("labels") self._properties.setdefaul...
[ "Sends all changed properties in a PATCH request.\n\n Updates the ``_properties`` with the response from the backend.\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type client: :class:`~google.cloud.storage.client.Client` or\n ``NoneType``\...
Please provide a description of the function:def get_blob( self, blob_name, client=None, encryption_key=None, generation=None, **kwargs ): blob = Blob( bucket=self, name=blob_name, encryption_key=encryption_key, generation=generation, ...
[ "Get a blob object by name.\n\n This will return None if the blob doesn't exist:\n\n .. literalinclude:: snippets.py\n :start-after: [START get_blob]\n :end-before: [END get_blob]\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type blob_...
Please provide a description of the function:def list_blobs( self, max_results=None, page_token=None, prefix=None, delimiter=None, versions=None, projection="noAcl", fields=None, client=None, ): extra_params = {"projection": pr...
[ "Return an iterator used to find blobs in the bucket.\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type max_results: int\n :param max_results:\n (Optional) The maximum number of blobs in each page of results\n from this request. Non-posit...
Please provide a description of the function:def list_notifications(self, client=None): client = self._require_client(client) path = self.path + "/notificationConfigs" iterator = page_iterator.HTTPIterator( client=client, api_request=client._connection.api_reques...
[ "List Pub / Sub notifications for this bucket.\n\n See:\n https://cloud.google.com/storage/docs/json_api/v1/notifications/list\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type client: :class:`~google.cloud.storage.client.Client` or\n ...
Please provide a description of the function:def delete(self, force=False, client=None): client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project if force: blobs = list( ...
[ "Delete this bucket.\n\n The bucket **must** be empty in order to submit a delete request. If\n ``force=True`` is passed, this will first attempt to delete all the\n objects / blobs in the bucket (i.e. try to empty the bucket).\n\n If the bucket doesn't exist, this will raise\n :c...
Please provide a description of the function:def delete_blob(self, blob_name, client=None, generation=None): client = self._require_client(client) blob = Blob(blob_name, bucket=self, generation=generation) # We intentionally pass `_target_object=None` since a DELETE # request h...
[ "Deletes a blob from the current bucket.\n\n If the blob isn't found (backend 404), raises a\n :class:`google.cloud.exceptions.NotFound`.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START delete_blob]\n :end-before: [END delete_blob]\n\n ...
Please provide a description of the function:def delete_blobs(self, blobs, on_error=None, client=None): for blob in blobs: try: blob_name = blob if not isinstance(blob_name, six.string_types): blob_name = blob.name self.del...
[ "Deletes a list of blobs from the current bucket.\n\n Uses :meth:`delete_blob` to delete each individual blob.\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type blobs: list\n :param blobs: A list of :class:`~google.cloud.storage.blob.Blob`-s or\n ...
Please provide a description of the function:def copy_blob( self, blob, destination_bucket, new_name=None, client=None, preserve_acl=True, source_generation=None, ): client = self._require_client(client) query_params = {} if s...
[ "Copy the given blob to the given bucket, optionally with a new name.\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type blob: :class:`google.cloud.storage.blob.Blob`\n :param blob: The blob to be copied.\n\n :type destination_bucket: :class:`google.clou...
Please provide a description of the function:def rename_blob(self, blob, new_name, client=None): same_name = blob.name == new_name new_blob = self.copy_blob(blob, self, new_name, client=client) if not same_name: blob.delete(client=client) return new_blob
[ "Rename the given blob using copy and delete operations.\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n Effectively, copies blob to the same bucket with a new name, then\n deletes the blob.\n\n .. warning::\n\n This method will first duplicate the...
Please provide a description of the function:def default_kms_key_name(self, value): encryption_config = self._properties.get("encryption", {}) encryption_config["defaultKmsKeyName"] = value self._patch_property("encryption", encryption_config)
[ "Set default KMS encryption key for objects in the bucket.\n\n :type value: str or None\n :param value: new KMS key name (None to clear any existing key).\n " ]
Please provide a description of the function:def labels(self): labels = self._properties.get("labels") if labels is None: return {} return copy.deepcopy(labels)
[ "Retrieve or set labels assigned to this bucket.\n\n See\n https://cloud.google.com/storage/docs/json_api/v1/buckets#labels\n\n .. note::\n\n The getter for this property returns a dict which is a *copy*\n of the bucket's labels. Mutating that dict has no effect unless\n ...
Please provide a description of the function:def labels(self, mapping): # If any labels have been expressly removed, we need to track this # so that a future .patch() call can do the correct thing. existing = set([k for k in self.labels.keys()]) incoming = set([k for k in mappin...
[ "Set labels assigned to this bucket.\n\n See\n https://cloud.google.com/storage/docs/json_api/v1/buckets#labels\n\n :type mapping: :class:`dict`\n :param mapping: Name-value pairs (string->string) labelling the bucket.\n " ]
Please provide a description of the function:def iam_configuration(self): info = self._properties.get("iamConfiguration", {}) return IAMConfiguration.from_api_repr(info, self)
[ "Retrieve IAM configuration for this bucket.\n\n :rtype: :class:`IAMConfiguration`\n :returns: an instance for managing the bucket's IAM configuration.\n " ]
Please provide a description of the function:def lifecycle_rules(self): info = self._properties.get("lifecycle", {}) for rule in info.get("rule", ()): action_type = rule["action"]["type"] if action_type == "Delete": yield LifecycleRuleDelete.from_api_repr...
[ "Retrieve or set lifecycle rules configured for this bucket.\n\n See https://cloud.google.com/storage/docs/lifecycle and\n https://cloud.google.com/storage/docs/json_api/v1/buckets\n\n .. note::\n\n The getter for this property returns a list which contains\n *copies* o...
Please provide a description of the function:def lifecycle_rules(self, rules): rules = [dict(rule) for rule in rules] # Convert helpers if needed self._patch_property("lifecycle", {"rule": rules})
[ "Set lifestyle rules configured for this bucket.\n\n See https://cloud.google.com/storage/docs/lifecycle and\n https://cloud.google.com/storage/docs/json_api/v1/buckets\n\n :type entries: list of dictionaries\n :param entries: A sequence of mappings describing each lifecycle rule.\n...
Please provide a description of the function:def add_lifecycle_delete_rule(self, **kw): rules = list(self.lifecycle_rules) rules.append(LifecycleRuleDelete(**kw)) self.lifecycle_rules = rules
[ "Add a \"delete\" rule to lifestyle rules configured for this bucket.\n\n See https://cloud.google.com/storage/docs/lifecycle and\n https://cloud.google.com/storage/docs/json_api/v1/buckets\n\n .. literalinclude:: snippets.py\n :start-after: [START add_lifecycle_delete_rule]\n ...
Please provide a description of the function:def add_lifecycle_set_storage_class_rule(self, storage_class, **kw): rules = list(self.lifecycle_rules) rules.append(LifecycleRuleSetStorageClass(storage_class, **kw)) self.lifecycle_rules = rules
[ "Add a \"delete\" rule to lifestyle rules configured for this bucket.\n\n See https://cloud.google.com/storage/docs/lifecycle and\n https://cloud.google.com/storage/docs/json_api/v1/buckets\n\n .. literalinclude:: snippets.py\n :start-after: [START add_lifecycle_set_storage_class_...
Please provide a description of the function:def location(self, value): warnings.warn(_LOCATION_SETTER_MESSAGE, DeprecationWarning, stacklevel=2) self._location = value
[ "(Deprecated) Set `Bucket.location`\n\n This can only be set at bucket **creation** time.\n\n See https://cloud.google.com/storage/docs/json_api/v1/buckets and\n https://cloud.google.com/storage/docs/bucket-locations\n\n .. warning::\n\n Assignment to 'Bucket.location' is depr...
Please provide a description of the function:def enable_logging(self, bucket_name, object_prefix=""): info = {"logBucket": bucket_name, "logObjectPrefix": object_prefix} self._patch_property("logging", info)
[ "Enable access logging for this bucket.\n\n See https://cloud.google.com/storage/docs/access-logs\n\n :type bucket_name: str\n :param bucket_name: name of bucket in which to store access logs\n\n :type object_prefix: str\n :param object_prefix: prefix for access log filenames\n ...
Please provide a description of the function:def retention_policy_effective_time(self): policy = self._properties.get("retentionPolicy") if policy is not None: timestamp = policy.get("effectiveTime") if timestamp is not None: return _rfc3339_to_datetime(t...
[ "Retrieve the effective time of the bucket's retention policy.\n\n :rtype: datetime.datetime or ``NoneType``\n :returns: point-in time at which the bucket's retention policy is\n effective, or ``None`` if the property is not\n set locally.\n " ]
Please provide a description of the function:def retention_period(self): policy = self._properties.get("retentionPolicy") if policy is not None: period = policy.get("retentionPeriod") if period is not None: return int(period)
[ "Retrieve or set the retention period for items in the bucket.\n\n :rtype: int or ``NoneType``\n :returns: number of seconds to retain items after upload or release\n from event-based lock, or ``None`` if the property is not\n set locally.\n " ]
Please provide a description of the function:def retention_period(self, value): policy = self._properties.setdefault("retentionPolicy", {}) if value is not None: policy["retentionPeriod"] = str(value) else: policy = None self._patch_property("retentionPol...
[ "Set the retention period for items in the bucket.\n\n :type value: int\n :param value:\n number of seconds to retain items after upload or release from\n event-based lock.\n\n :raises ValueError: if the bucket's retention policy is locked.\n " ]
Please provide a description of the function:def storage_class(self, value): if value not in self._STORAGE_CLASSES: raise ValueError("Invalid storage class: %s" % (value,)) self._patch_property("storageClass", value)
[ "Set the storage class for the bucket.\n\n See https://cloud.google.com/storage/docs/storage-classes\n\n :type value: str\n :param value: one of \"MULTI_REGIONAL\", \"REGIONAL\", \"NEARLINE\",\n \"COLDLINE\", \"STANDARD\", or \"DURABLE_REDUCED_AVAILABILITY\"\n " ]
Please provide a description of the function:def configure_website(self, main_page_suffix=None, not_found_page=None): data = {"mainPageSuffix": main_page_suffix, "notFoundPage": not_found_page} self._patch_property("website", data)
[ "Configure website-related properties.\n\n See https://cloud.google.com/storage/docs/hosting-static-website\n\n .. note::\n This (apparently) only works\n if your bucket name is a domain name\n (and to do that, you need to get approved somehow...).\n\n If you want thi...
Please provide a description of the function:def get_iam_policy(self, client=None): client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project info = client._connection.api_request( ...
[ "Retrieve the IAM policy for the bucket.\n\n See\n https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type client: :class:`~google.cloud.storage.client.Client` or\n ``...
Please provide a description of the function:def set_iam_policy(self, policy, client=None): client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project resource = policy.to_api_repr() ...
[ "Update the IAM policy for the bucket.\n\n See\n https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type policy: :class:`google.api_core.iam.Policy`\n :param policy: policy instance...
Please provide a description of the function:def make_private(self, recursive=False, future=False, client=None): self.acl.all().revoke_read() self.acl.save(client=client) if future: doa = self.default_object_acl if not doa.loaded: doa.reload(clie...
[ "Update bucket's ACL, revoking read access for anonymous users.\n\n :type recursive: bool\n :param recursive: If True, this will make all blobs inside the bucket\n private as well.\n\n :type future: bool\n :param future: If True, this will make all objects create...
Please provide a description of the function:def generate_upload_policy(self, conditions, expiration=None, client=None): client = self._require_client(client) credentials = client._base_connection.credentials _signing.ensure_signed_credentials(credentials) if expiration is None...
[ "Create a signed upload policy for uploading objects.\n\n This method generates and signs a policy document. You can use\n `policy documents`_ to allow visitors to a website to upload files to\n Google Cloud Storage without giving them direct write access.\n\n For example:\n\n .. ...
Please provide a description of the function:def lock_retention_policy(self, client=None): if "metageneration" not in self._properties: raise ValueError("Bucket has no retention policy assigned: try 'reload'?") policy = self._properties.get("retentionPolicy") if policy is ...
[ "Lock the bucket's retention policy.\n\n :raises ValueError:\n if the bucket has no metageneration (i.e., new or never reloaded);\n if the bucket has no retention policy assigned;\n if the bucket's retention policy is already locked.\n " ]
Please provide a description of the function: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.\n\n .. note::\n\n If you are on Google Compute Engine, you can't generate a signed\n URL using GCE service account. Follow `Issue 50`_ for updates on\n this. If you'd like to be able to generate a signed URL from GCE,\n you ...
Please provide a description of the function:def to_microseconds(value): if not value.tzinfo: value = value.replace(tzinfo=pytz.utc) # Regardless of what timezone is on the value, convert it to UTC. value = value.astimezone(pytz.utc) # Convert the datetime to a microsecond timestamp. re...
[ "Convert a datetime to microseconds since the unix epoch.\n\n Args:\n value (datetime.datetime): The datetime to covert.\n\n Returns:\n int: Microseconds since the unix epoch.\n " ]
Please provide a description of the function:def from_rfc3339(value): return datetime.datetime.strptime(value, _RFC3339_MICROS).replace(tzinfo=pytz.utc)
[ "Convert a microsecond-precision timestamp to datetime.\n\n Args:\n value (str): The RFC3339 string to convert.\n\n Returns:\n datetime.datetime: The datetime object equivalent to the timestamp in\n UTC.\n " ]
Please provide a description of the function:def from_rfc3339_nanos(value): with_nanos = _RFC3339_NANOS.match(value) if with_nanos is None: raise ValueError( "Timestamp: {!r}, does not match pattern: {!r}".format( value, _RFC3339_NANOS.pattern ) ) ...
[ "Convert a nanosecond-precision timestamp to a native datetime.\n\n .. note::\n Python datetimes do not support nanosecond precision; this function\n therefore truncates such values to microseconds.\n\n Args:\n value (str): The RFC3339 string to convert.\n\n Returns:\n datetime....
Please provide a description of the function:def rfc3339(self): if self._nanosecond == 0: return to_rfc3339(self) nanos = str(self._nanosecond).rjust(9, '0').rstrip("0") return "{}.{}Z".format(self.strftime(_RFC3339_NO_FRACTION), nanos)
[ "Return an RFC 3339-compliant timestamp.\n\n Returns:\n (str): Timestamp string according to RFC 3339 spec.\n " ]
Please provide a description of the function:def from_rfc3339(cls, stamp): with_nanos = _RFC3339_NANOS.match(stamp) if with_nanos is None: raise ValueError( "Timestamp: {}, does not match pattern: {}".format( stamp, _RFC3339_NANOS.pattern ...
[ "Parse RFC 3339-compliant timestamp, preserving nanoseconds.\n\n Args:\n stamp (str): RFC 3339 stamp, with up to nanosecond precision\n\n Returns:\n :class:`DatetimeWithNanoseconds`:\n an instance matching the timestamp string\n\n Raises:\n ValueE...
Please provide a description of the function:def timestamp_pb(self): inst = self if self.tzinfo is not None else self.replace(tzinfo=pytz.UTC) delta = inst - _UTC_EPOCH seconds = int(delta.total_seconds()) nanos = self._nanosecond or self.microsecond * 1000 return timest...
[ "Return a timestamp message.\n\n Returns:\n (:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message\n " ]
Please provide a description of the function:def from_timestamp_pb(cls, stamp): microseconds = int(stamp.seconds * 1e6) bare = from_microseconds(microseconds) return cls( bare.year, bare.month, bare.day, bare.hour, bare.minute,...
[ "Parse RFC 3339-compliant timestamp, preserving nanoseconds.\n\n Args:\n stamp (:class:`~google.protobuf.timestamp_pb2.Timestamp`): timestamp message\n\n Returns:\n :class:`DatetimeWithNanoseconds`:\n an instance matching the timestamp message\n " ]
Please provide a description of the function: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, ): # Wr...
[ "\n Creates a cluster in a project.\n\n Example:\n >>> from google.cloud import dataproc_v1beta2\n >>>\n >>> client = dataproc_v1beta2.ClusterControllerClient()\n >>>\n >>> # TODO: Initialize `project_id`:\n >>> project_id = ''\n ...
Please provide a description of the function: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=No...
[ "\n Deletes a cluster in a project.\n\n Example:\n >>> from google.cloud import dataproc_v1beta2\n >>>\n >>> client = dataproc_v1beta2.ClusterControllerClient()\n >>>\n >>> # TODO: Initialize `project_id`:\n >>> project_id = ''\n ...
Please provide a description of the function: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, ): # Wrap the transport method...
[ "\n Gets the resource representation for a cluster in a project.\n\n Example:\n >>> from google.cloud import dataproc_v1beta2\n >>>\n >>> client = dataproc_v1beta2.ClusterControllerClient()\n >>>\n >>> # TODO: Initialize `project_id`:\n ...
Please provide a description of the function: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, ): #...
[ "\n Lists all regions/{region}/clusters in a project.\n\n Example:\n >>> from google.cloud import dataproc_v1beta2\n >>>\n >>> client = dataproc_v1beta2.ClusterControllerClient()\n >>>\n >>> # TODO: Initialize `project_id`:\n >>> projec...
Please provide a description of the function: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, ): # Wrap the transport m...
[ "\n Gets cluster diagnostic information. After the operation completes, the\n Operation.response field contains ``DiagnoseClusterOutputLocation``.\n\n Example:\n >>> from google.cloud import dataproc_v1beta2\n >>>\n >>> client = dataproc_v1beta2.ClusterControlle...
Please provide a description of the function:def commit(self): # Set the status to "starting" synchronously, to ensure that # this batch will necessarily not accept new messages. with self._state_lock: if self._status == base.BatchStatus.ACCEPTING_MESSAGES: s...
[ "Actually publish all of the messages on the active batch.\n\n .. note::\n\n This method is non-blocking. It opens a new thread, which calls\n :meth:`_commit`, which does block.\n\n This synchronously sets the batch status to \"starting\", and then opens\n a new thread, wh...
Please provide a description of the function:def _commit(self): with self._state_lock: if self._status in _CAN_COMMIT: self._status = base.BatchStatus.IN_PROGRESS else: # If, in the intervening period between when this method was #...
[ "Actually publish all of the messages on the active batch.\n\n This moves the batch out from being the active batch to an in progress\n batch on the publisher, and then the batch is discarded upon\n completion.\n\n .. note::\n\n This method blocks. The :meth:`commit` method is...
Please provide a description of the function:def monitor(self): # NOTE: This blocks; it is up to the calling code to call it # in a separate thread. # Sleep for however long we should be waiting. time.sleep(self._settings.max_latency) _LOGGER.debug("Monitor is wa...
[ "Commit this batch after sufficient time has elapsed.\n\n This simply sleeps for ``self._settings.max_latency`` seconds,\n and then calls commit unless the batch has already been committed.\n " ]
Please provide a description of the function:def publish(self, message): # Coerce the type, just in case. if not isinstance(message, types.PubsubMessage): message = types.PubsubMessage(**message) future = None with self._state_lock: if not self.will_acc...
[ "Publish a single message.\n\n Add the given message to this object; this will cause it to be\n published once the batch either has enough messages or a sufficient\n period of time has elapsed.\n\n This method is called by :meth:`~.PublisherClient.publish`.\n\n Args:\n ...
Please provide a description of the function:def from_api_repr(cls, resource, zone): changes = cls(zone=zone) changes._set_properties(resource) return changes
[ "Factory: construct a change set given its API representation\n\n :type resource: dict\n :param resource: change set representation returned from the API.\n\n :type zone: :class:`google.cloud.dns.zone.ManagedZone`\n :param zone: A zone which holds zero or more change sets.\n\n :r...
Please provide a description of the function:def _set_properties(self, resource): resource = resource.copy() self._additions = tuple( [ ResourceRecordSet.from_api_repr(added_res, self.zone) for added_res in resource.pop("additions", ()) ] ...
[ "Helper method for :meth:`from_api_repr`, :meth:`create`, etc.\n\n :type resource: dict\n :param resource: change set representation returned from the API.\n " ]
Please provide a description of the function:def path(self): return "/projects/%s/managedZones/%s/changes/%s" % ( self.zone.project, self.zone.name, self.name, )
[ "URL path for change set APIs.\n\n :rtype: str\n :returns: the path based on project, zone, and change set names.\n " ]
Please provide a description of the function:def name(self, value): if not isinstance(value, six.string_types): raise ValueError("Pass a string") self._properties["id"] = value
[ "Update name of the change set.\n\n :type value: str\n :param value: New name for the changeset.\n " ]
Please provide a description of the function:def add_record_set(self, record_set): if not isinstance(record_set, ResourceRecordSet): raise ValueError("Pass a ResourceRecordSet") self._additions += (record_set,)
[ "Append a record set to the 'additions' for the change set.\n\n :type record_set:\n :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`\n :param record_set: the record set to append.\n\n :raises: ``ValueError`` if ``record_set`` is not of the required type.\n " ]
Please provide a description of the function:def delete_record_set(self, record_set): if not isinstance(record_set, ResourceRecordSet): raise ValueError("Pass a ResourceRecordSet") self._deletions += (record_set,)
[ "Append a record set to the 'deletions' for the change set.\n\n :type record_set:\n :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`\n :param record_set: the record set to append.\n\n :raises: ``ValueError`` if ``record_set`` is not of the required type.\n " ]
Please provide a description of the function:def _build_resource(self): additions = [ { "name": added.name, "type": added.record_type, "ttl": str(added.ttl), "rrdatas": added.rrdatas, } for added in self...
[ "Generate a resource for ``create``." ]
Please provide a description of the function:def create(self, client=None): if len(self.additions) == 0 and len(self.deletions) == 0: raise ValueError("No record sets added or deleted") client = self._require_client(client) path = "/projects/%s/managedZones/%s/changes" % ( ...
[ "API call: create the change set via a POST request.\n\n See\n https://cloud.google.com/dns/api/v1/changes/create\n\n :type client: :class:`google.cloud.dns.client.Client`\n :param client:\n (Optional) the client to use. If not passed, falls back to the\n ``client...
Please provide a description of the function:def logging_api(self): if self._logging_api is None: if self._use_grpc: self._logging_api = _gapic.make_logging_api(self) else: self._logging_api = JSONLoggingAPI(self) return self._logging_api
[ "Helper for logging-related API calls.\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs\n " ]
Please provide a description of the function:def sinks_api(self): if self._sinks_api is None: if self._use_grpc: self._sinks_api = _gapic.make_sinks_api(self) else: self._sinks_api = JSONSinksAPI(self) return self._sinks_api
[ "Helper for log sink-related API calls.\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks\n " ]
Please provide a description of the function:def metrics_api(self): if self._metrics_api is None: if self._use_grpc: self._metrics_api = _gapic.make_metrics_api(self) else: self._metrics_api = JSONMetricsAPI(self) return self._metrics_api
[ "Helper for log metric-related API calls.\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics\n " ]
Please provide a description of the function:def list_entries( self, projects=None, filter_=None, order_by=None, page_size=None, page_token=None, ): if projects is None: projects = [self.project] return self.logging_api.list_entri...
[ "Return a page of log entries.\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list\n\n :type projects: list of strings\n :param projects: project IDs to include. If not passed,\n defaults to the project bound to the client.\n\n ...
Please provide a description of the function:def sink(self, name, filter_=None, destination=None): return Sink(name, filter_, destination, client=self)
[ "Creates a sink bound to the current client.\n\n :type name: str\n :param name: the name of the sink to be constructed.\n\n :type filter_: str\n :param filter_: (optional) the advanced logs filter expression\n defining the entries exported by the sink. If not\n ...
Please provide a description of the function:def list_sinks(self, page_size=None, page_token=None): return self.sinks_api.list_sinks(self.project, page_size, page_token)
[ "List sinks for the project associated with this client.\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/list\n\n :type page_size: int\n :param page_size:\n Optional. The maximum number of sinks in each page of results from\n this...
Please provide a description of the function:def metric(self, name, filter_=None, description=""): return Metric(name, filter_, client=self, description=description)
[ "Creates a metric bound to the current client.\n\n :type name: str\n :param name: the name of the metric to be constructed.\n\n :type filter_: str\n :param filter_: the advanced logs filter expression defining the\n entries tracked by the metric. If not\n ...
Please provide a description of the function:def list_metrics(self, page_size=None, page_token=None): return self.metrics_api.list_metrics(self.project, page_size, page_token)
[ "List metrics for the project associated with this client.\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list\n\n :type page_size: int\n :param page_size:\n Optional. The maximum number of metrics in each page of results\n fro...