Exemplo n.º 1
0
    def _open(self, bind, kwargs):
        """Return a ``'<partial'`` opener tag with no terminator."""
        contents = kwargs.pop('contents', None)

        if PY2:
            attributes = _unicode_keyed(kwargs)
        else:
            attributes = kwargs
        tagname = self.tagname
        new_contents = transform(tagname, attributes, contents, self._context,
                                 bind)

        if not new_contents:
            new_contents = u''
        elif hasattr(new_contents, '__html__'):
            new_contents = _unpack(new_contents)
        self.contents = self._markup(new_contents)

        if self._context[u'ordered_attributes']:
            pairs = sorted(attributes.items(), key=_attribute_sort_key)
        else:
            pairs = iteritems(attributes)
        guts = u' '.join(u'%s="%s"' % (k, _attribute_escape(v))
                         for k, v in pairs)
        if guts:
            return u'<' + tagname + u' ' + guts
        else:
            return u'<' + tagname
Exemplo n.º 2
0
    def using(cls, **overrides):
        """Return a class with attributes set from *\*\*overrides*.

        :param \*\*overrides: new values for any attributes already present on
          the class.  A ``TypeError`` is raised for unknown attributes.
        :returns: a new class
        """

        # TODO: See TODO in __init__
        # TODO: take this from 'validates_up' and 'validates_down',
        #       don't hardcode validators
        if 'validators' in overrides:
            overrides['validators'] = list(overrides['validators'])

        if 'properties' in overrides:
            if not isinstance(overrides['properties'], Properties):
                overrides['properties'] = Properties(overrides['properties'])

        for attribute, value in iteritems(overrides):
            # TODO: must make better
            if callable(value):
                value = staticmethod(value)
            if hasattr(cls, attribute):
                setattr(cls, attribute, value)
                continue
            raise TypeError("%r is an invalid keyword argument: not a known "
                            "argument or an overridable class property of %s" %
                            (attribute, cls.__name__))
        return cls
Exemplo n.º 3
0
 def u(self):
     """A string repr of the element."""
     pairs = ((key, value.u
               if isinstance(value, Container) else decode_repr(value.u))
              for key, value in iteritems(self))
     return u'{%s}' % u', '.join(u"%s: %s" % (decode_repr(k), v)
                                 for k, v in pairs)
Exemplo n.º 4
0
    def using(cls, **overrides):
        """Return a class with attributes set from *\*\*overrides*.

        :param \*\*overrides: new values for any attributes already present on
          the class.  A ``TypeError`` is raised for unknown attributes.
        :returns: a new class
        """

        # TODO: See TODO in __init__
        # TODO: take this from 'validates_up' and 'validates_down',
        #       don't hardcode validators
        if 'validators' in overrides:
            overrides['validators'] = list(overrides['validators'])

        if 'properties' in overrides:
            if not isinstance(overrides['properties'], Properties):
                overrides['properties'] = Properties(overrides['properties'])

        for attribute, value in iteritems(overrides):
            # TODO: must make better
            if callable(value):
                value = staticmethod(value)
            if hasattr(cls, attribute):
                setattr(cls, attribute, value)
                continue
            raise TypeError(
                "%r is an invalid keyword argument: not a known "
                "argument or an overridable class property of %s" % (
                    attribute, cls.__name__))
        return cls
Exemplo n.º 5
0
    def _open(self, bind, kwargs):
        """Return a ``'<partial'`` opener tag with no terminator."""
        contents = kwargs.pop('contents', None)

        if PY2:
            attributes = _unicode_keyed(kwargs)
        else:
            attributes = kwargs
        tagname = self.tagname
        new_contents = transform(
            tagname, attributes, contents, self._context, bind)

        if not new_contents:
            new_contents = u''
        elif hasattr(new_contents, '__html__'):
            new_contents = _unpack(new_contents)
        self.contents = self._markup(new_contents)

        if self._context[u'ordered_attributes']:
            pairs = sorted(attributes.items(), key=_attribute_sort_key)
        else:
            pairs = iteritems(attributes)
        guts = u' '.join(u'%s="%s"' % (k, _attribute_escape(v))
                         for k, v in pairs)
        if guts:
            return u'<' + tagname + u' ' + guts
        else:
            return u'<' + tagname
Exemplo n.º 6
0
 def u(self):
     """A string repr of the element."""
     pairs = ((key, value.u if isinstance(value, Container)
                            else repr(value.u).decode('raw_unicode_escape'))
               for key, value in iteritems(self))
     return u'{%s}' % u', '.join(
         u"%s: %s" % (repr(k).decode('raw_unicode_escape'), v)
         for k, v in pairs)
