openpyxl.descriptors.nested 源代码

from __future__ import absolute_import
# Copyright (c) 2010-2019 openpyxl

"""
Generic serialisable classes
"""
from .base import (
    Convertible,
    Bool,
    Descriptor,
    NoneSet,
    MinMax,
    Set,
    Float,
    Integer,
    String,
    Text,
    )
from .sequence import Sequence
from openpyxl.compat import safe_string
from openpyxl.xml.functions import Element, localname


[文档]class Nested(Descriptor): nested = True attribute = "val" def __set__(self, instance, value): if hasattr(value, "tag"): tag = localname(value) if tag != self.name: raise ValueError("Tag does not match attribute") value = self.from_tree(value) super(Nested, self).__set__(instance, value)
[文档] def from_tree(self, node): return node.get(self.attribute)
[文档] def to_tree(self, tagname=None, value=None, namespace=None): namespace = getattr(self, "namespace", namespace) if value is not None: if namespace is not None: tagname = "{%s}%s" % (namespace, tagname) value = safe_string(value) return Element(tagname, {self.attribute:value})
[文档]class NestedValue(Nested, Convertible): """ Nested tag storing the value on the 'val' attribute """ pass
[文档]class NestedText(NestedValue): """ Represents any nested tag with the value as the contents of the tag """
[文档] def from_tree(self, node): return node.text
[文档] def to_tree(self, tagname=None, value=None, namespace=None): namespace = getattr(self, "namespace", namespace) if value is not None: if namespace is not None: tagname = "{%s}%s" % (namespace, tagname) el = Element(tagname) el.text = safe_string(value) return el
[文档]class NestedFloat(NestedValue, Float): pass
[文档]class NestedInteger(NestedValue, Integer): pass
[文档]class NestedString(NestedValue, String): pass
[文档]class NestedBool(NestedValue, Bool):
[文档] def from_tree(self, node): return node.get("val", True)
[文档]class NestedNoneSet(Nested, NoneSet): pass
[文档]class NestedSet(Nested, Set): pass
[文档]class NestedMinMax(Nested, MinMax): pass
[文档]class EmptyTag(Nested, Bool): """ Boolean if a tag exists or not. """
[文档] def from_tree(self, node): return True
[文档] def to_tree(self, tagname=None, value=None, namespace=None): if value: namespace = getattr(self, "namespace", namespace) if namespace is not None: tagname = "{%s}%s" % (namespace, tagname) return Element(tagname)