INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Parses positional arguments into key path with kinds and IDs. :type path_args: tuple :param path_args: A tuple from positional arguments. Should be alternating list of kinds (string) and ID/name parts (int or string). :rtype: :class:`list` of...
def _parse_path(path_args): """Parses positional arguments into key path with kinds and IDs. :type path_args: tuple :param path_args: A tuple from positional arguments. Should be alternating list of kinds (string) and ID/name parts (int or str...
Convert a tuple of ints and strings in a legacy "Path". .. note: This assumes, but does not verify, that each entry in ``dict_path`` is valid (i.e. doesn't have more than one key out of "name" / "id"). :type dict_path: lsit :param dict_path: The "structured" path for a key, i.e. i...
def _to_legacy_path(dict_path): """Convert a tuple of ints and strings in a legacy "Path". .. note: This assumes, but does not verify, that each entry in ``dict_path`` is valid (i.e. doesn't have more than one key out of "name" / "id"). :type dict_path: lsit :param dict_path: ...
Sets protected data by combining raw data set from the constructor. If a ``_parent`` is set, updates the ``_flat_path`` and sets the ``_namespace`` and ``_project`` if not already set. :rtype: :class:`list` of :class:`dict` :returns: A list of key parts with kind and ID or name set. ...
def _combine_args(self): """Sets protected data by combining raw data set from the constructor. If a ``_parent`` is set, updates the ``_flat_path`` and sets the ``_namespace`` and ``_project`` if not already set. :rtype: :class:`list` of :class:`dict` :returns: A list of key pa...
Duplicates the Key. Most attributes are simple types, so don't require copying. Other attributes like ``parent`` are long-lived and so we re-use them. :rtype: :class:`google.cloud.datastore.key.Key` :returns: A new ``Key`` instance with the same data as the current one.
def _clone(self): """Duplicates the Key. Most attributes are simple types, so don't require copying. Other attributes like ``parent`` are long-lived and so we re-use them. :rtype: :class:`google.cloud.datastore.key.Key` :returns: A new ``Key`` instance with the same data as the...
Creates new key from existing partial key by adding final ID/name. :type id_or_name: str or integer :param id_or_name: ID or name to be added to the key. :rtype: :class:`google.cloud.datastore.key.Key` :returns: A new ``Key`` instance with the same data as the current one ...
def completed_key(self, id_or_name): """Creates new key from existing partial key by adding final ID/name. :type id_or_name: str or integer :param id_or_name: ID or name to be added to the key. :rtype: :class:`google.cloud.datastore.key.Key` :returns: A new ``Key`` instance wit...
Return a protobuf corresponding to the key. :rtype: :class:`.entity_pb2.Key` :returns: The protobuf representing the key.
def to_protobuf(self): """Return a protobuf corresponding to the key. :rtype: :class:`.entity_pb2.Key` :returns: The protobuf representing the key. """ key = _entity_pb2.Key() key.partition_id.project_id = self.project if self.namespace: key.partitio...
Convert to a base64 encode urlsafe string for App Engine. This is intended to work with the "legacy" representation of a datastore "Key" used within Google App Engine (a so-called "Reference"). The returned string can be used as the ``urlsafe`` argument to ``ndb.Key(urlsafe=...)``. The ...
def to_legacy_urlsafe(self, location_prefix=None): """Convert to a base64 encode urlsafe string for App Engine. This is intended to work with the "legacy" representation of a datastore "Key" used within Google App Engine (a so-called "Reference"). The returned string can be used as the ...
Convert urlsafe string to :class:`~google.cloud.datastore.key.Key`. This is intended to work with the "legacy" representation of a datastore "Key" used within Google App Engine (a so-called "Reference"). This assumes that ``urlsafe`` was created within an App Engine app via something li...
def from_legacy_urlsafe(cls, urlsafe): """Convert urlsafe string to :class:`~google.cloud.datastore.key.Key`. This is intended to work with the "legacy" representation of a datastore "Key" used within Google App Engine (a so-called "Reference"). This assumes that ``urlsafe`` was created...
Creates a parent key for the current path. Extracts all but the last element in the key path and creates a new key, while still matching the namespace and the project. :rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType` :returns: A new ``Key`` instance, whose path cons...
def _make_parent(self): """Creates a parent key for the current path. Extracts all but the last element in the key path and creates a new key, while still matching the namespace and the project. :rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType` :returns: A ne...
The parent of the current key. :rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType` :returns: A new ``Key`` instance, whose path consists of all but the last element of current path. If the current key has only one path element, returns ``None``.
def parent(self): """The parent of the current key. :rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType` :returns: A new ``Key`` instance, whose path consists of all but the last element of current path. If the current key has only one path el...
Factory: construct a record set given its API representation :type resource: dict :param resource: record sets representation returned from the API :type zone: :class:`google.cloud.dns.zone.ManagedZone` :param zone: A zone which holds one or more record sets. :rtype: :class:`...
def from_api_repr(cls, resource, zone): """Factory: construct a record set given its API representation :type resource: dict :param resource: record sets representation returned from the API :type zone: :class:`google.cloud.dns.zone.ManagedZone` :param zone: A zone which holds...
The entry point for the worker thread. Pulls pending log entries off the queue and writes them in batches to the Cloud Logger.
def _thread_main(self): """The entry point for the worker thread. Pulls pending log entries off the queue and writes them in batches to the Cloud Logger. """ _LOGGER.debug("Background thread started.") quit_ = False while True: batch = self._cloud_lo...
Starts the background thread. Additionally, this registers a handler for process exit to attempt to send any pending log entries before shutdown.
def start(self): """Starts the background thread. Additionally, this registers a handler for process exit to attempt to send any pending log entries before shutdown. """ with self._operational_lock: if self.is_alive: return self._thread =...
Signals the background thread to stop. This does not terminate the background thread. It simply queues the stop signal. If the main process exits before the background thread processes the stop signal, it will be terminated without finishing work. The ``grace_period`` parameter will giv...
def stop(self, grace_period=None): """Signals the background thread to stop. This does not terminate the background thread. It simply queues the stop signal. If the main process exits before the background thread processes the stop signal, it will be terminated without finishing ...
Callback that attempts to send pending logs before termination.
def _main_thread_terminated(self): """Callback that attempts to send pending logs before termination.""" if not self.is_alive: return if not self._queue.empty(): print( "Program shutting down, attempting to send %d queued log " "entries to...
Queues a log entry to be written by the background thread. :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 ...
def enqueue( self, record, message, resource=None, labels=None, trace=None, span_id=None ): """Queues a log entry to be written by the background thread. :type record: :class:`logging.LogRecord` :param record: Python log record that the handler was called with. :type messag...
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...
Lex a field path into tokens (including dots). Args: path (str): field path to be lexed. Returns: List(str): tokens
def _tokenize_field_path(path): """Lex a field path into tokens (including dots). Args: path (str): field path to be lexed. Returns: List(str): tokens """ pos = 0 get_token = TOKENS_REGEX.match match = get_token(path) while match is not None: type_ = match.lastgr...
Split a field path into valid elements (without dots). Args: path (str): field path to be lexed. Returns: List(str): tokens Raises: ValueError: if the path does not match the elements-interspersed- with-dots pattern.
def split_field_path(path): """Split a field path into valid elements (without dots). Args: path (str): field path to be lexed. Returns: List(str): tokens Raises: ValueError: if the path does not match the elements-interspersed- with-dots pattern. """ ...
Parse a **field path** from into a list of nested field names. See :func:`field_path` for more on **field paths**. Args: api_repr (str): The unique Firestore api representation which consists of either simple or UTF-8 field names. It cannot exceed 1500 bytes, and ca...
def parse_field_path(api_repr): """Parse a **field path** from into a list of nested field names. See :func:`field_path` for more on **field paths**. Args: api_repr (str): The unique Firestore api representation which consists of either simple or UTF-8 field names. It canno...
Create a **field path** from a list of nested field names. A **field path** is a ``.``-delimited concatenation of the field names. It is used to represent a nested field. For example, in the data .. code-block: python data = { 'aa': { 'bb': { 'cc': 10,...
def render_field_path(field_names): """Create a **field path** from a list of nested field names. A **field path** is a ``.``-delimited concatenation of the field names. It is used to represent a nested field. For example, in the data .. code-block: python data = { 'aa': { ...
Get a (potentially nested) value from a dictionary. If the data is nested, for example: .. code-block:: python >>> data { 'top1': { 'middle2': { 'bottom3': 20, 'bottom4': 22, }, 'middle5': True, ...
def get_nested_value(field_path, data): """Get a (potentially nested) value from a dictionary. If the data is nested, for example: .. code-block:: python >>> data { 'top1': { 'middle2': { 'bottom3': 20, 'bottom4': 22, ...
Factory: create a FieldPath from the string formatted per the API. Args: api_repr (str): a string path, with non-identifier elements quoted It cannot exceed 1500 characters, and cannot be empty. Returns: (:class:`FieldPath`) An instance parsed from ``api_repr``. ...
def from_api_repr(cls, api_repr): """Factory: create a FieldPath from the string formatted per the API. Args: api_repr (str): a string path, with non-identifier elements quoted It cannot exceed 1500 characters, and cannot be empty. Returns: (:class:`FieldPath...
Factory: create a FieldPath from a unicode string representation. This method splits on the character `.` and disallows the characters `~*/[]`. To create a FieldPath whose components have those characters, call the constructor. Args: path_string (str): A unicode string whic...
def from_string(cls, path_string): """Factory: create a FieldPath from a unicode string representation. This method splits on the character `.` and disallows the characters `~*/[]`. To create a FieldPath whose components have those characters, call the constructor. Args: ...
Check whether ``other`` is an ancestor. Returns: (bool) True IFF ``other`` is an ancestor or equal to ``self``, else False.
def eq_or_parent(self, other): """Check whether ``other`` is an ancestor. Returns: (bool) True IFF ``other`` is an ancestor or equal to ``self``, else False. """ return self.parts[: len(other.parts)] == other.parts[: len(self.parts)]
Return field paths for all parents. Returns: Set[:class:`FieldPath`]
def lineage(self): """Return field paths for all parents. Returns: Set[:class:`FieldPath`] """ indexes = six.moves.range(1, len(self.parts)) return {FieldPath(*self.parts[:index]) for index in indexes}
Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. Example: >>> from google.api_core import operations_v1 >>> api = operations_v1.OperationsClient() >>> ...
def get_operation( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT ): """Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. Example: ...
Lists operations that match the specified filter in the request. Example: >>> from google.api_core import operations_v1 >>> api = operations_v1.OperationsClient() >>> name = '' >>> >>> # Iterate over all results >>> for operation in api.li...
def list_operations( self, name, filter_, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT, ): """ Lists operations that match the specified filter in the request. Example: >>> from google.api_core import operations_v1 ...
Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. Clients can use :meth:`get_operation` or service- specific methods to check whether the cancellation succeeded or whether the operation co...
def cancel_operation( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT ): """Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. Clients can use :meth:`get_oper...
Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. Example: >>> from google.api_core import operations_v1 >>> api = operations_v1.OperationsClient() >>> n...
def delete_operation( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT ): """Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. Example: ...
Extract the config name from a full resource name. >>> config_name_from_full_name('projects/my-proj/configs/my-config') "my-config" :type full_name: str :param full_name: The full resource name of a config. The full resource name looks like ``projects/project-name/configs/config-na...
def config_name_from_full_name(full_name): """Extract the config name from a full resource name. >>> config_name_from_full_name('projects/my-proj/configs/my-config') "my-config" :type full_name: str :param full_name: The full resource name of a config. The full resource name looks like...
Extract the variable name from a full resource name. >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/var-name') "var-name" >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/another/var/name') "another/var/...
def variable_name_from_full_name(full_name): """Extract the variable name from a full resource name. >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/var-name') "var-name" >>> variable_name_from_full_name( 'projects/my-proj/configs/my-con...
Return the maximum value in this histogram. If there are no values in the histogram at all, return 600. Returns: int: The maximum value in the histogram.
def max(self): """Return the maximum value in this histogram. If there are no values in the histogram at all, return 600. Returns: int: The maximum value in the histogram. """ if len(self._data) == 0: return 600 return next(iter(reversed(sorted(s...
Return the minimum value in this histogram. If there are no values in the histogram at all, return 10. Returns: int: The minimum value in the histogram.
def min(self): """Return the minimum value in this histogram. If there are no values in the histogram at all, return 10. Returns: int: The minimum value in the histogram. """ if len(self._data) == 0: return 10 return next(iter(sorted(self._data.k...
Add the value to this histogram. Args: value (int): The value. Values outside of ``10 <= x <= 600`` will be raised to ``10`` or reduced to ``600``.
def add(self, value): """Add the value to this histogram. Args: value (int): The value. Values outside of ``10 <= x <= 600`` will be raised to ``10`` or reduced to ``600``. """ # If the value is out of bounds, bring it in bounds. value = int(value) ...
Return the value that is the Nth precentile in the histogram. Args: percent (Union[int, float]): The precentile being sought. The default consumer implementations use consistently use ``99``. Returns: int: The value corresponding to the requested percentile.
def percentile(self, percent): """Return the value that is the Nth precentile in the histogram. Args: percent (Union[int, float]): The precentile being sought. The default consumer implementations use consistently use ``99``. Returns: int: The value corr...
Return a fully-qualified job string.
def job_path(cls, project, location, job): """Return a fully-qualified job string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/jobs/{job}", project=project, location=location, job=job, )
Union[datetime.datetime, None]: Datetime at which the model was created (:data:`None` until set from the server). Read-only.
def created(self): """Union[datetime.datetime, None]: Datetime at which the model was created (:data:`None` until set from the server). Read-only. """ value = self._proto.creation_time if value is not None and value != 0: # value will be in milliseconds. ...
Creates a job. Example: >>> from google.cloud import scheduler_v1beta1 >>> >>> client = scheduler_v1beta1.CloudSchedulerClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> >>> # TODO: Initialize `job`:...
def create_job( self, parent, job, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a job. Example: >>> from google.cloud import scheduler_v1beta1 ...
Union[datetime.datetime, None]: Datetime at which the model was last modified (:data:`None` until set from the server). Read-only.
def modified(self): """Union[datetime.datetime, None]: Datetime at which the model was last modified (:data:`None` until set from the server). Read-only. """ value = self._proto.last_modified_time if value is not None and value != 0: # value will be in millis...
Union[datetime.datetime, None]: The datetime when this model expires. If not present, the model will persist indefinitely. Expired models will be deleted and their storage reclaimed.
def expires(self): """Union[datetime.datetime, None]: The datetime when this model expires. If not present, the model will persist indefinitely. Expired models will be deleted and their storage reclaimed. """ value = self._properties.get("expirationTime") if value is not ...
Factory: construct a model resource given its API representation Args: resource (Dict[str, object]): Model resource representation from the API Returns: google.cloud.bigquery.model.Model: Model parsed from ``resource``.
def from_api_repr(cls, resource): """Factory: construct a model resource given its API representation Args: resource (Dict[str, object]): Model resource representation from the API Returns: google.cloud.bigquery.model.Model: Model parsed from ``resource`...
str: URL path for the model's APIs.
def path(self): """str: URL path for the model's APIs.""" return "/projects/%s/datasets/%s/models/%s" % ( self._proto.project_id, self._proto.dataset_id, self._proto.model_id, )
Factory: construct a model reference given its API representation Args: resource (Dict[str, object]): Model reference representation returned from the API Returns: google.cloud.bigquery.model.ModelReference: Model reference parsed from ``resourc...
def from_api_repr(cls, resource): """Factory: construct a model reference given its API representation Args: resource (Dict[str, object]): Model reference representation returned from the API Returns: google.cloud.bigquery.model.ModelReference: ...
Construct a model reference from model ID string. Args: model_id (str): A model ID in standard SQL format. If ``default_project`` is not specified, this must included a project ID, dataset ID, and model ID, each separated by ``.``. default...
def from_string(cls, model_id, default_project=None): """Construct a model reference from model ID string. Args: model_id (str): A model ID in standard SQL format. If ``default_project`` is not specified, this must included a project ID, dataset ...
Leases tasks from a pull queue for ``lease_duration``. This method is invoked by the worker to obtain a lease. The worker must acknowledge the task via ``AcknowledgeTask`` after they have performed the work associated with the task. The ``payload`` is intended to store data that the wo...
def lease_tasks( self, parent, lease_duration, max_tasks=None, response_view=None, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Leases tasks ...
Helper to format a LogRecord in in Stackdriver fluentd format. :rtype: str :returns: JSON str to be written to the log file.
def format_stackdriver_json(record, message): """Helper to format a LogRecord in in Stackdriver fluentd format. :rtype: str :returns: JSON str to be written to the log file. """ subsecond, second = math.modf(record.created) payload = { "message": message, "timestamp": {...
Get trace_id from flask request headers. :rtype: str :returns: TraceID in HTTP request headers.
def get_trace_id_from_flask(): """Get trace_id from flask request headers. :rtype: str :returns: TraceID in HTTP request headers. """ if flask is None or not flask.request: return None header = flask.request.headers.get(_FLASK_TRACE_HEADER) if header is None: return None ...
Get trace_id from webapp2 request headers. :rtype: str :returns: TraceID in HTTP request headers.
def get_trace_id_from_webapp2(): """Get trace_id from webapp2 request headers. :rtype: str :returns: TraceID in HTTP request headers. """ if webapp2 is None: return None try: # get_request() succeeds if we're in the middle of a webapp2 # request, or raises an assertion ...
Get trace_id from django request headers. :rtype: str :returns: TraceID in HTTP request headers.
def get_trace_id_from_django(): """Get trace_id from django request headers. :rtype: str :returns: TraceID in HTTP request headers. """ request = _get_django_request() if request is None: return None header = request.META.get(_DJANGO_TRACE_HEADER) if header is None: re...
Helper to get trace_id from web application request header. :rtype: str :returns: TraceID in HTTP request headers.
def get_trace_id(): """Helper to get trace_id from web application request header. :rtype: str :returns: TraceID in HTTP request headers. """ checkers = ( get_trace_id_from_django, get_trace_id_from_flask, get_trace_id_from_webapp2, ) for checker in checkers: ...
Return a fully-qualified group string.
def group_path(cls, project, group): """Return a fully-qualified group string.""" return google.api_core.path_template.expand( "projects/{project}/groups/{group}", project=project, group=group )
Lists the existing groups. Example: >>> from google.cloud import monitoring_v3 >>> >>> client = monitoring_v3.GroupServiceClient() >>> >>> name = client.project_path('[PROJECT]') >>> >>> # Iterate over all results >...
def list_groups( self, name, children_of_group=None, ancestors_of_group=None, descendants_of_group=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): "...
Returns a list of ``Voice`` supported for synthesis. Example: >>> from google.cloud import texttospeech_v1beta1 >>> >>> client = texttospeech_v1beta1.TextToSpeechClient() >>> >>> response = client.list_voices() Args: language_code...
def list_voices( self, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Returns a list of ``Voice`` supported for synthesis. Example: >>> from google....
Synthesizes speech synchronously: receive results after all text input has been processed. Example: >>> from google.cloud import texttospeech_v1beta1 >>> >>> client = texttospeech_v1beta1.TextToSpeechClient() >>> >>> # TODO: Initialize `input_...
def synthesize_speech( self, input_, voice, audio_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Synthesizes speech synchronously: receive results after all text inp...
Raise AttributeError if the credentials are unsigned. :type credentials: :class:`google.auth.credentials.Signing` :param credentials: The credentials used to create a private key for signing text. :raises: :exc:`AttributeError` if credentials is not an instance of :clas...
def ensure_signed_credentials(credentials): """Raise AttributeError if the credentials are unsigned. :type credentials: :class:`google.auth.credentials.Signing` :param credentials: The credentials used to create a private key for signing text. :raises: :exc:`AttributeError` if ...
Gets query parameters for creating a signed URL. :type credentials: :class:`google.auth.credentials.Signing` :param credentials: The credentials used to create a private key for signing text. :type expiration: int or long :param expiration: When the signed URL should expire. ...
def get_signed_query_params_v2(credentials, expiration, string_to_sign): """Gets query parameters for creating a signed URL. :type credentials: :class:`google.auth.credentials.Signing` :param credentials: The credentials used to create a private key for signing text. :type expi...
Convert 'expiration' to a number of seconds in the future. :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :raises: :exc:`TypeError` when expiration is not a valid type. :rtype: int :returns: a timestamp a...
def get_expiration_seconds_v2(expiration): """Convert 'expiration' to a number of seconds in the future. :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :raises: :exc:`TypeError` when expiration is not a valid ...
Convert 'expiration' to a number of seconds offset from the current time. :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :raises: :exc:`TypeError` when expiration is not a valid type. :raises: :exc:`ValueError...
def get_expiration_seconds_v4(expiration): """Convert 'expiration' to a number of seconds offset from the current time. :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :raises: :exc:`TypeError` when expiration ...
Canonicalize headers for signing. See: https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers :type headers: Union[dict|List(Tuple(str,str))] :param headers: (Optional) Additional HTTP headers to be included as part of the signed URLs. See: ...
def get_canonical_headers(headers): """Canonicalize headers for signing. See: https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers :type headers: Union[dict|List(Tuple(str,str))] :param headers: (Optional) Additional HTTP headers to be included...
Canonicalize method, resource :type method: str :param method: The HTTP verb that will be used when requesting the URL. Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the signature will additionally contain the `x-goog-resumable` header, and th...
def canonicalize(method, resource, query_parameters, headers): """Canonicalize method, resource :type method: str :param method: The HTTP verb that will be used when requesting the URL. Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the signature will additio...
Generate a V2 signed URL to provide query-string auth'n to a resource. .. note:: Assumes ``credentials`` implements the :class:`google.auth.credentials.Signing` interface. Also assumes ``credentials`` has a ``service_account_email`` property which identifies the credentials. ....
def generate_signed_url_v2( credentials, resource, expiration, api_access_endpoint="", method="GET", content_md5=None, content_type=None, response_type=None, response_disposition=None, generation=None, headers=None, query_parameters=None, ): """Generate a V2 signed UR...
Generate a V4 signed URL to provide query-string auth'n to a resource. .. note:: Assumes ``credentials`` implements the :class:`google.auth.credentials.Signing` interface. Also assumes ``credentials`` has a ``service_account_email`` property which identifies the credentials. ....
def generate_signed_url_v4( credentials, resource, expiration, api_access_endpoint=DEFAULT_ENDPOINT, method="GET", content_md5=None, content_type=None, response_type=None, response_disposition=None, generation=None, headers=None, query_parameters=None, _request_timest...
Return a fully-qualified glossary string.
def glossary_path(cls, project, location, glossary): """Return a fully-qualified glossary string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/glossaries/{glossary}", project=project, location=location, glossary=...
Translates input text and returns translated text. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> # TODO: Initialize `contents`: >>> contents = [] >...
def translate_text( self, contents, target_language_code, mime_type=None, source_language_code=None, parent=None, model=None, glossary_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAU...
Detects the language of text within a request. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> response = client.detect_language() Args: parent (str): O...
def detect_language( self, parent=None, model=None, content=None, mime_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Detects the language of text within ...
Returns a list of supported languages for translation. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> response = client.get_supported_languages() Args: ...
def get_supported_languages( self, parent=None, display_language_code=None, model=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Returns a list of supported languages ...
Translates a large volume of text in asynchronous batch mode. This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location. Thi...
def batch_translate_text( self, source_language_code, target_language_codes, input_configs, output_config, parent=None, models=None, glossaries=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEF...
Creates a glossary and returns the long-running operation. Returns NOT\_FOUND, if the project doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() >>> >>> parent =...
def create_glossary( self, parent, glossary, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a glossary and returns the long-running operation. Returns NOT\_FOUND, if...
Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns NOT\_FOUND, if the glossary doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() ...
def delete_glossary( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns NOT\_...
Return a copy of time_series with the points removed.
def _extract_header(time_series): """Return a copy of time_series with the points removed.""" return TimeSeries( metric=time_series.metric, resource=time_series.resource, metric_kind=time_series.metric_kind, value_type=time_series.value_type, )
Build a :mod:`pandas` dataframe out of time series. :type time_series_iterable: iterable over :class:`~google.cloud.monitoring_v3.types.TimeSeries` :param time_series_iterable: An iterable (e.g., a query object) yielding time series. :type label: str :param label: (Optional) Th...
def _build_dataframe(time_series_iterable, label=None, labels=None): # pragma: NO COVER """Build a :mod:`pandas` dataframe out of time series. :type time_series_iterable: iterable over :class:`~google.cloud.monitoring_v3.types.TimeSeries` :param time_series_iterable: An iterable (e.g., a q...
Build the combined resource and metric labels, with resource_type.
def _extract_labels(time_series): """Build the combined resource and metric labels, with resource_type.""" labels = {"resource_type": time_series.resource.type} labels.update(time_series.resource.labels) labels.update(time_series.metric.labels) return labels
Sort label names, putting well-known resource labels first.
def _sorted_resource_labels(labels): """Sort label names, putting well-known resource labels first.""" head = [label for label in TOP_RESOURCE_LABELS if label in labels] tail = sorted(label for label in labels if label not in TOP_RESOURCE_LABELS) return head + tail
Starts a thread and marks it as a daemon thread.
def start_daemon_thread(*args, **kwargs): """Starts a thread and marks it as a daemon thread.""" thread = threading.Thread(*args, **kwargs) thread.daemon = True thread.start() return thread
Invoke a callback, swallowing and logging any exceptions.
def safe_invoke_callback(callback, *args, **kwargs): """Invoke a callback, swallowing and logging any exceptions.""" # pylint: disable=bare-except # We intentionally want to swallow all exceptions. try: return callback(*args, **kwargs) except Exception: _LOGGER.exception("Error while...
Create a project bound to the current client. Use :meth:`Project.reload() \ <google.cloud.resource_manager.project.Project.reload>` to retrieve project metadata after creating a :class:`~google.cloud.resource_manager.project.Project` instance. .. note: This does no...
def new_project(self, project_id, name=None, labels=None): """Create a project bound to the current client. Use :meth:`Project.reload() \ <google.cloud.resource_manager.project.Project.reload>` to retrieve project metadata after creating a :class:`~google.cloud.resource_manager....
Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: The ID for this project. :rtype: :class:...
def fetch_project(self, project_id): """Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: T...
List the projects visible to this client. Example:: >>> from google.cloud import resource_manager >>> client = resource_manager.Client() >>> for project in client.list_projects(): ... print(project.project_id) List all projects with label ``'environ...
def list_projects(self, filter_params=None, page_size=None): """List the projects visible to this client. Example:: >>> from google.cloud import resource_manager >>> client = resource_manager.Client() >>> for project in client.list_projects(): ... pr...
Return a fully-qualified session string.
def session_path(cls, project, instance, database, session): """Return a fully-qualified session string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/databases/{database}/sessions/{session}", project=project, instance=instan...
Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions. Sessions can only execute one transaction at a time. To execute multiple concurrent read-writ...
def create_session( self, database, session=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new session. A session can be used to perform transactions that re...
Like ``ExecuteSql``, except returns the result set as a stream. Unlike ``ExecuteSql``, there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB. Example: >>> from google.c...
def execute_streaming_sql( self, session, sql, transaction=None, params=None, param_types=None, resume_token=None, query_mode=None, partition_token=None, seqno=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=goo...
Executes a batch of SQL DML statements. This method allows many statements to be run with lower latency than submitting them sequentially with ``ExecuteSql``. Statements are executed in order, sequentially. ``ExecuteBatchDmlResponse`` will contain a ``ResultSet`` for each DML st...
def execute_batch_dml( self, session, transaction, statements, seqno, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Executes a batch of SQL DML statements. This met...
Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ``ExecuteSql``. This method cannot be used to return a result set larger than 10 MiB; if the read matches more data than that, the read fails with a ``FAILED_PRECONDITION`` error. Reads ...
def read( self, session, table, columns, key_set, transaction=None, index=None, limit=None, resume_token=None, partition_token=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFA...
Commits a transaction. The request includes the mutations to be applied to rows in the database. ``Commit`` might return an ``ABORTED`` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other re...
def commit( self, session, mutations, transaction_id=None, single_use_transaction=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Commits a transaction. The req...
Creates a set of partition tokens that can be used to execute a query operation in parallel. Each of the returned partition tokens can be used by ``ExecuteStreamingSql`` to specify a subset of the query result to read. The same session and read-only transaction must be used by the Partit...
def partition_query( self, session, sql, transaction=None, params=None, param_types=None, partition_options=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): ...
Creates a set of partition tokens that can be used to execute a read operation in parallel. Each of the returned partition tokens can be used by ``StreamingRead`` to specify a subset of the read result to read. The same session and read-only transaction must be used by the PartitionReadR...
def partition_read( self, session, table, key_set, transaction=None, index=None, columns=None, partition_options=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ...
Report events issued when end user interacts with customer's application that uses Cloud Talent Solution. You may inspect the created events in `self service tools <https://console.cloud.google.com/talent-solution/overview>`__. `Learn more <https://cloud.google.com/talent-solutio...
def create_client_event( self, parent, client_event, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Report events issued when end user interacts with customer's application ...
Create an instance of the GAPIC Datastore API. :type client: :class:`~google.cloud.datastore.client.Client` :param client: The client that holds configuration details. :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient` :returns: A datastore API instance with the proper credentials.
def make_datastore_api(client): """Create an instance of the GAPIC Datastore API. :type client: :class:`~google.cloud.datastore.client.Client` :param client: The client that holds configuration details. :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient` :returns: A datastore API insta...
Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of Python corresponding to the ``nox`` binary the ``PATH`` can run the tests.
def default(session): """Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of Python corresponding to the ``nox`` binary the ``PATH`` can run the tests. """ # Install all test dependencies, t...
Run the snippets test suite.
def snippets(session): """Run the snippets test suite.""" # Sanity check: Only run snippets tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable.") # Install all test dependencies, ...
Run linters. Returns a failure if the linters find linting errors or sufficiently serious code quality issues.
def lint(session): """Run linters. Returns a failure if the linters find linting errors or sufficiently serious code quality issues. """ session.install("black", "flake8", *LOCAL_DEPS) session.install(".") session.run("flake8", os.path.join("google", "cloud", "bigquery")) session.run("...
Indent some text. Note that this is present as ``textwrap.indent``, but not in Python 2. Args: lines (str): The newline delimited string to be indented. prefix (Optional[str]): The prefix to indent each line with. Default to two spaces. Returns: str: The newly indented...
def _indent(lines, prefix=" "): """Indent some text. Note that this is present as ``textwrap.indent``, but not in Python 2. Args: lines (str): The newline delimited string to be indented. prefix (Optional[str]): The prefix to indent each line with. Default to two spaces. ...
Return the time that the message was originally published. Returns: datetime: The date and time that the message was published.
def publish_time(self): """Return the time that the message was originally published. Returns: datetime: The date and time that the message was published. """ timestamp = self._message.publish_time delta = datetime.timedelta( seconds=timestamp.seconds, mi...
Acknowledge the given message. Acknowledging a message in Pub/Sub means that you are done with it, and it will not be delivered to this subscription again. You should avoid acknowledging messages until you have *finished* processing them, so that in the event of a failure, you r...
def ack(self): """Acknowledge the given message. Acknowledging a message in Pub/Sub means that you are done with it, and it will not be delivered to this subscription again. You should avoid acknowledging messages until you have *finished* processing them, so that in the event o...
Release the message from lease management. This informs the policy to no longer hold on to the lease for this message. Pub/Sub will re-deliver the message if it is not acknowledged before the existing lease expires. .. warning:: For most use cases, the only reason to drop a...
def drop(self): """Release the message from lease management. This informs the policy to no longer hold on to the lease for this message. Pub/Sub will re-deliver the message if it is not acknowledged before the existing lease expires. .. warning:: For most use cases...
Inform the policy to lease this message continually. .. note:: This method is called by the constructor, and you should never need to call it manually.
def lease(self): """Inform the policy to lease this message continually. .. note:: This method is called by the constructor, and you should never need to call it manually. """ self._request_queue.put( requests.LeaseRequest(ack_id=self._ack_id, byte_si...
Resets the deadline for acknowledgement. New deadline will be the given value of seconds from now. The default implementation handles this for you; you should not need to manually deal with setting ack deadlines. The exception case is if you are implementing your own custom subclass of...
def modify_ack_deadline(self, seconds): """Resets the deadline for acknowledgement. New deadline will be the given value of seconds from now. The default implementation handles this for you; you should not need to manually deal with setting ack deadlines. The exception case is ...
Decline to acknowldge the given message. This will cause the message to be re-delivered to the subscription.
def nack(self): """Decline to acknowldge the given message. This will cause the message to be re-delivered to the subscription. """ self._request_queue.put( requests.NackRequest(ack_id=self._ack_id, byte_size=self.size) )
Runs a query while printing status updates Args: client (google.cloud.bigquery.client.Client): Client to bundle configuration needed for API requests. query (str): SQL query to be executed. Defaults to the standard SQL dialect. Use the ``job_config`` parameter to...
def _run_query(client, query, job_config=None): """Runs a query while printing status updates Args: client (google.cloud.bigquery.client.Client): Client to bundle configuration needed for API requests. query (str): SQL query to be executed. Defaults to the standard SQL d...