_native.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. """
  3. markupsafe._native
  4. ~~~~~~~~~~~~~~~~~~
  5. Native Python implementation used when the C module is not compiled.
  6. :copyright: © 2010 by the Pallets team.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from . import Markup
  10. from ._compat import text_type
  11. def escape(s):
  12. """Replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in
  13. the string with HTML-safe sequences. Use this if you need to display
  14. text that might contain such characters in HTML.
  15. If the object has an ``__html__`` method, it is called and the
  16. return value is assumed to already be safe for HTML.
  17. :param s: An object to be converted to a string and escaped.
  18. :return: A :class:`Markup` string with the escaped text.
  19. """
  20. if hasattr(s, "__html__"):
  21. return Markup(s.__html__())
  22. return Markup(
  23. text_type(s)
  24. .replace("&", "&amp;")
  25. .replace(">", "&gt;")
  26. .replace("<", "&lt;")
  27. .replace("'", "&#39;")
  28. .replace('"', "&#34;")
  29. )
  30. def escape_silent(s):
  31. """Like :func:`escape` but treats ``None`` as the empty string.
  32. Useful with optional values, as otherwise you get the string
  33. ``'None'`` when the value is ``None``.
  34. >>> escape(None)
  35. Markup('None')
  36. >>> escape_silent(None)
  37. Markup('')
  38. """
  39. if s is None:
  40. return Markup()
  41. return escape(s)
  42. def soft_unicode(s):
  43. """Convert an object to a string if it isn't already. This preserves
  44. a :class:`Markup` string rather than converting it back to a basic
  45. string, so it will still be marked as safe and won't be escaped
  46. again.
  47. >>> value = escape('<User 1>')
  48. >>> value
  49. Markup('&lt;User 1&gt;')
  50. >>> escape(str(value))
  51. Markup('&amp;lt;User 1&amp;gt;')
  52. >>> escape(soft_unicode(value))
  53. Markup('&lt;User 1&gt;')
  54. """
  55. if not isinstance(s, text_type):
  56. s = text_type(s)
  57. return s