Ejemplo n.º 1
0
    def set(self, value):
        self.raw = value
        if isinstance(value, (list, tuple)):
            values = value
        elif not isinstance(value, text_type):
            values = list(value)
        elif self.separator_regex:
            # a text regexp separator
            values = self.separator_regex.split(value)
        else:
            # a text static separator
            values = value.split(self.separator)

        del self[:]
        prune = self.prune_empty
        success = []
        for value in values:
            if prune and not value:
                continue
            child = self.member_schema()
            success.append(child.set(value))
            self.append(child)

        res = all(success)
        element_set.send(self, adapted=res)
        return res
Ejemplo n.º 2
0
    def set(self, value):
        self.raw = value
        if isinstance(value, (list, tuple)):
            values = value
        elif not isinstance(value, string_types):
            values = list(value)
        elif self.separator_regex:
            # a text regexp separator
            values = self.separator_regex.split(value)
        else:
            # a text static separator
            values = value.split(self.separator)

        del self[:]
        prune = self.prune_empty
        success = []
        for value in values:
            if prune and not value:
                continue
            child = self.member_schema()
            success.append(child.set(value))
            self.append(child)

        res = all(success)
        element_set.send(self, adapted=res)
        return res
Ejemplo n.º 3
0
    def set(self, value, policy=None):
        self.raw = value
        pairs = list(to_pairs(value))
        self._reset()

        if policy is None:
            policy = self.policy
        if policy not in ('strict', 'subset', 'duck', None):
            raise RuntimeError("Unknown %s policy %r" % (
                self.__class__.__name__, policy))

        if policy == 'strict':
            missing, extra = _evaluate_dict_strict_policy(self, pairs)
            if missing and extra:
                raise KeyError(
                    'Strict %s %r schema does not allow keys %r and '
                    'requires keys %r' % (
                        self.__class__.__name__, self.name,
                        list(extra), list(missing)))
            elif missing:
                # match previous logic's exception type here
                raise TypeError(
                    'Strict %s %r schema requires keys %r' % (
                        self.__class__.__name__, self.name,
                        list(missing)))
            elif extra:
                raise KeyError(
                    'Strict %s %r schema does not allow keys %r' % (
                        self.__class__.__name__, self.name,
                        list(extra)))
        elif policy == 'subset':
            mismatch = _evaluate_dict_subset_policy(self, pairs)
            if mismatch:
                raise KeyError(
                    'Subset %s %r schema does not allow keys %r' % (
                        self.__class__.__name__, self.name,
                        list(mismatch)))

        fields = self.field_schema_mapping
        converted = True
        for key, value in pairs:
            if PY2 and isinstance(key, bytestring_type):
                key = key.decode('ascii', 'replace')
            if key not in fields:
                continue
            if dict.__contains__(self, key):
                converted &= self[key].set(value)
            else:
                self[key] = el = fields[key]()
                converted &= el.set(value)
        element_set.send(self, adapted=converted)
        return converted
Ejemplo n.º 4
0
    def set(self, value, policy=None):
        self.raw = value
        pairs = list(to_pairs(value))
        self._reset()

        if policy is None:
            policy = self.policy
        if policy not in ('strict', 'subset', 'duck', None):
            raise RuntimeError("Unknown %s policy %r" %
                               (self.__class__.__name__, policy))

        if policy == 'strict':
            missing, extra = _evaluate_dict_strict_policy(self, pairs)
            if missing and extra:
                raise KeyError(
                    'Strict %s %r schema does not allow keys %r and '
                    'requires keys %r' % (self.__class__.__name__, self.name,
                                          list(extra), list(missing)))
            elif missing:
                # match previous logic's exception type here
                raise TypeError(
                    'Strict %s %r schema requires keys %r' %
                    (self.__class__.__name__, self.name, list(missing)))
            elif extra:
                raise KeyError(
                    'Strict %s %r schema does not allow keys %r' %
                    (self.__class__.__name__, self.name, list(extra)))
        elif policy == 'subset':
            mismatch = _evaluate_dict_subset_policy(self, pairs)
            if mismatch:
                raise KeyError(
                    'Subset %s %r schema does not allow keys %r' %
                    (self.__class__.__name__, self.name, list(mismatch)))

        fields = self.field_schema_mapping
        converted = True
        for key, value in pairs:
            if PY2 and isinstance(key, bytestring_type):
                key = key.decode('ascii', 'replace')
            if key not in fields:
                continue
            if dict.__contains__(self, key):
                converted &= self[key].set(value)
            else:
                self[key] = el = fields[key]()
                converted &= el.set(value)
        element_set.send(self, adapted=converted)
        return converted
