Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

safestring.py 1.8KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 functools import wraps
  8. from django.utils.functional import keep_lazy
  9. class SafeData:
  10. __slots__ = ()
  11. def __html__(self):
  12. """
  13. Return the html representation of a string for interoperability.
  14. This allows other template engines to understand Django's SafeData.
  15. """
  16. return self
  17. class SafeString(str, SafeData):
  18. """
  19. A str subclass that has been specifically marked as "safe" for HTML output
  20. purposes.
  21. """
  22. __slots__ = ()
  23. def __add__(self, rhs):
  24. """
  25. Concatenating a safe string with another safe bytestring or
  26. safe string is safe. Otherwise, the result is no longer safe.
  27. """
  28. t = super().__add__(rhs)
  29. if isinstance(rhs, SafeData):
  30. return SafeString(t)
  31. return t
  32. def __str__(self):
  33. return self
  34. SafeText = SafeString # For backwards compatibility since Django 2.0.
  35. def _safety_decorator(safety_marker, func):
  36. @wraps(func)
  37. def wrapped(*args, **kwargs):
  38. return safety_marker(func(*args, **kwargs))
  39. return wrapped
  40. @keep_lazy(SafeString)
  41. def mark_safe(s):
  42. """
  43. Explicitly mark a string as safe for (HTML) output purposes. The returned
  44. object can be used everywhere a string is appropriate.
  45. If used on a method as a decorator, mark the returned data as safe.
  46. Can be called multiple times on a single string.
  47. """
  48. if hasattr(s, "__html__"):
  49. return s
  50. if callable(s):
  51. return _safety_decorator(mark_safe, s)
  52. return SafeString(s)