safestring.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """
  2. Functions for working with "safe strings": strings that can be displayed safely
  3. without further escaping in HTML. Marking something as a "safe string" means
  4. that the producer of the string has already turned characters that should not
  5. be interpreted by the HTML engine (e.g. '<') into the appropriate entities.
  6. """
  7. from django.utils.functional import wraps
  8. class SafeData:
  9. def __html__(self):
  10. """
  11. Return the html representation of a string for interoperability.
  12. This allows other template engines to understand Django's SafeData.
  13. """
  14. return self
  15. class SafeString(str, SafeData):
  16. """
  17. A str subclass that has been specifically marked as "safe" for HTML output
  18. purposes.
  19. """
  20. def __add__(self, rhs):
  21. """
  22. Concatenating a safe string with another safe bytestring or
  23. safe string is safe. Otherwise, the result is no longer safe.
  24. """
  25. t = super().__add__(rhs)
  26. if isinstance(rhs, SafeData):
  27. return SafeString(t)
  28. return t
  29. def __str__(self):
  30. return self
  31. SafeText = SafeString # For backwards compatibility since Django 2.0.
  32. def _safety_decorator(safety_marker, func):
  33. @wraps(func)
  34. def wrapped(*args, **kwargs):
  35. return safety_marker(func(*args, **kwargs))
  36. return wrapped
  37. def mark_safe(s):
  38. """
  39. Explicitly mark a string as safe for (HTML) output purposes. The returned
  40. object can be used everywhere a string is appropriate.
  41. If used on a method as a decorator, mark the returned data as safe.
  42. Can be called multiple times on a single string.
  43. """
  44. if hasattr(s, '__html__'):
  45. return s
  46. if callable(s):
  47. return _safety_decorator(mark_safe, s)
  48. return SafeString(s)