Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _invoke_callbacks(self, *args, **kwargs): for callback in self._done_callbacks: _helpers.safe_invoke_callback(callback, *args, **kwargs)
[ "Invoke all done callbacks." ]
Please provide a description of the function:def set_result(self, result): self._result = result self._result_set = True self._invoke_callbacks(self)
[ "Set the Future's result." ]
Please provide a description of the function:def set_exception(self, exception): self._exception = exception self._result_set = True self._invoke_callbacks(self)
[ "Set the Future's exception." ]
Please provide a description of the function:def build_flask_context(request): return HTTPContext( url=request.url, method=request.method, user_agent=request.user_agent.string, referrer=request.referrer, remote_ip=request.remote_addr, )
[ "Builds an HTTP context object from a Flask (Werkzeug) request object.\n\n This helper method extracts the relevant HTTP context from a Flask request\n object into an object ready to be sent to Error Reporting.\n\n .. code-block:: python\n\n >>> @app.errorhandler(HTTPException)\n ... def ha...
Please provide a description of the function:def instantiate_client(_unused_client, _unused_to_delete): # [START client_create_default] from google.cloud import logging client = logging.Client() # [END client_create_default] credentials = object() # [START client_create_explicit] fro...
[ "Instantiate client." ]
Please provide a description of the function:def client_list_entries(client, to_delete): # pylint: disable=unused-argument # [START client_list_entries_default] for entry in client.list_entries(): # API call(s) do_something_with(entry) # [END client_list_entries_default] # [START client...
[ "List entries via client." ]
Please provide a description of the function:def client_list_entries_multi_project( client, to_delete ): # pylint: disable=unused-argument # [START client_list_entries_multi_project] PROJECT_IDS = ["one-project", "another-project"] for entry in client.list_entries(project_ids=PROJECT_IDS): # API...
[ "List entries via client across multiple projects." ]
Please provide a description of the function:def logger_usage(client, to_delete): LOG_NAME = "logger_usage_%d" % (_millis()) # [START logger_create] logger = client.logger(LOG_NAME) # [END logger_create] to_delete.append(logger) # [START logger_log_text] logger.log_text("A simple entr...
[ "Logger usage." ]
Please provide a description of the function:def metric_crud(client, to_delete): METRIC_NAME = "robots-%d" % (_millis(),) DESCRIPTION = "Robots all up in your server" FILTER = "logName:apache-access AND textPayload:robot" UPDATED_FILTER = "textPayload:robot" UPDATED_DESCRIPTION = "Danger, Will ...
[ "Metric CRUD." ]
Please provide a description of the function:def sink_storage(client, to_delete): bucket = _sink_storage_setup(client) to_delete.append(bucket) SINK_NAME = "robots-storage-%d" % (_millis(),) FILTER = "textPayload:robot" # [START sink_storage_create] DESTINATION = "storage.googleapis.com/%s...
[ "Sink log entries to storage." ]
Please provide a description of the function:def sink_bigquery(client, to_delete): dataset = _sink_bigquery_setup(client) to_delete.append(dataset) SINK_NAME = "robots-bigquery-%d" % (_millis(),) FILTER = "textPayload:robot" # [START sink_bigquery_create] DESTINATION = "bigquery.googleapis...
[ "Sink log entries to bigquery." ]
Please provide a description of the function:def sink_pubsub(client, to_delete): topic = _sink_pubsub_setup(client) to_delete.append(topic) SINK_NAME = "robots-pubsub-%d" % (_millis(),) FILTER = "logName:apache-access AND textPayload:robot" UPDATED_FILTER = "textPayload:robot" # [START sin...
[ "Sink log entries to pubsub." ]
Please provide a description of the function:def complain(distribution_name): try: pkg_resources.get_distribution(distribution_name) warnings.warn( "The {pkg} distribution is now obsolete. " "Please `pip uninstall {pkg}`. " "In the future, this warning will b...
[ "Issue a warning if `distribution_name` is installed.\n\n In a future release, this method will be updated to raise ImportError\n rather than just send a warning.\n\n Args:\n distribution_name (str): The name of the obsolete distribution.\n " ]
Please provide a description of the function:def _get_encryption_headers(key, source=False): if key is None: return {} key = _to_bytes(key) key_hash = hashlib.sha256(key).digest() key_hash = base64.b64encode(key_hash) key = base64.b64encode(key) if source: prefix = "X-Goog...
[ "Builds customer encryption key headers\n\n :type key: bytes\n :param key: 32 byte key to build request key and hash.\n\n :type source: bool\n :param source: If true, return headers for the \"source\" blob; otherwise,\n return headers for the \"destination\" blob.\n\n :rtype: dict\n...
Please provide a description of the function:def _raise_from_invalid_response(error): response = error.response error_message = str(error) message = u"{method} {url}: {error}".format( method=response.request.method, url=response.request.url, error=error_message ) raise exceptions.from...
[ "Re-wrap and raise an ``InvalidResponse`` exception.\n\n :type error: :exc:`google.resumable_media.InvalidResponse`\n :param error: A caught exception from the ``google-resumable-media``\n library.\n\n :raises: :class:`~google.cloud.exceptions.GoogleCloudError` corresponding\n ...
Please provide a description of the function:def _add_query_parameters(base_url, name_value_pairs): if len(name_value_pairs) == 0: return base_url scheme, netloc, path, query, frag = urlsplit(base_url) query = parse_qsl(query) query.extend(name_value_pairs) return urlunsplit((scheme, n...
[ "Add one query parameter to a base URL.\n\n :type base_url: string\n :param base_url: Base URL (may already contain query parameters)\n\n :type name_value_pairs: list of (string, string) tuples.\n :param name_value_pairs: Names and values of the query parameters to add\n\n :rtype: string\n :return...
Please provide a description of the function:def chunk_size(self, value): if value is not None and value > 0 and value % self._CHUNK_SIZE_MULTIPLE != 0: raise ValueError( "Chunk size must be a multiple of %d." % (self._CHUNK_SIZE_MULTIPLE,) ) self._chunk_...
[ "Set the blob's default chunk size.\n\n :type value: int\n :param value: (Optional) The current blob's chunk size, if it is set.\n\n :raises: :class:`ValueError` if ``value`` is not ``None`` and is not a\n multiple of 256 KB.\n " ]
Please provide a description of the function:def path(self): if not self.name: raise ValueError("Cannot determine path without a blob name.") return self.path_helper(self.bucket.path, self.name)
[ "Getter property for the URL path to this Blob.\n\n :rtype: str\n :returns: The URL path to this Blob.\n " ]
Please provide a description of the function:def _query_params(self): params = {} if self.generation is not None: params["generation"] = self.generation if self.user_project is not None: params["userProject"] = self.user_project return params
[ "Default query parameters." ]
Please provide a description of the function:def public_url(self): return "{storage_base_url}/{bucket_name}/{quoted_name}".format( storage_base_url=_API_ACCESS_ENDPOINT, bucket_name=self.bucket.name, quoted_name=quote(self.name.encode("utf-8")), )
[ "The public URL for this blob.\n\n Use :meth:`make_public` to enable anonymous access via the returned\n URL.\n\n :rtype: `string`\n :returns: The public URL for this blob.\n " ]
Please provide a description of the function:def generate_signed_url( self, expiration=None, api_access_endpoint=_API_ACCESS_ENDPOINT, method="GET", content_md5=None, content_type=None, response_disposition=None, response_type=None, generation=None...
[ "Generates a signed URL for this blob.\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 ca...
Please provide a description of the function:def exists(self, client=None): client = self._require_client(client) # We only need the status code (200 or not) so we seek to # minimize the returned payload. query_params = self._query_params query_params["fields"] = "name" ...
[ "Determines whether or not this blob exists.\n\n If :attr:`user_project` is set on the bucket, bills the API request\n to that project.\n\n :type client: :class:`~google.cloud.storage.client.Client` or\n ``NoneType``\n :param client: Optional. The client to use. If ...
Please provide a description of the function:def delete(self, client=None): return self.bucket.delete_blob( self.name, client=client, generation=self.generation )
[ "Deletes a blob from Cloud Storage.\n\n If :attr:`user_project` is set on the bucket, bills the API request\n to that project.\n\n :type client: :class:`~google.cloud.storage.client.Client` or\n ``NoneType``\n :param client: Optional. The client to use. If not passe...
Please provide a description of the function:def _get_download_url(self): name_value_pairs = [] if self.media_link is None: base_url = _DOWNLOAD_URL_TEMPLATE.format(path=self.path) if self.generation is not None: name_value_pairs.append(("generation", "{:...
[ "Get the download URL for the current blob.\n\n If the ``media_link`` has been loaded, it will be used, otherwise\n the URL will be constructed from the current blob's path (and possibly\n generation) to avoid a round trip.\n\n :rtype: str\n :returns: The download URL for the curr...
Please provide a description of the function:def _do_download( self, transport, file_obj, download_url, headers, start=None, end=None ): if self.chunk_size is None: download = Download( download_url, stream=file_obj, headers=headers, start=start, end=end ...
[ "Perform a download without any error handling.\n\n This is intended to be called by :meth:`download_to_file` so it can\n be wrapped with error handling / remapping.\n\n :type transport:\n :class:`~google.auth.transport.requests.AuthorizedSession`\n :param transport: The trans...
Please provide a description of the function:def download_to_file(self, file_obj, client=None, start=None, end=None): download_url = self._get_download_url() headers = _get_encryption_headers(self._encryption_key) headers["accept-encoding"] = "gzip" transport = self._get_transp...
[ "Download the contents of this blob into a file-like object.\n\n .. note::\n\n If the server-set property, :attr:`media_link`, is not yet\n initialized, makes an additional API request to load it.\n\n Downloading a file that has been encrypted with a `customer-supplied`_\n e...
Please provide a description of the function:def download_to_filename(self, filename, client=None, start=None, end=None): try: with open(filename, "wb") as file_obj: self.download_to_file(file_obj, client=client, start=start, end=end) except resumable_media.DataCorru...
[ "Download the contents of this blob into a named file.\n\n If :attr:`user_project` is set on the bucket, bills the API request\n to that project.\n\n :type filename: str\n :param filename: A filename to be passed to ``open``.\n\n :type client: :class:`~google.cloud.storage.client....
Please provide a description of the function:def download_as_string(self, client=None, start=None, end=None): string_buffer = BytesIO() self.download_to_file(string_buffer, client=client, start=start, end=end) return string_buffer.getvalue()
[ "Download the contents of this blob as a string.\n\n If :attr:`user_project` is set on the bucket, bills the API request\n to that project.\n\n :type client: :class:`~google.cloud.storage.client.Client` or\n ``NoneType``\n :param client: Optional. The client to use. ...
Please provide a description of the function:def _get_content_type(self, content_type, filename=None): if content_type is None: content_type = self.content_type if content_type is None and filename is not None: content_type, _ = mimetypes.guess_type(filename) i...
[ "Determine the content type from the current object.\n\n The return value will be determined in order of precedence:\n\n - The value passed in to this method (if not :data:`None`)\n - The value stored on the current blob\n - The default value ('application/octet-stream')\n\n :type...
Please provide a description of the function:def _get_writable_metadata(self): # NOTE: This assumes `self.name` is unicode. object_metadata = {"name": self.name} for key in self._changes: if key in _WRITABLE_FIELDS: object_metadata[key] = self._properties[key...
[ "Get the object / blob metadata which is writable.\n\n This is intended to be used when creating a new object / blob.\n\n See the `API reference docs`_ for more information, the fields\n marked as writable are:\n\n * ``acl``\n * ``cacheControl``\n * ``contentDisposition``\n...
Please provide a description of the function:def _get_upload_arguments(self, content_type): headers = _get_encryption_headers(self._encryption_key) object_metadata = self._get_writable_metadata() content_type = self._get_content_type(content_type) return headers, object_metadata...
[ "Get required arguments for performing an upload.\n\n The content type returned will be determined in order of precedence:\n\n - The value passed in to this method (if not :data:`None`)\n - The value stored on the current blob\n - The default value ('application/octet-stream')\n\n ...
Please provide a description of the function:def _do_multipart_upload( self, client, stream, content_type, size, num_retries, predefined_acl ): if size is None: data = stream.read() else: data = stream.read(size) if len(data) < size: ...
[ "Perform a multipart upload.\n\n The content type of the upload will be determined in order\n of precedence:\n\n - The value passed in to this method (if not :data:`None`)\n - The value stored on the current blob\n - The default value ('application/octet-stream')\n\n :type ...
Please provide a description of the function:def _initiate_resumable_upload( self, client, stream, content_type, size, num_retries, predefined_acl=None, extra_headers=None, chunk_size=None, ): if chunk_size is None: ...
[ "Initiate a resumable upload.\n\n The content type of the upload will be determined in order\n of precedence:\n\n - The value passed in to this method (if not :data:`None`)\n - The value stored on the current blob\n - The default value ('application/octet-stream')\n\n :type...
Please provide a description of the function:def _do_resumable_upload( self, client, stream, content_type, size, num_retries, predefined_acl ): upload, transport = self._initiate_resumable_upload( client, stream, content_type, size, ...
[ "Perform a resumable upload.\n\n Assumes ``chunk_size`` is not :data:`None` on the current blob.\n\n The content type of the upload will be determined in order\n of precedence:\n\n - The value passed in to this method (if not :data:`None`)\n - The value stored on the current blob\...
Please provide a description of the function:def _do_upload( self, client, stream, content_type, size, num_retries, predefined_acl ): if size is not None and size <= _MAX_MULTIPART_SIZE: response = self._do_multipart_upload( client, stream, content_type, size, nu...
[ "Determine an upload strategy and then perform the upload.\n\n If the size of the data to be uploaded exceeds 5 MB a resumable media\n request will be used, otherwise the content and the metadata will be\n uploaded in a single multipart upload request.\n\n The content type of the upload ...
Please provide a description of the function:def upload_from_file( self, file_obj, rewind=False, size=None, content_type=None, num_retries=None, client=None, predefined_acl=None, ): if num_retries is not None: warnings.warn...
[ "Upload the contents of this blob from a file-like object.\n\n The content type of the upload will be determined in order\n of precedence:\n\n - The value passed in to this method (if not :data:`None`)\n - The value stored on the current blob\n - The default value ('application/oc...
Please provide a description of the function:def upload_from_filename( self, filename, content_type=None, client=None, predefined_acl=None ): content_type = self._get_content_type(content_type, filename=filename) with open(filename, "rb") as file_obj: total_bytes = os.f...
[ "Upload this blob's contents from the content of a named file.\n\n The content type of the upload will be determined in order\n of precedence:\n\n - The value passed in to this method (if not :data:`None`)\n - The value stored on the current blob\n - The value given by ``mimetypes...
Please provide a description of the function:def upload_from_string( self, data, content_type="text/plain", client=None, predefined_acl=None ): data = _to_bytes(data, encoding="utf-8") string_buffer = BytesIO(data) self.upload_from_file( file_obj=string_buffer, ...
[ "Upload contents of this blob from the provided string.\n\n .. note::\n The effect of uploading to an existing blob depends on the\n \"versioning\" and \"lifecycle\" policies defined on the blob's\n bucket. In the absence of those policies, upload will\n overwrite any...
Please provide a description of the function:def create_resumable_upload_session( self, content_type=None, size=None, origin=None, client=None ): extra_headers = {} if origin is not None: # This header is specifically for client-side uploads, it # determines ...
[ "Create a resumable upload session.\n\n Resumable upload sessions allow you to start an upload session from\n one client and complete the session in another. This method is called\n by the initiator to set the metadata and limits. The initiator then\n passes the session URL to the client...
Please provide a description of the function:def make_public(self, client=None): self.acl.all().grant_read() self.acl.save(client=client)
[ "Update blob's ACL, granting read access to anonymous users.\n\n :type client: :class:`~google.cloud.storage.client.Client` or\n ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the blob's buc...
Please provide a description of the function:def make_private(self, client=None): self.acl.all().revoke_read() self.acl.save(client=client)
[ "Update blob's ACL, revoking read access for anonymous users.\n\n :type client: :class:`~google.cloud.storage.client.Client` or\n ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n to the ``client`` stored on the blob's bu...
Please provide a description of the function:def compose(self, sources, client=None): client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project request = { "sourceObjects": ...
[ "Concatenate source blobs into this one.\n\n If :attr:`user_project` is set on the bucket, bills the API request\n to that project.\n\n :type sources: list of :class:`Blob`\n :param sources: blobs whose contents will be composed into this blob.\n\n :type client: :class:`~google.cl...
Please provide a description of the function:def rewrite(self, source, token=None, client=None): client = self._require_client(client) headers = _get_encryption_headers(self._encryption_key) headers.update(_get_encryption_headers(source._encryption_key, source=True)) query_para...
[ "Rewrite source blob into this one.\n\n If :attr:`user_project` is set on the bucket, bills the API request\n to that project.\n\n :type source: :class:`Blob`\n :param source: blob whose contents will be rewritten into this blob.\n\n :type token: str\n :param token: Optiona...
Please provide a description of the function:def update_storage_class(self, new_class, client=None): if new_class not in self._STORAGE_CLASSES: raise ValueError("Invalid storage class: %s" % (new_class,)) # Update current blob's storage class prior to rewrite self._patch_pr...
[ "Update blob's storage class via a rewrite-in-place. This helper will\n wait for the rewrite to complete before returning, so it may take some\n time for large files.\n\n See\n https://cloud.google.com/storage/docs/per-object-storage-class\n\n If :attr:`user_project` is set on the...
Please provide a description of the function:def verify_path(path, is_collection): num_elements = len(path) if num_elements == 0: raise ValueError("Document or collection path cannot be empty") if is_collection: if num_elements % 2 == 0: raise ValueError("A collection must ...
[ "Verifies that a ``path`` has the correct form.\n\n Checks that all of the elements in ``path`` are strings.\n\n Args:\n path (Tuple[str, ...]): The components in a collection or\n document path.\n is_collection (bool): Indicates if the ``path`` represents\n a document or a...
Please provide a description of the function:def encode_value(value): if value is None: return document_pb2.Value(null_value=struct_pb2.NULL_VALUE) # Must come before six.integer_types since ``bool`` is an integer subtype. if isinstance(value, bool): return document_pb2.Value(boolean_v...
[ "Converts a native Python value into a Firestore protobuf ``Value``.\n\n Args:\n value (Union[NoneType, bool, int, float, datetime.datetime, \\\n str, bytes, dict, ~google.cloud.Firestore.GeoPoint]): A native\n Python value to convert to a protobuf field.\n\n Returns:\n ~go...
Please provide a description of the function:def encode_dict(values_dict): return {key: encode_value(value) for key, value in six.iteritems(values_dict)}
[ "Encode a dictionary into protobuf ``Value``-s.\n\n Args:\n values_dict (dict): The dictionary to encode as protobuf fields.\n\n Returns:\n Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A\n dictionary of string keys and ``Value`` protobufs as dictionary\n values.\n " ]
Please provide a description of the function:def reference_value_to_document(reference_value, client): # The first 5 parts are # projects, {project}, databases, {database}, documents parts = reference_value.split(DOCUMENT_PATH_DELIMITER, 5) if len(parts) != 6: msg = BAD_REFERENCE_ERROR.form...
[ "Convert a reference value string to a document.\n\n Args:\n reference_value (str): A document reference value.\n client (~.firestore_v1beta1.client.Client): A client that has\n a document factory.\n\n Returns:\n ~.firestore_v1beta1.document.DocumentReference: The document\n ...
Please provide a description of the function:def decode_value(value, client): value_type = value.WhichOneof("value_type") if value_type == "null_value": return None elif value_type == "boolean_value": return value.boolean_value elif value_type == "integer_value": return val...
[ "Converts a Firestore protobuf ``Value`` to a native Python value.\n\n Args:\n value (google.cloud.firestore_v1beta1.types.Value): A\n Firestore protobuf to be decoded / parsed / converted.\n client (~.firestore_v1beta1.client.Client): A client that has\n a document factory.\n...
Please provide a description of the function:def decode_dict(value_fields, client): return { key: decode_value(value, client) for key, value in six.iteritems(value_fields) }
[ "Converts a protobuf map of Firestore ``Value``-s.\n\n Args:\n value_fields (google.protobuf.pyext._message.MessageMapContainer): A\n protobuf map of Firestore ``Value``-s.\n client (~.firestore_v1beta1.client.Client): A client that has\n a document factory.\n\n Returns:\n ...
Please provide a description of the function:def get_doc_id(document_pb, expected_prefix): prefix, document_id = document_pb.name.rsplit(DOCUMENT_PATH_DELIMITER, 1) if prefix != expected_prefix: raise ValueError( "Unexpected document name", document_pb.name, "Exp...
[ "Parse a document ID from a document protobuf.\n\n Args:\n document_pb (google.cloud.proto.firestore.v1beta1.\\\n document_pb2.Document): A protobuf for a document that\n was created in a ``CreateDocument`` RPC.\n expected_prefix (str): The expected collection prefix for the\n...
Please provide a description of the function:def extract_fields(document_data, prefix_path, expand_dots=False): if not document_data: yield prefix_path, _EmptyDict else: for key, value in sorted(six.iteritems(document_data)): if expand_dots: sub_key = FieldPath....
[ "Do depth-first walk of tree, yielding field_path, value" ]
Please provide a description of the function:def set_field_value(document_data, field_path, value): current = document_data for element in field_path.parts[:-1]: current = current.setdefault(element, {}) if value is _EmptyDict: value = {} current[field_path.parts[-1]] = value
[ "Set a value into a document for a field_path" ]
Please provide a description of the function:def pbs_for_create(document_path, document_data): extractor = DocumentExtractor(document_data) if extractor.deleted_fields: raise ValueError("Cannot apply DELETE_FIELD in a create request.") write_pbs = [] # Conformance tests require skipping ...
[ "Make ``Write`` protobufs for ``create()`` methods.\n\n Args:\n document_path (str): A fully-qualified document path.\n document_data (dict): Property names and values to use for\n creating a document.\n\n Returns:\n List[google.cloud.firestore_v1beta1.types.Write]: One or two\...
Please provide a description of the function:def pbs_for_set_no_merge(document_path, document_data): extractor = DocumentExtractor(document_data) if extractor.deleted_fields: raise ValueError( "Cannot apply DELETE_FIELD in a set request without " "specifying 'merge=True' or...
[ "Make ``Write`` protobufs for ``set()`` methods.\n\n Args:\n document_path (str): A fully-qualified document path.\n document_data (dict): Property names and values to use for\n replacing a document.\n\n Returns:\n List[google.cloud.firestore_v1beta1.types.Write]: One\n ...
Please provide a description of the function:def pbs_for_set_with_merge(document_path, document_data, merge): extractor = DocumentExtractorForMerge(document_data) extractor.apply_merge(merge) merge_empty = not document_data write_pbs = [] if extractor.has_updates or merge_empty: writ...
[ "Make ``Write`` protobufs for ``set()`` methods.\n\n Args:\n document_path (str): A fully-qualified document path.\n document_data (dict): Property names and values to use for\n replacing a document.\n merge (Optional[bool] or Optional[List<apispec>]):\n If True, merge ...
Please provide a description of the function:def pbs_for_update(document_path, field_updates, option): extractor = DocumentExtractorForUpdate(field_updates) if extractor.empty_document: raise ValueError("Cannot update with an empty document.") if option is None: # Default is to use ``exists=...
[ "Make ``Write`` protobufs for ``update()`` methods.\n\n Args:\n document_path (str): A fully-qualified document path.\n field_updates (dict): Field names or paths to update and values\n to update with.\n option (optional[~.firestore_v1beta1.client.WriteOption]): A\n writ...
Please provide a description of the function:def pb_for_delete(document_path, option): write_pb = write_pb2.Write(delete=document_path) if option is not None: option.modify_write(write_pb) return write_pb
[ "Make a ``Write`` protobuf for ``delete()`` methods.\n\n Args:\n document_path (str): A fully-qualified document path.\n option (optional[~.firestore_v1beta1.client.WriteOption]): A\n write option to make assertions / preconditions on the server\n state of the document before ap...
Please provide a description of the function:def get_transaction_id(transaction, read_operation=True): if transaction is None: return None else: if not transaction.in_progress: raise ValueError(INACTIVE_TXN) if read_operation and len(transaction._write_pbs) > 0: ...
[ "Get the transaction ID from a ``Transaction`` object.\n\n Args:\n transaction (Optional[~.firestore_v1beta1.transaction.\\\n Transaction]): An existing transaction that this query will\n run in.\n read_operation (Optional[bool]): Indicates if the transaction ID\n w...
Please provide a description of the function:def modify_write(self, write_pb, **unused_kwargs): current_doc = types.Precondition(update_time=self._last_update_time) write_pb.current_document.CopyFrom(current_doc)
[ "Modify a ``Write`` protobuf based on the state of this write option.\n\n The ``last_update_time`` is added to ``write_pb`` as an \"update time\"\n precondition. When set, the target document must exist and have been\n last updated at that time.\n\n Args:\n write_pb (google.cl...
Please provide a description of the function:def modify_write(self, write_pb, **unused_kwargs): current_doc = types.Precondition(exists=self._exists) write_pb.current_document.CopyFrom(current_doc)
[ "Modify a ``Write`` protobuf based on the state of this write option.\n\n If:\n\n * ``exists=True``, adds a precondition that requires existence\n * ``exists=False``, adds a precondition that requires non-existence\n\n Args:\n write_pb (google.cloud.firestore_v1beta1.types.Wri...
Please provide a description of the function:def uptime_check_config_path(cls, project, uptime_check_config): return google.api_core.path_template.expand( "projects/{project}/uptimeCheckConfigs/{uptime_check_config}", project=project, uptime_check_config=uptime_check...
[ "Return a fully-qualified uptime_check_config string." ]
Please provide a description of the function:def create_uptime_check_config( self, parent, uptime_check_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): if metadata is None: ...
[ "\n Creates a new uptime check configuration.\n\n Example:\n >>> from google.cloud import monitoring_v3\n >>>\n >>> client = monitoring_v3.UptimeCheckServiceClient()\n >>>\n >>> parent = client.project_path('[PROJECT]')\n >>>\n ...
Please provide a description of the function:def annotate_video( self, input_uri=None, input_content=None, features=None, video_context=None, output_uri=None, location_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core....
[ "\n Performs asynchronous video annotation. Progress and results can be\n retrieved through the ``google.longrunning.Operations`` interface.\n ``Operation.metadata`` contains ``AnnotateVideoProgress`` (progress).\n ``Operation.response`` contains ``AnnotateVideoResponse`` (results).\n\n ...
Please provide a description of the function:def owners(self): result = set() for role in self._OWNER_ROLES: for member in self._bindings.get(role, ()): result.add(member) return frozenset(result)
[ "Legacy access to owner role.\n\n DEPRECATED: use ``policy[\"roles/owners\"]`` instead." ]
Please provide a description of the function:def owners(self, value): warnings.warn( _ASSIGNMENT_DEPRECATED_MSG.format("owners", OWNER_ROLE), DeprecationWarning ) self[OWNER_ROLE] = value
[ "Update owners.\n\n DEPRECATED: use ``policy[\"roles/owners\"] = value`` instead." ]
Please provide a description of the function:def editors(self): result = set() for role in self._EDITOR_ROLES: for member in self._bindings.get(role, ()): result.add(member) return frozenset(result)
[ "Legacy access to editor role.\n\n DEPRECATED: use ``policy[\"roles/editors\"]`` instead." ]
Please provide a description of the function:def editors(self, value): warnings.warn( _ASSIGNMENT_DEPRECATED_MSG.format("editors", EDITOR_ROLE), DeprecationWarning, ) self[EDITOR_ROLE] = value
[ "Update editors.\n\n DEPRECATED: use ``policy[\"roles/editors\"] = value`` instead." ]
Please provide a description of the function:def viewers(self): result = set() for role in self._VIEWER_ROLES: for member in self._bindings.get(role, ()): result.add(member) return frozenset(result)
[ "Legacy access to viewer role.\n\n DEPRECATED: use ``policy[\"roles/viewers\"]`` instead\n " ]
Please provide a description of the function:def viewers(self, value): warnings.warn( _ASSIGNMENT_DEPRECATED_MSG.format("viewers", VIEWER_ROLE), DeprecationWarning, ) self[VIEWER_ROLE] = value
[ "Update viewers.\n\n DEPRECATED: use ``policy[\"roles/viewers\"] = value`` instead.\n " ]
Please provide a description of the function:def from_api_repr(cls, resource): version = resource.get("version") etag = resource.get("etag") policy = cls(etag, version) for binding in resource.get("bindings", ()): role = binding["role"] members = sorted(b...
[ "Factory: create a policy from a JSON resource.\n\n Args:\n resource (dict): policy resource returned by ``getIamPolicy`` API.\n\n Returns:\n :class:`Policy`: the parsed policy\n " ]
Please provide a description of the function:def to_api_repr(self): resource = {} if self.etag is not None: resource["etag"] = self.etag if self.version is not None: resource["version"] = self.version if self._bindings: bindings = resource[...
[ "Render a JSON policy resource.\n\n Returns:\n dict: a resource to be passed to the ``setIamPolicy`` API.\n " ]
Please provide a description of the function:def _reference_info(references): document_paths = [] reference_map = {} for reference in references: doc_path = reference._document_path document_paths.append(doc_path) reference_map[doc_path] = reference return document_paths, r...
[ "Get information about document references.\n\n Helper for :meth:`~.firestore_v1beta1.client.Client.get_all`.\n\n Args:\n references (List[.DocumentReference, ...]): Iterable of document\n references.\n\n Returns:\n Tuple[List[str, ...], Dict[str, .DocumentReference]]: A two-tuple ...
Please provide a description of the function:def _get_reference(document_path, reference_map): try: return reference_map[document_path] except KeyError: msg = _BAD_DOC_TEMPLATE.format(document_path) raise ValueError(msg)
[ "Get a document reference from a dictionary.\n\n This just wraps a simple dictionary look-up with a helpful error that is\n specific to :meth:`~.firestore.client.Client.get_all`, the\n **public** caller of this function.\n\n Args:\n document_path (str): A fully-qualified document path.\n r...
Please provide a description of the function:def _parse_batch_get(get_doc_response, reference_map, client): result_type = get_doc_response.WhichOneof("result") if result_type == "found": reference = _get_reference(get_doc_response.found.name, reference_map) data = _helpers.decode_dict(get_d...
[ "Parse a `BatchGetDocumentsResponse` protobuf.\n\n Args:\n get_doc_response (~google.cloud.proto.firestore.v1beta1.\\\n firestore_pb2.BatchGetDocumentsResponse): A single response (from\n a stream) containing the \"get\" response for a document.\n reference_map (Dict[str, .Doc...
Please provide a description of the function:def _firestore_api(self): if self._firestore_api_internal is None: self._firestore_api_internal = firestore_client.FirestoreClient( credentials=self._credentials ) return self._firestore_api_internal
[ "Lazy-loading getter GAPIC Firestore API.\n\n Returns:\n ~.gapic.firestore.v1beta1.firestore_client.FirestoreClient: The\n GAPIC client with the credentials of the current client.\n " ]
Please provide a description of the function:def _database_string(self): if self._database_string_internal is None: # NOTE: database_root_path() is a classmethod, so we don't use # self._firestore_api (it isn't necessary). db_str = firestore_client.FirestoreCli...
[ "The database string corresponding to this client's project.\n\n This value is lazy-loaded and cached.\n\n Will be of the form\n\n ``projects/{project_id}/databases/{database_id}``\n\n but ``database_id == '(default)'`` for the time being.\n\n Returns:\n str: The fu...
Please provide a description of the function:def _rpc_metadata(self): if self._rpc_metadata_internal is None: self._rpc_metadata_internal = _helpers.metadata_with_prefix( self._database_string ) return self._rpc_metadata_internal
[ "The RPC metadata for this client's associated database.\n\n Returns:\n Sequence[Tuple(str, str)]: RPC metadata with resource prefix\n for the database associated with this client.\n " ]
Please provide a description of the function:def collection(self, *collection_path): if len(collection_path) == 1: path = collection_path[0].split(_helpers.DOCUMENT_PATH_DELIMITER) else: path = collection_path return CollectionReference(*path, client=self)
[ "Get a reference to a collection.\n\n For a top-level collection:\n\n .. code-block:: python\n\n >>> client.collection('top')\n\n For a sub-collection:\n\n .. code-block:: python\n\n >>> client.collection('mydocs/doc/subcol')\n >>> # is the same as\n ...
Please provide a description of the function:def document(self, *document_path): if len(document_path) == 1: path = document_path[0].split(_helpers.DOCUMENT_PATH_DELIMITER) else: path = document_path return DocumentReference(*path, client=self)
[ "Get a reference to a document in a collection.\n\n For a top-level document:\n\n .. code-block:: python\n\n >>> client.document('collek/shun')\n >>> # is the same as\n >>> client.document('collek', 'shun')\n\n For a document in a sub-collection:\n\n .. c...
Please provide a description of the function:def write_option(**kwargs): if len(kwargs) != 1: raise TypeError(_BAD_OPTION_ERR) name, value = kwargs.popitem() if name == "last_update_time": return _helpers.LastUpdateOption(value) elif name == "exists": ...
[ "Create a write option for write operations.\n\n Write operations include :meth:`~.DocumentReference.set`,\n :meth:`~.DocumentReference.update` and\n :meth:`~.DocumentReference.delete`.\n\n One of the following keyword arguments must be provided:\n\n * ``last_update_time`` (:class...
Please provide a description of the function:def get_all(self, references, field_paths=None, transaction=None): document_paths, reference_map = _reference_info(references) mask = _get_doc_mask(field_paths) response_iterator = self._firestore_api.batch_get_documents( self._da...
[ "Retrieve a batch of documents.\n\n .. note::\n\n Documents returned by this method are not guaranteed to be\n returned in the same order that they are given in ``references``.\n\n .. note::\n\n If multiple ``references`` refer to the same document, the server\n ...
Please provide a description of the function:def collections(self): iterator = self._firestore_api.list_collection_ids( self._database_string, metadata=self._rpc_metadata ) iterator.client = self iterator.item_to_value = _item_to_collection_ref return iterato...
[ "List top-level collections of the client's database.\n\n Returns:\n Sequence[~.firestore_v1beta1.collection.CollectionReference]:\n iterator of subcollections of the current document.\n " ]
Please provide a description of the function:def _check_state(self): if self._transaction_id is None: raise ValueError("Transaction is not begun") if self.committed is not None: raise ValueError("Transaction is already committed") if self._rolled_back: ...
[ "Helper for :meth:`commit` et al.\n\n :raises: :exc:`ValueError` if the object's state is invalid for making\n API requests.\n " ]
Please provide a description of the function:def begin(self): if self._transaction_id is not None: raise ValueError("Transaction already begun") if self.committed is not None: raise ValueError("Transaction already committed") if self._rolled_back: r...
[ "Begin a transaction on the database.\n\n :rtype: bytes\n :returns: the ID for the newly-begun transaction.\n :raises ValueError:\n if the transaction is already begun, committed, or rolled back.\n " ]
Please provide a description of the function:def rollback(self): self._check_state() database = self._session._database api = database.spanner_api metadata = _metadata_with_prefix(database.name) api.rollback(self._session.name, self._transaction_id, metadata=metadata) ...
[ "Roll back a transaction on the database." ]
Please provide a description of the function:def commit(self): self._check_state() database = self._session._database api = database.spanner_api metadata = _metadata_with_prefix(database.name) response = api.commit( self._session.name, self._muta...
[ "Commit mutations to the database.\n\n :rtype: datetime\n :returns: timestamp of the committed changes.\n :raises ValueError: if there are no mutations to commit.\n " ]
Please provide a description of the function:def _make_params_pb(params, param_types): if params is not None: if param_types is None: raise ValueError("Specify 'param_types' when passing 'params'.") return Struct( fields={key: _make_value_pb(value...
[ "Helper for :meth:`execute_update`.\n\n :type params: dict, {str -> column value}\n :param params: values for parameter replacement. Keys must match\n the names used in ``dml``.\n\n :type param_types: dict[str -> Union[dict, .types.Type]]\n :param param_types:\n ...
Please provide a description of the function:def execute_update(self, dml, params=None, param_types=None, query_mode=None): params_pb = self._make_params_pb(params, param_types) database = self._session._database metadata = _metadata_with_prefix(database.name) transaction = self...
[ "Perform an ``ExecuteSql`` API request with DML.\n\n :type dml: str\n :param dml: SQL DML statement\n\n :type params: dict, {str -> column value}\n :param params: values for parameter replacement. Keys must match\n the names used in ``dml``.\n\n :type param_...
Please provide a description of the function:def batch_update(self, statements): parsed = [] for statement in statements: if isinstance(statement, str): parsed.append({"sql": statement}) else: dml, params, param_types = statement ...
[ "Perform a batch of DML statements via an ``ExecuteBatchDml`` request.\n\n :type statements:\n Sequence[Union[ str, Tuple[str, Dict[str, Any], Dict[str, Union[dict, .types.Type]]]]]\n\n :param statements:\n List of DML statements, with optional params / param types.\n ...
Please provide a description of the function:def to_pb(self): timestamp_range_kwargs = {} if self.start is not None: timestamp_range_kwargs["start_timestamp_micros"] = ( _microseconds_from_datetime(self.start) // 1000 * 1000 ) if self.end is not N...
[ "Converts the :class:`TimestampRange` to a protobuf.\n\n :rtype: :class:`.data_v2_pb2.TimestampRange`\n :returns: The converted current object.\n " ]
Please provide a description of the function:def to_pb(self): column_range_kwargs = {"family_name": self.column_family_id} if self.start_column is not None: if self.inclusive_start: key = "start_qualifier_closed" else: key = "start_qualifi...
[ "Converts the row filter to a protobuf.\n\n First converts to a :class:`.data_v2_pb2.ColumnRange` and then uses it\n in the ``column_range_filter`` field.\n\n :rtype: :class:`.data_v2_pb2.RowFilter`\n :returns: The converted current object.\n " ]
Please provide a description of the function:def to_pb(self): value_range_kwargs = {} if self.start_value is not None: if self.inclusive_start: key = "start_value_closed" else: key = "start_value_open" value_range_kwargs[key] =...
[ "Converts the row filter to a protobuf.\n\n First converts to a :class:`.data_v2_pb2.ValueRange` and then uses\n it to create a row filter protobuf.\n\n :rtype: :class:`.data_v2_pb2.RowFilter`\n :returns: The converted current object.\n " ]
Please provide a description of the function:def to_pb(self): chain = data_v2_pb2.RowFilter.Chain( filters=[row_filter.to_pb() for row_filter in self.filters] ) return data_v2_pb2.RowFilter(chain=chain)
[ "Converts the row filter to a protobuf.\n\n :rtype: :class:`.data_v2_pb2.RowFilter`\n :returns: The converted current object.\n " ]
Please provide a description of the function:def to_pb(self): interleave = data_v2_pb2.RowFilter.Interleave( filters=[row_filter.to_pb() for row_filter in self.filters] ) return data_v2_pb2.RowFilter(interleave=interleave)
[ "Converts the row filter to a protobuf.\n\n :rtype: :class:`.data_v2_pb2.RowFilter`\n :returns: The converted current object.\n " ]
Please provide a description of the function:def to_pb(self): condition_kwargs = {"predicate_filter": self.base_filter.to_pb()} if self.true_filter is not None: condition_kwargs["true_filter"] = self.true_filter.to_pb() if self.false_filter is not None: condition...
[ "Converts the row filter to a protobuf.\n\n :rtype: :class:`.data_v2_pb2.RowFilter`\n :returns: The converted current object.\n " ]
Please provide a description of the function:def organization_deidentify_template_path(cls, organization, deidentify_template): return google.api_core.path_template.expand( "organizations/{organization}/deidentifyTemplates/{deidentify_template}", organization=organization, ...
[ "Return a fully-qualified organization_deidentify_template string." ]
Please provide a description of the function:def project_deidentify_template_path(cls, project, deidentify_template): return google.api_core.path_template.expand( "projects/{project}/deidentifyTemplates/{deidentify_template}", project=project, deidentify_template=dei...
[ "Return a fully-qualified project_deidentify_template string." ]
Please provide a description of the function:def organization_inspect_template_path(cls, organization, inspect_template): return google.api_core.path_template.expand( "organizations/{organization}/inspectTemplates/{inspect_template}", organization=organization, inspe...
[ "Return a fully-qualified organization_inspect_template string." ]
Please provide a description of the function:def project_inspect_template_path(cls, project, inspect_template): return google.api_core.path_template.expand( "projects/{project}/inspectTemplates/{inspect_template}", project=project, inspect_template=inspect_template, ...
[ "Return a fully-qualified project_inspect_template string." ]