Statistics
| Branch: | Tag: | Revision:

root / ncclient / content.py @ c2a5b930

History | View | Annotate | Download (3.9 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
"TODO: docstring"
16

    
17
from xml.etree import cElementTree as ET
18

    
19
iselement = ET.iselement
20
element2string = ET.tostring
21

    
22
### Namespace-related ###
23

    
24
BASE_NS = 'urn:ietf:params:xml:ns:netconf:base:1.0'
25
# and this is BASE_NS according to cisco devices...
26
CISCO_BS = 'urn:ietf:params:netconf:base:1.0'
27

    
28
try:
29
    register_namespace = ET.register_namespace
30
except AttributeError:
31
    def register_namespace(prefix, uri):
32
        from xml.etree import ElementTree
33
        # cElementTree uses ElementTree's _namespace_map, so that's ok
34
        ElementTree._namespace_map[uri] = prefix
35

    
36
# we'd like BASE_NS to be prefixed as "netconf"
37
register_namespace('netconf', BASE_NS)
38

    
39
qualify = lambda tag, ns=BASE_NS: '{%s}%s' % (ns, tag)
40

    
41
# i would have written a def if lambdas weren't so much fun
42
multiqualify = lambda tag, nslist=(BASE_NS, CISCO_BS): [qualify(tag, ns)
43
                                                        for ns in nslist]
44

    
45
unqualify = lambda tag: tag[tag.rfind('}')+1:]
46

    
47
def namespaced_find(ele, tag, workaround=True):
48
    """`workaround` is for Cisco implementations (at least the one tested), 
49
    which uses an incorrect namespace.
50
    """
51
    found = None
52
    if not workaround:
53
        found = ele.find(tag)
54
    else:
55
        for qname in multiqualify(tag):
56
            found = ele.find(qname)
57
            if found is not None:
58
                break
59
    return found
60
    
61

    
62
### Build XML using Python data structures ###
63

    
64
class XMLConverter:
65
    """Build an ElementTree.Element instance from an XML tree specification
66
    based on nested dictionaries. TODO: describe spec
67
    """
68
    
69
    def __init__(self, spec):
70
        "TODO: docstring"
71
        self._root = XMLConverter.build(spec)
72
    
73
    def to_string(self, encoding='utf-8'):
74
        "TODO: docstring"
75
        xml = ET.tostring(self._root, encoding)
76
        # some etree versions don't include xml decl with utf-8
77
        # this is a problem with some devices
78
        return (xml if xml.startswith('<?xml')
79
                else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml))
80
    
81
    @property
82
    def tree(self):
83
        "TODO: docstring"
84
        return self._root
85
    
86
    @staticmethod
87
    def build(spec):
88
        "TODO: docstring"
89
        if iselement(spec):
90
            return spec
91
        elif isinstance(spec, basestring):
92
            return ET.XML(spec)
93
        ## assume isinstance(spec, dict)
94
        if 'tag' in spec:
95
            ele = ET.Element(spec.get('tag'), spec.get('attributes', {}))
96
            ele.text = spec.get('text', '')
97
            ele.tail = spec.get('tail', '')
98
            subtree = spec.get('subtree', [])
99
            # might not be properly specified as list but may be dict
100
            if isinstance(subtree, dict):
101
                subtree = [subtree]
102
            for subele in subtree:
103
                ele.append(XMLConverter.build(subele))
104
            return ele
105
        elif 'comment' in spec:
106
            return ET.Comment(spec.get('comment'))
107
        else:
108
            raise ContentError('Invalid tree spec')
109
    
110
    @staticmethod
111
    def from_string(xml):
112
        return XMLConverter.parse(ET.fromstring(xml))
113
    
114
    @staticmethod
115
    def parse(root):
116
        return {
117
            'tag': root.tag,
118
            'attributes': root.attrib,
119
            'text': root.text,
120
            'tail': root.tail,
121
            'subtree': [ XMLConverter.parse(child) for child in root.getchildren() ]
122
        }