_native.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # -*- coding: utf-8 -*-
  2. """
  3. markupsafe._native
  4. ~~~~~~~~~~~~~~~~~~
  5. Native Python implementation the C module is not compiled.
  6. :copyright: (c) 2010 by Armin Ronacher.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from markupsafe import Markup
  10. from markupsafe._compat import text_type
  11. def escape(s):
  12. """Convert the characters &, <, >, ' and " in string s to HTML-safe
  13. sequences. Use this if you need to display text that might contain
  14. such characters in HTML. Marks return value as markup string.
  15. """
  16. if hasattr(s, '__html__'):
  17. return s.__html__()
  18. return Markup(text_type(s)
  19. .replace('&', '&amp;')
  20. .replace('>', '&gt;')
  21. .replace('<', '&lt;')
  22. .replace("'", '&#39;')
  23. .replace('"', '&#34;')
  24. )
  25. def escape_silent(s):
  26. """Like :func:`escape` but converts `None` into an empty
  27. markup string.
  28. """
  29. if s is None:
  30. return Markup()
  31. return escape(s)
  32. def soft_unicode(s):
  33. """Make a string unicode if it isn't already. That way a markup
  34. string is not converted back to unicode.
  35. """
  36. if not isinstance(s, text_type):
  37. s = text_type(s)
  38. return s