-
Notifications
You must be signed in to change notification settings - Fork 421
/
namespace.py
37 lines (27 loc) · 971 Bytes
/
namespace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import re
from defusedxml.ElementTree import fromstring
OLD_NAMESPACE = "http://tableausoftware.com/api"
NEW_NAMESPACE = "http://tableau.com/api"
NAMESPACE_RE = re.compile(r"\{(.*?)\}")
class UnknownNamespaceError(Exception):
pass
class Namespace(object):
def __init__(self):
self._namespace = {"t": NEW_NAMESPACE}
self._detected = False
def __call__(self):
return self._namespace
def detect(self, xml):
if self._detected:
return
if not xml.startswith(b"<?xml"):
return # Not an xml file, don't detect anything
root = fromstring(xml)
matches = NAMESPACE_RE.match(root.tag)
if matches:
detected_ns = matches.group(1)
if detected_ns in (OLD_NAMESPACE, NEW_NAMESPACE):
self._namespace = {"t": detected_ns}
self._detected = True
else:
raise UnknownNamespaceError(detected_ns)