Statistics
| Branch: | Tag: | Revision:

root / ncclient / content.py @ 0b7d3b31

History | View | Annotate | Download (6.8 kB)

1
# Copyright 2009 Shikhar Bhushan
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#    http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14

    
15

    
16
"""The :mod:`content` module provides methods for creating XML documents, parsing XML, and converting between different XML representations. It uses :mod:`~xml.etree.ElementTree` internally.
17
"""
18

    
19
from cStringIO import StringIO
20
from xml.etree import cElementTree as ET
21

    
22
from ncclient import NCClientError
23

    
24
class ContentError(NCClientError):
25
    "Raised by methods of the :mod:`content` module in case of an error."
26
    pass
27

    
28
### Namespace-related
29

    
30
#: Base NETCONf namespace
31
BASE_NS = 'urn:ietf:params:xml:ns:netconf:base:1.0'
32
#: ... and this is BASE_NS according to Cisco devices tested
33
CISCO_BS = 'urn:ietf:params:netconf:base:1.0'
34

    
35
try:
36
    register_namespace = ET.register_namespace
37
except AttributeError:
38
    def register_namespace(prefix, uri):
39
        from xml.etree import ElementTree
40
        # cElementTree uses ElementTree's _namespace_map, so that's ok
41
        ElementTree._namespace_map[uri] = prefix
42

    
43
# we'd like BASE_NS to be prefixed as "netconf"
44
register_namespace('netconf', BASE_NS)
45

    
46
qualify = lambda tag, ns=BASE_NS: tag if ns is None else '{%s}%s' % (ns, tag)
47

    
48
# deprecated
49
multiqualify = lambda tag, nslist=(BASE_NS, CISCO_BS): [qualify(tag, ns) for ns in nslist]
50

    
51
unqualify = lambda tag: tag[tag.rfind('}')+1:]
52

    
53
### XML with Python data structures
54

    
55
class DictTree:
56

    
57
    @staticmethod
58
    def Element(spec):
59
        """DictTree -> Element
60

61
        :type spec: :obj:`dict` or :obj:`string` or :class:`~xml.etree.ElementTree.Element`
62

63
        :rtype: :class:`~xml.etree.ElementTree.Element`
64
        """
65
        if iselement(spec):
66
            return spec
67
        elif isinstance(spec, basestring):
68
            return XML.Element(spec)
69
        if not isinstance(spec, dict):
70
            raise ContentError("Invalid tree spec")
71
        if 'tag' in spec:
72
            ele = ET.Element(spec.get('tag'), spec.get('attrib', {}))
73
            ele.text = spec.get('text', '')
74
            ele.tail = spec.get('tail', '')
75
            subtree = spec.get('subtree', [])
76
            # might not be properly specified as list but may be dict
77
            if not isinstance(subtree, list):
78
                subtree = [subtree]
79
            for subele in subtree:
80
                ele.append(DictTree.Element(subele))
81
            return ele
82
        elif 'comment' in spec:
83
            return ET.Comment(spec.get('comment'))
84
        else:
85
            raise ContentError('Invalid tree spec')
86

    
87
    @staticmethod
88
    def XML(spec, encoding='UTF-8'):
89
        """DictTree -> XML
90

91
        :type spec: :obj:`dict` or :obj:`string` or :class:`~xml.etree.ElementTree.Element`
92

93
        :arg encoding: chraracter encoding
94

95
        :rtype: string
96
        """
97
        return Element.XML(DictTree.Element(spec), encoding)
98

    
99
class Element:
100

    
101
    @staticmethod
102
    def DictTree(ele):
103
        """DictTree -> Element
104

105
        :type spec: :class:`~xml.etree.ElementTree.Element`
106
        :rtype: :obj:`dict`
107
        """
108
        return {
109
            'tag': ele.tag,
110
            'attributes': ele.attrib,
111
            'text': ele.text,
112
            'tail': ele.tail,
113
            'subtree': [ Element.DictTree(child) for child in root.getchildren() ]
114
        }
115

    
116
    @staticmethod
117
    def XML(ele, encoding='UTF-8'):
118
        """Element -> XML
119

120
        :type spec: :class:`~xml.etree.ElementTree.Element`
121
        :arg encoding: character encoding
122
        :rtype: :obj:`string`
123
        """
124
        xml = ET.tostring(ele, encoding)
125
        if xml.startswith('<?xml'):
126
            return xml
127
        else:
128
            return '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml)
129

    
130
class XML:
131

    
132
    @staticmethod
133
    def DictTree(xml):
134
        """XML -> DictTree
135

136
        :type spec: :obj:`string`
137
        :rtype: :obj:`dict`
138
        """
139
        return Element.DictTree(XML.Element(xml))
140

    
141
    @staticmethod
142
    def Element(xml):
143
        """XML -> Element
144

145
        :type xml: :obj:`string`
146
        :rtype: :class:`~xml.etree.ElementTree.Element`
147
        """
148
        return ET.fromstring(xml)
149

    
150
dtree2ele = DictTree.Element
151
dtree2xml = DictTree.XML
152
ele2dtree = Element.DictTree
153
ele2xml = Element.XML
154
xml2dtree = XML.DictTree
155
xml2ele = XML.Element
156

    
157
### Other utility functions
158

    
159
iselement = ET.iselement
160

    
161
def find(ele, tag, nslist=[]):
162
    """If *nslist* is empty, same as :meth:`xml.etree.ElementTree.Element.find`. If it is not, *tag* is interpreted as an unqualified name and qualified using each item in *nslist* (with a :const:`None` item in *nslit* meaning no qualification is done). The first match is returned.
163

164
    :arg nslist: optional list of namespaces
165
    :type nslit: `string` `list`
166
    """
167
    if nslist:
168
        for qname in multiqualify(tag):
169
            found = ele.find(qname)
170
            if found is not None:
171
                return found
172
    else:
173
        return ele.find(tag)
174

    
175
def parse_root(raw):
176
    """Efficiently parses the root element of an XML document.
177

178
    :arg raw: XML document
179
    :type raw: string
180
    :returns: a tuple of `(tag, attributes)`, where `tag` is the (qualified) name of the element and `attributes` is a dictionary of its attributes.
181
    :rtype: `tuple`
182
    """
183
    fp = StringIO(raw[:1024]) # this is a guess but start element beyond 1024 bytes would be a bit absurd
184
    for event, element in ET.iterparse(fp, events=('start',)):
185
        return (element.tag, element.attrib)
186

    
187
def validated_element(rep, tags=None, attrs=None, text=None):
188
    """Checks if the root element meets the supplied criteria. Returns a :class:`~xml.etree.ElementTree.Element` instance if so, otherwise raises :exc:`ContentError`.
189

190
    :arg tags: tag name or a list of allowable tag names
191
    :arg attrs: list of required attribute names, each item may be a list of allowable alternatives
192
    :arg text: textual content to match
193
    :type rep: :obj:`dict` or :obj:`string` or :class:`~xml.etree.ElementTree.Element`
194
    """
195
    ele = dtree2ele(rep)
196
    err = False
197
    if tags:
198
        if isinstance(tags, basestring):
199
            tags = [tags]
200
        if ele.tag not in tags:
201
            err = True
202
    if attrs:
203
        for req in attrs:
204
            if isinstance(req, basestring): req = [req]
205
            for alt in req:
206
                if alt in ele.attrib:
207
                    break
208
            else:
209
                err = True
210
    if text and ele.text != text:
211
        err = True
212
    if err:
213
        raise ContentError("Element [%s] does not meet requirements" % ele.tag)
214
    return ele