Exemplo n.º 7
0
 def iteritems(self):
     seen = set()
     for frame in self._frames():
         for key, value in iteritems(frame):
             if key not in seen:
                 seen.add(key)
                 if value is not Deleted:
                     yield (key, value)
Exemplo n.º 8
0
 def slice(self, include=None, omit=None, rename=None, key=None):
     """Return a ``dict`` containing a subset of the element's values."""
     pairs = ((key, element.value)
              for key, element in sorted(iteritems(self)))
     sliced = keyslice_pairs(pairs,
                             include=include,
                             omit=omit,
                             rename=rename,
                             key=key)
     return dict(sliced)
Exemplo n.º 9
0
 def update(self, *dictish, **kwargs):
     """Update with keys from dict-like *\*dictish* and *\*\*kwargs*"""
     if len(dictish) > 1:
         raise TypeError("update expected at most 1 arguments, got %s" %
                         len(dictish))
     elif dictish:
         for key, value in to_pairs(dictish[0]):
             self[key] = value
     for key, value in iteritems(kwargs):
         self[key] = value
Exemplo n.º 10
0
 def update(self, *dictish, **kwargs):
     """Update with keys from dict-like *\*dictish* and *\*\*kwargs*"""
     if len(dictish) > 1:
         raise TypeError(
             "update expected at most 1 arguments, got %s" % len(dictish))
     elif dictish:
         for key, value in to_pairs(dictish[0]):
             self[key] = value
     for key, value in iteritems(kwargs):
         self[key] = value
Exemplo n.º 11
0
 def slice(self, include=None, omit=None, rename=None, key=None):
     """Return a ``dict`` containing a subset of the element's values."""
     pairs = ((key, element.value)
              for key, element in sorted(iteritems(self)))
     sliced = keyslice_pairs(pairs,
                             include=include,
                             omit=omit,
                             rename=rename,
                             key=key)
     return dict(sliced)
Exemplo n.º 12
0
def _rewrite_stream(stream, directives, ctxt, vars, bind):
    stream = list(stream)
    mutable_attrs = {}

    for control_attribute in directives:
        control_attribute.inject(mutable_attrs, ctxt, vars)

    kind, (tagname, attrs), pos = stream[0]
    if len(stream) == 2:
        contents = None
    else:
        contents = _simplify_stream(stream[1:-1], ctxt, vars)

    existing_attributes = {}
    for qname, value in attrs:
        if qname.namespace is None:
            if not isinstance(value, text_type):
                value = _simplify_stream(value, ctxt, vars)
                attrs |= ((qname, value),)
            existing_attributes[qname.localname] = qname
            mutable_attrs[qname.localname] = value

    try:
        render_context = ctxt[u'flatland_render_context']
    except KeyError:
        ctxt[u'flatland_render_context'] = render_context = Context()

    new_contents = transform(tagname.localname, mutable_attrs, contents,
                             render_context, bind)

    if new_contents is None:
        new_contents = ()
    elif isinstance(new_contents, text_type):
        new_contents = [(TEXT, new_contents, (None, -1, -1))]

    pairs = sorted(iteritems(mutable_attrs), key=_attribute_sort_key)
    for attribute_name, value in pairs:
        if attribute_name in existing_attributes:
            qname = existing_attributes.pop(attribute_name)
        else:
            qname = QName(attribute_name)
        attrs |= ((qname, value),)
    for qname in existing_attributes.values():
        attrs -= qname

    stream[0] = (kind, (tagname, attrs), pos)
    if new_contents and tagname.localname == u'select' and bind is not None:
        if tagname.namespace:
            sub_tag = Namespace(tagname.namespace).option
        else:  # pragma: nocover
            sub_tag = QName(u'option')
        new_contents = _bind_unbound_tags(new_contents, sub_tag, bind)
    if new_contents:
        stream[1:-1] = new_contents
    return iter(stream)
