__init__.py 924 B

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