1"""
2General functions for HTML manipulation, backported from Py3.
3
4Note that this uses Python 2.7 code with the corresponding Python 3
5module names and locations.
6"""
7
8from __future__ import unicode_literals
9
10
11_escape_map = {ord('&'): '&', ord('<'): '<', ord('>'): '>'}
12_escape_map_full = {ord('&'): '&', ord('<'): '<', ord('>'): '>',
13 ord('"'): '"', ord('\''): '''}
14
15# NB: this is a candidate for a bytes/string polymorphic interface
16
17def escape(s, quote=True):
18 """
19 Replace special characters "&", "<" and ">" to HTML-safe sequences.
20 If the optional flag quote is true (the default), the quotation mark
21 characters, both double quote (") and single quote (') characters are also
22 translated.
23 """
24 assert not isinstance(s, bytes), 'Pass a unicode string'
25 if quote:
26 return s.translate(_escape_map_full)
27 return s.translate(_escape_map)