Ejemplo n.º 5
0
 def set(self, value):
     self.raw = value
     try:
         res = self.explode(value)
         # TODO: historically explode() did not need to have a return value
         # but it would be nice to return it form set() as below.
         res = True if res is None else res  # compat
         element_set.send(self, adapted=res)
         return res
     except (SystemExit, KeyboardInterrupt, NotImplementedError):
         raise
     except Exception:
         # not wild about quashing here, but set() doesn't allow
         # adaptation exceptions to bubble up.
         element_set.send(self, adapted=False)
         return False
Ejemplo n.º 6
0
 def set(self, value):
     self.raw = value
     try:
         res = self.explode(value)
         # TODO: historically explode() did not need to have a return value
         # but it would be nice to return it form set() as below.
         res = True if res is None else res  # compat
         element_set.send(self, adapted=res)
         return res
     except (SystemExit, KeyboardInterrupt, NotImplementedError):
         raise
     except Exception:
         # not wild about quashing here, but set() doesn't allow
         # adaptation exceptions to bubble up.
         element_set.send(self, adapted=False)
         return False
Ejemplo n.º 7
0
    def set(self, obj):
        """Process *obj* and assign the native and text values.

        :returns: True if adaptation of *obj* was successful.

        Attempts to adapt the given object and assigns this element's
        :attr:`~flatland.Element.value` and :attr:`u`
        attributes in tandem.

        If adaptation succeeds, ``.value`` will contain the
        :meth:`adapted<adapt>` native Python value and ``.u`` will contain a
        text :meth:`serialized<serialize>` version of it.  A native value
        of ``None`` will be represented as ``u''`` in ``.u``.

        If adaptation fails, ``.value`` will be ``None`` and ``.u`` will
        contain ``str(obj)`` (or unicode), or ``u''`` for none.

        """
        self.raw = obj
        try:
            # adapt and normalize the value, if possible
            obj = self.value = self.adapt(obj)
        except AdaptationError:
            self.value = None  # could not be adapted
            # but, still try to textify it
            if obj is None:
                self.u = u''
            elif isinstance(obj, text_type):
                self.u = obj
            else:
                try:
                    self.u = text_transform(obj)
                except TypeError:
                    self.u = u''
                except UnicodeDecodeError:
                    self.u = text_type(obj, errors='replace')
            element_set.send(self, adapted=False)
            return False

        # stringify it, possibly storing what we received verbatim or a
        # normalized version of it.
        if obj is None:
            self.u = u''
        else:
            self.u = self.serialize(obj)
        element_set.send(self, adapted=True)
        return True
Ejemplo n.º 8
0
    def set(self, obj):
        """Process *obj* and assign the native and text values.

        :returns: True if adaptation of *obj* was successful.

        Attempts to adapt the given object and assigns this element's
        :attr:`~flatland.Element.value` and :attr:`u`
        attributes in tandem.

        If adaptation succeeds, ``.value`` will contain the
        :meth:`adapted<adapt>` native Python value and ``.u`` will contain a
        text :meth:`serialized<serialize>` version of it.  A native value
        of ``None`` will be represented as ``u''`` in ``.u``.

        If adaptation fails, ``.value`` will be ``None`` and ``.u`` will
        contain ``str(obj)`` (or unicode), or ``u''`` for none.

        """
        self.raw = obj
        try:
            # adapt and normalize the value, if possible
            obj = self.value = self.adapt(obj)
        except AdaptationError:
            self.value = None  # could not be adapted
            # but, still try to textify it
            if obj is None:
                self.u = u''
            elif isinstance(obj, text_type):
                self.u = obj
            else:
                try:
                    self.u = text_transform(obj)
                except TypeError:
                    self.u = u''
                except UnicodeDecodeError:
                    self.u = text_type(obj, errors='replace')
            element_set.send(self, adapted=False)
            return False

        # stringify it, possibly storing what we received verbatim or a
        # normalized version of it.
        if obj is None:
            self.u = u''
        else:
            self.u = self.serialize(obj)
        element_set.send(self, adapted=True)
        return True
