__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. from __future__ import annotations
  2. import collections.abc as cabc
  3. import string
  4. import typing as t
  5. try:
  6. from ._speedups import _escape_inner
  7. except ImportError:
  8. from ._native import _escape_inner
  9. if t.TYPE_CHECKING:
  10. import typing_extensions as te
  11. class _HasHTML(t.Protocol):
  12. def __html__(self, /) -> str: ...
  13. class _TPEscape(t.Protocol):
  14. def __call__(self, s: t.Any, /) -> Markup: ...
  15. def escape(s: t.Any, /) -> Markup:
  16. """Replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in
  17. the string with HTML-safe sequences. Use this if you need to display
  18. text that might contain such characters in HTML.
  19. If the object has an ``__html__`` method, it is called and the
  20. return value is assumed to already be safe for HTML.
  21. :param s: An object to be converted to a string and escaped.
  22. :return: A :class:`Markup` string with the escaped text.
  23. """
  24. # If the object is already a plain string, skip __html__ check and string
  25. # conversion. This is the most common use case.
  26. # Use type(s) instead of s.__class__ because a proxy object may be reporting
  27. # the __class__ of the proxied value.
  28. if type(s) is str:
  29. return Markup(_escape_inner(s))
  30. if hasattr(s, "__html__"):
  31. return Markup(s.__html__())
  32. return Markup(_escape_inner(str(s)))
  33. def escape_silent(s: t.Any | None, /) -> Markup:
  34. """Like :func:`escape` but treats ``None`` as the empty string.
  35. Useful with optional values, as otherwise you get the string
  36. ``'None'`` when the value is ``None``.
  37. >>> escape(None)
  38. Markup('None')
  39. >>> escape_silent(None)
  40. Markup('')
  41. """
  42. if s is None:
  43. return Markup()
  44. return escape(s)
  45. def soft_str(s: t.Any, /) -> str:
  46. """Convert an object to a string if it isn't already. This preserves
  47. a :class:`Markup` string rather than converting it back to a basic
  48. string, so it will still be marked as safe and won't be escaped
  49. again.
  50. >>> value = escape("<User 1>")
  51. >>> value
  52. Markup('&lt;User 1&gt;')
  53. >>> escape(str(value))
  54. Markup('&amp;lt;User 1&amp;gt;')
  55. >>> escape(soft_str(value))
  56. Markup('&lt;User 1&gt;')
  57. """
  58. if not isinstance(s, str):
  59. return str(s)
  60. return s
  61. class Markup(str):
  62. """A string that is ready to be safely inserted into an HTML or XML
  63. document, either because it was escaped or because it was marked
  64. safe.
  65. Passing an object to the constructor converts it to text and wraps
  66. it to mark it safe without escaping. To escape the text, use the
  67. :meth:`escape` class method instead.
  68. >>> Markup("Hello, <em>World</em>!")
  69. Markup('Hello, <em>World</em>!')
  70. >>> Markup(42)
  71. Markup('42')
  72. >>> Markup.escape("Hello, <em>World</em>!")
  73. Markup('Hello &lt;em&gt;World&lt;/em&gt;!')
  74. This implements the ``__html__()`` interface that some frameworks
  75. use. Passing an object that implements ``__html__()`` will wrap the
  76. output of that method, marking it safe.
  77. >>> class Foo:
  78. ... def __html__(self):
  79. ... return '<a href="/foo">foo</a>'
  80. ...
  81. >>> Markup(Foo())
  82. Markup('<a href="/foo">foo</a>')
  83. This is a subclass of :class:`str`. It has the same methods, but
  84. escapes their arguments and returns a ``Markup`` instance.
  85. >>> Markup("<em>%s</em>") % ("foo & bar",)
  86. Markup('<em>foo &amp; bar</em>')
  87. >>> Markup("<em>Hello</em> ") + "<foo>"
  88. Markup('<em>Hello</em> &lt;foo&gt;')
  89. """
  90. __slots__ = ()
  91. def __new__(
  92. cls, object: t.Any = "", encoding: str | None = None, errors: str = "strict"
  93. ) -> te.Self:
  94. if hasattr(object, "__html__"):
  95. object = object.__html__()
  96. if encoding is None:
  97. return super().__new__(cls, object)
  98. return super().__new__(cls, object, encoding, errors)
  99. def __html__(self, /) -> te.Self:
  100. return self
  101. def __add__(self, value: str | _HasHTML, /) -> te.Self:
  102. if isinstance(value, str) or hasattr(value, "__html__"):
  103. return self.__class__(super().__add__(self.escape(value)))
  104. return NotImplemented
  105. def __radd__(self, value: str | _HasHTML, /) -> te.Self:
  106. if isinstance(value, str) or hasattr(value, "__html__"):
  107. return self.escape(value).__add__(self)
  108. return NotImplemented
  109. def __mul__(self, value: t.SupportsIndex, /) -> te.Self:
  110. return self.__class__(super().__mul__(value))
  111. def __rmul__(self, value: t.SupportsIndex, /) -> te.Self:
  112. return self.__class__(super().__mul__(value))
  113. def __mod__(self, value: t.Any, /) -> te.Self:
  114. if isinstance(value, tuple):
  115. # a tuple of arguments, each wrapped
  116. value = tuple(_MarkupEscapeHelper(x, self.escape) for x in value)
  117. elif hasattr(type(value), "__getitem__") and not isinstance(value, str):
  118. # a mapping of arguments, wrapped
  119. value = _MarkupEscapeHelper(value, self.escape)
  120. else:
  121. # a single argument, wrapped with the helper and a tuple
  122. value = (_MarkupEscapeHelper(value, self.escape),)
  123. return self.__class__(super().__mod__(value))
  124. def __repr__(self, /) -> str:
  125. return f"{self.__class__.__name__}({super().__repr__()})"
  126. def join(self, iterable: cabc.Iterable[str | _HasHTML], /) -> te.Self:
  127. return self.__class__(super().join(map(self.escape, iterable)))
  128. def split( # type: ignore[override]
  129. self, /, sep: str | None = None, maxsplit: t.SupportsIndex = -1
  130. ) -> list[te.Self]:
  131. return [self.__class__(v) for v in super().split(sep, maxsplit)]
  132. def rsplit( # type: ignore[override]
  133. self, /, sep: str | None = None, maxsplit: t.SupportsIndex = -1
  134. ) -> list[te.Self]:
  135. return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
  136. def splitlines( # type: ignore[override]
  137. self, /, keepends: bool = False
  138. ) -> list[te.Self]:
  139. return [self.__class__(v) for v in super().splitlines(keepends)]
  140. def unescape(self, /) -> str:
  141. """Convert escaped markup back into a text string. This replaces
  142. HTML entities with the characters they represent.
  143. >>> Markup("Main &raquo; <em>About</em>").unescape()
  144. 'Main » <em>About</em>'
  145. """
  146. from html import unescape
  147. return unescape(str(self))
  148. def striptags(self, /) -> str:
  149. """:meth:`unescape` the markup, remove tags, and normalize
  150. whitespace to single spaces.
  151. >>> Markup("Main &raquo;\t<em>About</em>").striptags()
  152. 'Main » About'
  153. """
  154. value = str(self)
  155. parts = []
  156. pos = 0
  157. while (start := value.find("<", pos)) != -1:
  158. if value.startswith("<!--", start):
  159. # comment
  160. if (end := value.find("-->", start + 4)) == -1:
  161. # unclosed
  162. break
  163. end += 3
  164. else:
  165. # tag
  166. if (end := value.find(">", start)) == -1:
  167. # unclosed
  168. break
  169. end += 1
  170. parts.append(value[pos:start])
  171. pos = end
  172. # found at least one tag, combine parts
  173. if pos > 0:
  174. # any trailing data after the last closed tag
  175. parts.append(value[pos:])
  176. value = "".join(parts)
  177. # collapse spaces
  178. value = " ".join(value.split())
  179. # unescape the processed value using the current class
  180. return self.__class__(value).unescape()
  181. @classmethod
  182. def escape(cls, s: t.Any, /) -> te.Self:
  183. """Escape a string. Calls :func:`escape` and ensures that for
  184. subclasses the correct type is returned.
  185. """
  186. rv = escape(s)
  187. if rv.__class__ is not cls:
  188. return cls(rv)
  189. return rv
  190. def __getitem__(self, key: t.SupportsIndex | slice, /) -> te.Self:
  191. return self.__class__(super().__getitem__(key))
  192. def capitalize(self, /) -> te.Self:
  193. return self.__class__(super().capitalize())
  194. def title(self, /) -> te.Self:
  195. return self.__class__(super().title())
  196. def lower(self, /) -> te.Self:
  197. return self.__class__(super().lower())
  198. def upper(self, /) -> te.Self:
  199. return self.__class__(super().upper())
  200. def replace(self, old: str, new: str, count: t.SupportsIndex = -1, /) -> te.Self:
  201. return self.__class__(super().replace(old, self.escape(new), count))
  202. def ljust(self, width: t.SupportsIndex, fillchar: str = " ", /) -> te.Self:
  203. return self.__class__(super().ljust(width, self.escape(fillchar)))
  204. def rjust(self, width: t.SupportsIndex, fillchar: str = " ", /) -> te.Self:
  205. return self.__class__(super().rjust(width, self.escape(fillchar)))
  206. def lstrip(self, chars: str | None = None, /) -> te.Self:
  207. return self.__class__(super().lstrip(chars))
  208. def rstrip(self, chars: str | None = None, /) -> te.Self:
  209. return self.__class__(super().rstrip(chars))
  210. def center(self, width: t.SupportsIndex, fillchar: str = " ", /) -> te.Self:
  211. return self.__class__(super().center(width, self.escape(fillchar)))
  212. def strip(self, chars: str | None = None, /) -> te.Self:
  213. return self.__class__(super().strip(chars))
  214. def translate(
  215. self,
  216. table: cabc.Mapping[int, str | int | None], # type: ignore[override]
  217. /,
  218. ) -> str:
  219. return self.__class__(super().translate(table))
  220. def expandtabs(self, /, tabsize: t.SupportsIndex = 8) -> te.Self:
  221. return self.__class__(super().expandtabs(tabsize))
  222. def swapcase(self, /) -> te.Self:
  223. return self.__class__(super().swapcase())
  224. def zfill(self, width: t.SupportsIndex, /) -> te.Self:
  225. return self.__class__(super().zfill(width))
  226. def casefold(self, /) -> te.Self:
  227. return self.__class__(super().casefold())
  228. def removeprefix(self, prefix: str, /) -> te.Self:
  229. return self.__class__(super().removeprefix(prefix))
  230. def removesuffix(self, suffix: str) -> te.Self:
  231. return self.__class__(super().removesuffix(suffix))
  232. def partition(self, sep: str, /) -> tuple[te.Self, te.Self, te.Self]:
  233. left, sep, right = super().partition(sep)
  234. cls = self.__class__
  235. return cls(left), cls(sep), cls(right)
  236. def rpartition(self, sep: str, /) -> tuple[te.Self, te.Self, te.Self]:
  237. left, sep, right = super().rpartition(sep)
  238. cls = self.__class__
  239. return cls(left), cls(sep), cls(right)
  240. def format(self, *args: t.Any, **kwargs: t.Any) -> te.Self:
  241. formatter = EscapeFormatter(self.escape)
  242. return self.__class__(formatter.vformat(self, args, kwargs))
  243. def format_map(
  244. self,
  245. mapping: cabc.Mapping[str, t.Any], # type: ignore[override]
  246. /,
  247. ) -> te.Self:
  248. formatter = EscapeFormatter(self.escape)
  249. return self.__class__(formatter.vformat(self, (), mapping))
  250. def __html_format__(self, format_spec: str, /) -> te.Self:
  251. if format_spec:
  252. raise ValueError("Unsupported format specification for Markup.")
  253. return self
  254. class EscapeFormatter(string.Formatter):
  255. __slots__ = ("escape",)
  256. def __init__(self, escape: _TPEscape) -> None:
  257. self.escape: _TPEscape = escape
  258. super().__init__()
  259. def format_field(self, value: t.Any, format_spec: str) -> str:
  260. if hasattr(value, "__html_format__"):
  261. rv = value.__html_format__(format_spec)
  262. elif hasattr(value, "__html__"):
  263. if format_spec:
  264. raise ValueError(
  265. f"Format specifier {format_spec} given, but {type(value)} does not"
  266. " define __html_format__. A class that defines __html__ must define"
  267. " __html_format__ to work with format specifiers."
  268. )
  269. rv = value.__html__()
  270. else:
  271. # We need to make sure the format spec is str here as
  272. # otherwise the wrong callback methods are invoked.
  273. rv = super().format_field(value, str(format_spec))
  274. return str(self.escape(rv))
  275. class _MarkupEscapeHelper:
  276. """Helper for :meth:`Markup.__mod__`."""
  277. __slots__ = ("obj", "escape")
  278. def __init__(self, obj: t.Any, escape: _TPEscape) -> None:
  279. self.obj: t.Any = obj
  280. self.escape: _TPEscape = escape
  281. def __getitem__(self, key: t.Any, /) -> te.Self:
  282. return self.__class__(self.obj[key], self.escape)
  283. def __str__(self, /) -> str:
  284. return str(self.escape(self.obj))
  285. def __repr__(self, /) -> str:
  286. return str(self.escape(repr(self.obj)))
  287. def __int__(self, /) -> int:
  288. return int(self.obj)
  289. def __float__(self, /) -> float:
  290. return float(self.obj)
  291. def __getattr__(name: str) -> t.Any:
  292. if name == "__version__":
  293. import importlib.metadata
  294. import warnings
  295. warnings.warn(
  296. "The '__version__' attribute is deprecated and will be removed in"
  297. " MarkupSafe 3.1. Use feature detection, or"
  298. ' `importlib.metadata.version("markupsafe")`, instead.',
  299. DeprecationWarning,
  300. stacklevel=2,
  301. )
  302. return importlib.metadata.version("markupsafe")
  303. raise AttributeError(name)