1 | """Utility functions used by various web helpers""" |
---|
2 | import cgi |
---|
3 | from xml.sax.saxutils import XMLGenerator |
---|
4 | |
---|
5 | def html_escape(s): |
---|
6 | """HTML-escape a string or object |
---|
7 | |
---|
8 | This converts any non-string objects passed into it to strings |
---|
9 | (actually, using ``unicode()``). All values returned are |
---|
10 | non-unicode strings (using ``&#num;`` entities for all non-ASCII |
---|
11 | characters). |
---|
12 | |
---|
13 | None is treated specially, and returns the empty string. |
---|
14 | """ |
---|
15 | if s is None: |
---|
16 | return '' |
---|
17 | if not isinstance(s, basestring): |
---|
18 | if hasattr(s, '__unicode__'): |
---|
19 | s = unicode(s) |
---|
20 | else: |
---|
21 | s = str(s) |
---|
22 | s = cgi.escape(s, True) |
---|
23 | if isinstance(s, unicode): |
---|
24 | s = s.encode('ascii', 'xmlcharrefreplace') |
---|
25 | return s |
---|
26 | |
---|
27 | class Partial(object): |
---|
28 | """partial object, which will be in Python 2.5""" |
---|
29 | def __init__(*args, **kw): |
---|
30 | self = args[0] |
---|
31 | self.fn, self.args, self.kw = (args[1], args[2:], kw) |
---|
32 | |
---|
33 | def __call__(self, *args, **kw): |
---|
34 | if kw and self.kw: |
---|
35 | d = self.kw.copy() |
---|
36 | d.update(kw) |
---|
37 | else: |
---|
38 | d = kw or self.kw |
---|
39 | return self.fn(*(self.args + args), **d) |
---|
40 | |
---|
41 | class SimplerXMLGenerator(XMLGenerator): |
---|
42 | def addQuickElement(self, name, contents=None, attrs={}): |
---|
43 | """Convenience method for adding an element with no children""" |
---|
44 | self.startElement(name, attrs) |
---|
45 | if contents is not None: |
---|
46 | self.characters(contents) |
---|
47 | self.endElement(name) |
---|