Added DCMeta - EAV based application to represent document meta-data. Started to...
[redakcja.git] / apps / dcmeta / utils.py
1 class XMLNamespace(object):
2     '''A handy structure to represent names in an XML namespace.'''
3
4     def __init__(self, uri):
5         self.uri = uri
6
7     def __call__(self, tag):
8         return '{%s}%s' % (self.uri, tag)
9
10     def __contains__(self, tag):
11         return tag.startswith('{' + self.uri + '}')
12
13     def __repr__(self):
14         return 'XMLNamespace(%r)' % self.uri
15
16     def __str__(self):
17         return '%s' % self.uri
18
19     def strip(self, qtag):
20         if qtag not in self:
21             raise ValueError("Tag %s not in namespace %s" % (qtag, self.uri))
22         return qtag[len(self.uri) + 2:]
23
24     @classmethod
25     def split_tag(cls, tag):
26         if '{' != tag[0]:
27             raise ValueError
28         end = tag.find('}')
29         if end < 0:
30             raise ValueError
31         return cls(tag[1:end]), tag[end + 1:]
32
33     @classmethod
34     def tagname(cls, tag):
35         return cls.split_tag(tag)[1]
36
37
38 class EmptyNamespace(XMLNamespace):
39     def __init__(self):
40         super(EmptyNamespace, self).__init__('')
41
42     def __call__(self, tag):
43         return tag
44
45 # some common namespaces we use
46 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
47 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
48 MARCRELNS = XMLNamespace('http://www.loc.gov/loc.terms/relators/')
49
50 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
51 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
52
53 common_uris = {
54     RDFNS.uri: 'rdf',
55     DCNS.uri: 'dc',
56     MARCRELNS.uri: 'marcrel',
57 }
58
59 common_prefixes = dict((i[1], i[0]) for i in common_uris.items())
60
61 class NamespaceProxy(object):
62
63     def __init__(self, desc, uri):
64         object.__setattr__(self, 'uri', uri)
65         object.__setattr__(self, 'desc', desc)
66
67     def __getattr__(self, key):
68         return object.__getattribute__(self, 'desc')[self.uri, key]
69
70     def __setattr__(self, key, value):
71         object.__getattribute__(self, 'desc')[self.uri, key] = value
72
73     def __iter__(self):
74         return ((XMLNamespace.tagname(attr.schema.name), attr.value) for attr in object.__getattribute__(self, 'desc').attrs.filter(schema__name__startswith="{%s}" % self.uri))
75
76 class NamespaceDescriptor(object):
77
78     def __init__(self, nsuri):
79         self.nsuri = nsuri
80
81     def __get__(self, instance, owner):
82         if instance is None:
83             return self
84         return NamespaceProxy(instance, self.nsuri)
85
86     def __set__(self, instance, value):
87         raise ValueError
88
89
90