Ejemplo n.º 9
0
    def set(self, value):
        """.. TODO:: doc set()"""
        self.raw = value
        pairs = to_pairs(value)
        self._reset()

        seen = set()
        converted = True
        for key, value in pairs:
            if not self.may_contain(key):
                raise KeyError('%s %r schema does not allow key %r' %
                               (type(self).__name__, self.name, key))
            converted &= self[key].set(value)
            seen.add(key)
        required = set(iterkeys(self))
        if seen != required:
            missing = required - seen
            raise TypeError(
                'all keys required for a set() operation, missing %s.' %
                (','.join(repr(key) for key in missing)))
        element_set.send(self, adapted=converted)
        return converted
Ejemplo n.º 10
0
    def set(self, value):
        """.. TODO:: doc set()"""
        self.raw = value
        pairs = to_pairs(value)
        self._reset()

        seen = set()
        converted = True
        for key, value in pairs:
            if not self.may_contain(key):
                raise KeyError(
                    '%s %r schema does not allow key %r' % (
                        type(self).__name__, self.name, key))
            converted &= self[key].set(value)
            seen.add(key)
        required = set(iterkeys(self))
        if seen != required:
            missing = required - seen
            raise TypeError(
                'all keys required for a set() operation, missing %s.' % (
                    ','.join(repr(key) for key in missing)))
        element_set.send(self, adapted=converted)
        return converted
Ejemplo n.º 11
0
    def set(self, iterable):
        """Assign the native and Unicode value.

        Attempts to adapt the given *iterable* and assigns this element's
        :attr:`value` and :attr:`u` attributes in tandem.  Returns True if the
        adaptation was successful.  See
        :meth:`Element.set()<flatland.schema.base.Element.set>`.

        Set must be supplied a Python sequence or iterable:

        .. doctest::

          >>> from flatland import Integer, List
          >>> Numbers = List.of(Integer)
          >>> nums = Numbers()
          >>> nums.set([1, 2, 3, 4])
          True
          >>> nums.value
          [1, 2, 3, 4]

        """

        del self[:]
        self.raw = iterable
        values, converted = [], True
        try:
            for v in iterable:
                el = self.member_schema()
                converted &= el.set(v)
                values.append(el)
            self.extend(values)
        except TypeError:
            element_set.send(self, adapted=False)
            return False
        else:
            element_set.send(self, adapted=converted)
            return converted
Ejemplo n.º 12
0
    def set(self, iterable):
        """Assign the native and Unicode value.

        Attempts to adapt the given *iterable* and assigns this element's
        :attr:`value` and :attr:`u` attributes in tandem.  Returns True if the
        adaptation was successful.  See
        :meth:`Element.set()<flatland.schema.base.Element.set>`.

        Set must be supplied a Python sequence or iterable:

        .. doctest::

          >>> from flatland import Integer, List
          >>> Numbers = List.of(Integer)
          >>> nums = Numbers()
          >>> nums.set([1, 2, 3, 4])
          True
          >>> nums.value
          [1, 2, 3, 4]

        """

        del self[:]
        self.raw = iterable
        values, converted = [], True
        try:
            for v in iterable:
                el = self.member_schema()
                converted &= el.set(v)
                values.append(el)
            self.extend(values)
        except TypeError:
            element_set.send(self, adapted=False)
            return False
        else:
            element_set.send(self, adapted=converted)
            return converted