1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 """
18 ========================
19 Output Encoder Classes
20 ========================
21
22 This module provides output encoding logic.
23 """
24 __author__ = u"Andr\xe9 Malo"
25 __docformat__ = "restructuredtext en"
26
27 from tdi import interfaces as _interfaces
28
29
30 -class TextEncoder(object):
31 """ Encoder for text output """
32 __implements__ = [_interfaces.EncoderInterface]
33
34 - def __init__(self, encoding):
35 """
36 Initialization
37
38 :Parameters:
39 `encoding` : ``str``
40 The target encoding
41 """
42 self.encoding = encoding
43
44 - def starttag(self, name, attr, closed):
45 """ :See: `EncoderInterface` """
46 return (closed and "[[%s]]" or "[%s]") % (' '.join([name] + [
47 value is not None and "%s=%s" % (key, value) or key
48 for key, value in attr
49 ]))
50
51 - def endtag(self, name):
52 """ :See: `EncoderInterface` """
53 return "[/%s]" % name
54
55 - def name(self, name):
56 """ :See: `EncoderInterface` """
57 if isinstance(name, unicode):
58 return name.encode(self.encoding, 'strict')
59 return name
60
61 - def attribute(self, value):
62 """ :See: `EncoderInterface` """
63 if isinstance(value, unicode):
64 value = (value
65 .replace(u'"', u'\\"')
66 .encode(self.encoding, 'strict')
67 )
68 else:
69 value = value.replace('"', '\\"')
70 return '"%s"' % value
71
72 - def content(self, value):
73 """ :See: `EncoderInterface` """
74 if isinstance(value, unicode):
75 return (value
76 .encode(self.encoding, 'strict')
77 )
78 return value
79
80 - def encode(self, value):
81 """ :See: `EncoderInterface` """
82 return value.encode(self.encoding, 'strict')
83
84 - def escape(self, value):
85 """ :See: `EncoderInterface` """
86 return value.replace('[', '[]')
87
88
89 from tdi import c
90 c = c.load('impl')
91 if c is not None:
92 TextEncoder = c.TextEncoder
93 del c
94