Exemplo n.º 13
0
def _rewrite_stream(stream, directives, ctxt, vars, bind):
    stream = list(stream)
    mutable_attrs = {}

    for control_attribute in directives:
        control_attribute.inject(mutable_attrs, ctxt, vars)

    kind, (tagname, attrs), pos = stream[0]
    if len(stream) == 2:
        contents = None
    else:
        contents = _simplify_stream(stream[1:-1], ctxt, vars)

    existing_attributes = {}
    for qname, value in attrs:
        if qname.namespace is None:
            if not isinstance(value, text_type):
                value = _simplify_stream(value, ctxt, vars)
                attrs |= ((qname, value), )
            existing_attributes[qname.localname] = qname
            mutable_attrs[qname.localname] = value

    try:
        render_context = ctxt[u'flatland_render_context']
    except KeyError:
        ctxt[u'flatland_render_context'] = render_context = Context()

    new_contents = transform(tagname.localname, mutable_attrs, contents,
                             render_context, bind)

    if new_contents is None:
        new_contents = ()
    elif isinstance(new_contents, text_type):
        new_contents = [(TEXT, new_contents, (None, -1, -1))]

    pairs = sorted(iteritems(mutable_attrs), key=_attribute_sort_key)
    for attribute_name, value in pairs:
        if attribute_name in existing_attributes:
            qname = existing_attributes.pop(attribute_name)
        else:
            qname = QName(attribute_name)
        attrs |= ((qname, value), )
    for qname in existing_attributes.values():
        attrs -= qname

    stream[0] = (kind, (tagname, attrs), pos)
    if new_contents and tagname.localname == u'select' and bind is not None:
        if tagname.namespace:
            sub_tag = Namespace(tagname.namespace).option
        else:  # pragma: nocover
            sub_tag = QName(u'option')
        new_contents = _bind_unbound_tags(new_contents, sub_tag, bind)
    if new_contents:
        stream[1:-1] = new_contents
    return iter(stream)
Exemplo n.º 14
0
 def iteritems(self):
     seen = set()
     for key, value in iteritems(self.local):
         seen.add(key)
         if value is not Deleted:
             yield key, value
     for key, value in self.class_lookup.iteritems():
         if key not in seen:
             seen.add(key)
             if value is not Deleted:  # pragma: nocover  (coverage bug)
                 yield key, value
Exemplo n.º 15
0
 def update(self, *iterable, **kwargs):
     if len(iterable):
         if len(iterable) > 1:
             raise TypeError("update expected at most 1 arguments, got %s" %
                             (len(iterable)))
         source = to_pairs(iterable[0])
         for key, value in source:
             self[key] = value
     for key, value in iteritems(kwargs):
         if PY2:
             key = key.decode('ascii')
         self[key] = value
Exemplo n.º 16
0
 def update(self, *iterable, **kwargs):
     if len(iterable):
         if len(iterable) > 1:
             raise TypeError(
                 "update expected at most 1 arguments, got %s" % (
                 len(iterable)))
         source = to_pairs(iterable[0])
         for key, value in source:
             self[key] = value
     for key, value in iteritems(kwargs):
         if PY2:
             key = key.decode('ascii')
         self[key] = value
Exemplo n.º 17
0
    def __init__(self, **kw):
        """Construct a validator.

        :param \*\*kw: override any extant class attribute on this instance.

        """
        cls = type(self)
        for attr, value in iteritems(kw):
            if hasattr_py2(cls, attr):
                setattr_py2(self, attr, value)
            else:
                raise TypeError("%s has no attribute %r, can not override." % (
                    cls.__name__, attr))
Exemplo n.º 18
0
    def __init__(self, **kw):
        """Construct a validator.

        :param \*\*kw: override any extant class attribute on this instance.

        """
        cls = type(self)
        for attr, value in iteritems(kw):
            if hasattr_py2(cls, attr):
                setattr_py2(self, attr, value)
            else:
                raise TypeError("%s has no attribute %r, can not override." %
                                (cls.__name__, attr))
Exemplo n.º 19
0
    def update_object(self, obj, include=None, omit=None, rename=None,
                      key=identifier_transform):
        """Update an object's attributes using the element's values.

        Produces a :meth:`slice` using *include*, *omit*, *rename* and
        *key*, and sets the selected attributes on *obj* using
        ``setattr``.

        :returns: nothing. *obj* is modified directly.

        """
        data = self.slice(include=include, omit=omit, rename=rename, key=key)
        for attribute, value in iteritems(data):
            setattr(obj, attribute, value)
Exemplo n.º 20
0
    def update_object(self,
                      obj,
                      include=None,
                      omit=None,
                      rename=None,
                      key=identifier_transform):
        """Update an object's attributes using the element's values.

        Produces a :meth:`slice` using *include*, *omit*, *rename* and
        *key*, and sets the selected attributes on *obj* using
        ``setattr``.

        :returns: nothing. *obj* is modified directly.

        """
        data = self.slice(include=include, omit=omit, rename=rename, key=key)
        for attribute, value in iteritems(data):
            setattr(obj, attribute, value)
Exemplo n.º 21
0
 def value(self):
     """The element as a regular Python dictionary."""
     return dict((key, value.value) for key, value in iteritems(self))
Exemplo n.º 22
0
 def value_dict(element):
     return dict((k, v.value) for k, v in iteritems(element))
Exemplo n.º 23
0
 def value(self):
     """The element as a regular Python dictionary."""
     return dict((key, value.value) for key, value in iteritems(self))