Example #1
0
    def __init__(self, blob_key):
        if isinstance(blob_key, bytes):
            if len(blob_key) > _MAX_STRING_LENGTH:
                raise exceptions.BadValueError(
                    "blob key must be under {:d} "
                    "bytes.".format(_MAX_STRING_LENGTH))
        elif blob_key is not None:
            raise exceptions.BadValueError(
                "blob key should be bytes; received "
                "{} (a {})".format(blob_key, blob_key.__class__.__name__))

        self._blob_key = blob_key
Example #2
0
    def _set_value(self, entity, value):
        """Set a value in an entity for a property.

        This performs validation first. For a repeated property the value
        should be a list (or similar container).

        Args:
            entity (Model): An entity to set a value on.
            value (Any): The value to be stored for this property.

        Raises:
            ReadonlyPropertyError: If the ``entity`` is the result of a
                projection query.
            .BadValueError: If the current property is repeated but the
                ``value`` is not a basic container (:class:`list`,
                :class:`tuple`, :class:`set` or :class:`frozenset`).
        """
        if entity._projection:
            raise ReadonlyPropertyError(
                "You cannot set property values of a projection entity"
            )

        if self._repeated:
            if not isinstance(value, (list, tuple, set, frozenset)):
                raise exceptions.BadValueError(
                    "Expected list or tuple, got {!r}".format(value)
                )
            value = [self._do_validate(v) for v in value]
        else:
            if value is not None:
                value = self._do_validate(value)

        self._store_value(entity, value)
Example #3
0
    def _do_validate(self, value):
        """Call all validations on the value.

        This transforms the ``value`` via:

        * Calling the derived ``_validate()`` method(s) (on subclasses that
          don't define ``_to_base_type``),
        * Calling the custom validator function

        After transforming, it checks if the transformed value is in
        ``choices`` (if defined).

        It's possible that one of the ``_validate()`` methods will raise
        an exception.

        If ``value`` is a base-value, this will do nothing and return it.

        .. note::

            This does not call all composable ``_validate()`` methods.
            It only calls ``_validate()`` methods up to the
            first class in the hierarchy that defines a ``_to_base_type()``
            method, when the MRO is traversed looking for ``_validate()`` and
            ``_to_base_type()`` methods.

        .. note::

            For a repeated property this method should be called
            for each value in the list, not for the list as a whole.

        Args:
            value (Any): The value to be converted / validated.

        Returns:
            Any: The transformed ``value``, possibly modified in an idempotent
            way.
        """
        if isinstance(value, _BaseValue):
            return value

        value = self._call_shallow_validation(value)

        if self._validator is not None:
            new_value = self._validator(self, value)
            if new_value is not None:
                value = new_value

        if self._choices is not None:
            if value not in self._choices:
                raise exceptions.BadValueError(
                    "Value {!r} for property {} is not an allowed "
                    "choice".format(value, self._name)
                )

        return value
Example #4
0
def _parse_from_args(pairs=None,
                     flat=None,
                     app=None,
                     namespace=None,
                     parent=None):
    """Construct a key the path (and possibly a parent key).

    Args:
        pairs (Optional[Iterable[Tuple[str, Union[str, int]]]]): An iterable
            of (kind, ID) pairs.
        flat (Optional[Iterable[Union[str, int]]]): An iterable of the
            (kind, ID) pairs but flattened into a single value. For example,
            the pairs ``[("Parent", 1), ("Child", "a")]`` would be flattened to
            ``["Parent", 1, "Child", "a"]``.
        app (Optional[str]): The Google Cloud Platform project (previously
            on Google App Engine, this was called the Application ID).
        namespace (Optional[str]): The namespace for the key.
        parent (Optional[~.ndb.key.Key]): The parent of the key being
            constructed. If provided, the key path will be **relative** to the
            parent key's path.

    Returns:
        ~.datastore.Key: The constructed key.

    Raises:
        .BadValueError: If ``parent`` is passed but is not a ``Key``.
    """
    flat = _get_path(flat, pairs)
    _clean_flat_path(flat)

    parent_ds_key = None
    if parent is None:
        project = _project_from_app(app)
    else:
        project = _project_from_app(app, allow_empty=True)
        if not isinstance(parent, Key):
            raise exceptions.BadValueError(
                "Expected Key instance, got {!r}".format(parent))
        # Offload verification of parent to ``google.cloud.datastore.Key()``.
        parent_ds_key = parent._key

    return google.cloud.datastore.Key(*flat,
                                      parent=parent_ds_key,
                                      project=project,
                                      namespace=namespace)