utils.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. import enum
  2. import json
  3. import os
  4. import re
  5. import typing as t
  6. import warnings
  7. from collections import abc
  8. from collections import deque
  9. from random import choice
  10. from random import randrange
  11. from threading import Lock
  12. from types import CodeType
  13. from urllib.parse import quote_from_bytes
  14. import markupsafe
  15. if t.TYPE_CHECKING:
  16. import typing_extensions as te
  17. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  18. # special singleton representing missing values for the runtime
  19. missing: t.Any = type("MissingType", (), {"__repr__": lambda x: "missing"})()
  20. internal_code: t.MutableSet[CodeType] = set()
  21. concat = "".join
  22. def pass_context(f: F) -> F:
  23. """Pass the :class:`~jinja2.runtime.Context` as the first argument
  24. to the decorated function when called while rendering a template.
  25. Can be used on functions, filters, and tests.
  26. If only ``Context.eval_context`` is needed, use
  27. :func:`pass_eval_context`. If only ``Context.environment`` is
  28. needed, use :func:`pass_environment`.
  29. .. versionadded:: 3.0.0
  30. Replaces ``contextfunction`` and ``contextfilter``.
  31. """
  32. f.jinja_pass_arg = _PassArg.context # type: ignore
  33. return f
  34. def pass_eval_context(f: F) -> F:
  35. """Pass the :class:`~jinja2.nodes.EvalContext` as the first argument
  36. to the decorated function when called while rendering a template.
  37. See :ref:`eval-context`.
  38. Can be used on functions, filters, and tests.
  39. If only ``EvalContext.environment`` is needed, use
  40. :func:`pass_environment`.
  41. .. versionadded:: 3.0.0
  42. Replaces ``evalcontextfunction`` and ``evalcontextfilter``.
  43. """
  44. f.jinja_pass_arg = _PassArg.eval_context # type: ignore
  45. return f
  46. def pass_environment(f: F) -> F:
  47. """Pass the :class:`~jinja2.Environment` as the first argument to
  48. the decorated function when called while rendering a template.
  49. Can be used on functions, filters, and tests.
  50. .. versionadded:: 3.0.0
  51. Replaces ``environmentfunction`` and ``environmentfilter``.
  52. """
  53. f.jinja_pass_arg = _PassArg.environment # type: ignore
  54. return f
  55. class _PassArg(enum.Enum):
  56. context = enum.auto()
  57. eval_context = enum.auto()
  58. environment = enum.auto()
  59. @classmethod
  60. def from_obj(cls, obj: F) -> t.Optional["_PassArg"]:
  61. if hasattr(obj, "jinja_pass_arg"):
  62. return obj.jinja_pass_arg # type: ignore
  63. for prefix in "context", "eval_context", "environment":
  64. squashed = prefix.replace("_", "")
  65. for name in f"{squashed}function", f"{squashed}filter":
  66. if getattr(obj, name, False) is True:
  67. warnings.warn(
  68. f"{name!r} is deprecated and will stop working"
  69. f" in Jinja 3.1. Use 'pass_{prefix}' instead.",
  70. DeprecationWarning,
  71. stacklevel=2,
  72. )
  73. return cls[prefix]
  74. return None
  75. def contextfunction(f: F) -> F:
  76. """Pass the context as the first argument to the decorated function.
  77. .. deprecated:: 3.0
  78. Will be removed in Jinja 3.1. Use :func:`~jinja2.pass_context`
  79. instead.
  80. """
  81. warnings.warn(
  82. "'contextfunction' is renamed to 'pass_context', the old name"
  83. " will be removed in Jinja 3.1.",
  84. DeprecationWarning,
  85. stacklevel=2,
  86. )
  87. return pass_context(f)
  88. def evalcontextfunction(f: F) -> F:
  89. """Pass the eval context as the first argument to the decorated
  90. function.
  91. .. deprecated:: 3.0
  92. Will be removed in Jinja 3.1. Use
  93. :func:`~jinja2.pass_eval_context` instead.
  94. .. versionadded:: 2.4
  95. """
  96. warnings.warn(
  97. "'evalcontextfunction' is renamed to 'pass_eval_context', the"
  98. " old name will be removed in Jinja 3.1.",
  99. DeprecationWarning,
  100. stacklevel=2,
  101. )
  102. return pass_eval_context(f)
  103. def environmentfunction(f: F) -> F:
  104. """Pass the environment as the first argument to the decorated
  105. function.
  106. .. deprecated:: 3.0
  107. Will be removed in Jinja 3.1. Use
  108. :func:`~jinja2.pass_environment` instead.
  109. """
  110. warnings.warn(
  111. "'environmentfunction' is renamed to 'pass_environment', the"
  112. " old name will be removed in Jinja 3.1.",
  113. DeprecationWarning,
  114. stacklevel=2,
  115. )
  116. return pass_environment(f)
  117. def internalcode(f: F) -> F:
  118. """Marks the function as internally used"""
  119. internal_code.add(f.__code__)
  120. return f
  121. def is_undefined(obj: t.Any) -> bool:
  122. """Check if the object passed is undefined. This does nothing more than
  123. performing an instance check against :class:`Undefined` but looks nicer.
  124. This can be used for custom filters or tests that want to react to
  125. undefined variables. For example a custom default filter can look like
  126. this::
  127. def default(var, default=''):
  128. if is_undefined(var):
  129. return default
  130. return var
  131. """
  132. from .runtime import Undefined
  133. return isinstance(obj, Undefined)
  134. def consume(iterable: t.Iterable[t.Any]) -> None:
  135. """Consumes an iterable without doing anything with it."""
  136. for _ in iterable:
  137. pass
  138. def clear_caches() -> None:
  139. """Jinja keeps internal caches for environments and lexers. These are
  140. used so that Jinja doesn't have to recreate environments and lexers all
  141. the time. Normally you don't have to care about that but if you are
  142. measuring memory consumption you may want to clean the caches.
  143. """
  144. from .environment import get_spontaneous_environment
  145. from .lexer import _lexer_cache
  146. get_spontaneous_environment.cache_clear()
  147. _lexer_cache.clear()
  148. def import_string(import_name: str, silent: bool = False) -> t.Any:
  149. """Imports an object based on a string. This is useful if you want to
  150. use import paths as endpoints or something similar. An import path can
  151. be specified either in dotted notation (``xml.sax.saxutils.escape``)
  152. or with a colon as object delimiter (``xml.sax.saxutils:escape``).
  153. If the `silent` is True the return value will be `None` if the import
  154. fails.
  155. :return: imported object
  156. """
  157. try:
  158. if ":" in import_name:
  159. module, obj = import_name.split(":", 1)
  160. elif "." in import_name:
  161. module, _, obj = import_name.rpartition(".")
  162. else:
  163. return __import__(import_name)
  164. return getattr(__import__(module, None, None, [obj]), obj)
  165. except (ImportError, AttributeError):
  166. if not silent:
  167. raise
  168. def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO]:
  169. """Returns a file descriptor for the filename if that file exists,
  170. otherwise ``None``.
  171. """
  172. if not os.path.isfile(filename):
  173. return None
  174. return open(filename, mode)
  175. def object_type_repr(obj: t.Any) -> str:
  176. """Returns the name of the object's type. For some recognized
  177. singletons the name of the object is returned instead. (For
  178. example for `None` and `Ellipsis`).
  179. """
  180. if obj is None:
  181. return "None"
  182. elif obj is Ellipsis:
  183. return "Ellipsis"
  184. cls = type(obj)
  185. if cls.__module__ == "builtins":
  186. return f"{cls.__name__} object"
  187. return f"{cls.__module__}.{cls.__name__} object"
  188. def pformat(obj: t.Any) -> str:
  189. """Format an object using :func:`pprint.pformat`."""
  190. from pprint import pformat # type: ignore
  191. return pformat(obj)
  192. _http_re = re.compile(
  193. r"""
  194. ^
  195. (
  196. (https?://|www\.) # scheme or www
  197. (([\w%-]+\.)+)? # subdomain
  198. (
  199. [a-z]{2,63} # basic tld
  200. |
  201. xn--[\w%]{2,59} # idna tld
  202. )
  203. |
  204. ([\w%-]{2,63}\.)+ # basic domain
  205. (com|net|int|edu|gov|org|info|mil) # basic tld
  206. |
  207. (https?://) # scheme
  208. (
  209. (([\d]{1,3})(\.[\d]{1,3}){3}) # IPv4
  210. |
  211. (\[([\da-f]{0,4}:){2}([\da-f]{0,4}:?){1,6}]) # IPv6
  212. )
  213. )
  214. (?::[\d]{1,5})? # port
  215. (?:[/?#]\S*)? # path, query, and fragment
  216. $
  217. """,
  218. re.IGNORECASE | re.VERBOSE,
  219. )
  220. _email_re = re.compile(r"^\S+@\w[\w.-]*\.\w+$")
  221. def urlize(
  222. text: str,
  223. trim_url_limit: t.Optional[int] = None,
  224. rel: t.Optional[str] = None,
  225. target: t.Optional[str] = None,
  226. extra_schemes: t.Optional[t.Iterable[str]] = None,
  227. ) -> str:
  228. """Convert URLs in text into clickable links.
  229. This may not recognize links in some situations. Usually, a more
  230. comprehensive formatter, such as a Markdown library, is a better
  231. choice.
  232. Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
  233. addresses. Links with trailing punctuation (periods, commas, closing
  234. parentheses) and leading punctuation (opening parentheses) are
  235. recognized excluding the punctuation. Email addresses that include
  236. header fields are not recognized (for example,
  237. ``mailto:address@example.com?cc=copy@example.com``).
  238. :param text: Original text containing URLs to link.
  239. :param trim_url_limit: Shorten displayed URL values to this length.
  240. :param target: Add the ``target`` attribute to links.
  241. :param rel: Add the ``rel`` attribute to links.
  242. :param extra_schemes: Recognize URLs that start with these schemes
  243. in addition to the default behavior.
  244. .. versionchanged:: 3.0
  245. The ``extra_schemes`` parameter was added.
  246. .. versionchanged:: 3.0
  247. Generate ``https://`` links for URLs without a scheme.
  248. .. versionchanged:: 3.0
  249. The parsing rules were updated. Recognize email addresses with
  250. or without the ``mailto:`` scheme. Validate IP addresses. Ignore
  251. parentheses and brackets in more cases.
  252. """
  253. if trim_url_limit is not None:
  254. def trim_url(x: str) -> str:
  255. if len(x) > trim_url_limit: # type: ignore
  256. return f"{x[:trim_url_limit]}..."
  257. return x
  258. else:
  259. def trim_url(x: str) -> str:
  260. return x
  261. words = re.split(r"(\s+)", str(markupsafe.escape(text)))
  262. rel_attr = f' rel="{markupsafe.escape(rel)}"' if rel else ""
  263. target_attr = f' target="{markupsafe.escape(target)}"' if target else ""
  264. for i, word in enumerate(words):
  265. head, middle, tail = "", word, ""
  266. match = re.match(r"^([(<]|&lt;)+", middle)
  267. if match:
  268. head = match.group()
  269. middle = middle[match.end() :]
  270. # Unlike lead, which is anchored to the start of the string,
  271. # need to check that the string ends with any of the characters
  272. # before trying to match all of them, to avoid backtracking.
  273. if middle.endswith((")", ">", ".", ",", "\n", "&gt;")):
  274. match = re.search(r"([)>.,\n]|&gt;)+$", middle)
  275. if match:
  276. tail = match.group()
  277. middle = middle[: match.start()]
  278. # Prefer balancing parentheses in URLs instead of ignoring a
  279. # trailing character.
  280. for start_char, end_char in ("(", ")"), ("<", ">"), ("&lt;", "&gt;"):
  281. start_count = middle.count(start_char)
  282. if start_count <= middle.count(end_char):
  283. # Balanced, or lighter on the left
  284. continue
  285. # Move as many as possible from the tail to balance
  286. for _ in range(min(start_count, tail.count(end_char))):
  287. end_index = tail.index(end_char) + len(end_char)
  288. # Move anything in the tail before the end char too
  289. middle += tail[:end_index]
  290. tail = tail[end_index:]
  291. if _http_re.match(middle):
  292. if middle.startswith("https://") or middle.startswith("http://"):
  293. middle = (
  294. f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'
  295. )
  296. else:
  297. middle = (
  298. f'<a href="https://{middle}"{rel_attr}{target_attr}>'
  299. f"{trim_url(middle)}</a>"
  300. )
  301. elif middle.startswith("mailto:") and _email_re.match(middle[7:]):
  302. middle = f'<a href="{middle}">{middle[7:]}</a>'
  303. elif (
  304. "@" in middle
  305. and not middle.startswith("www.")
  306. and ":" not in middle
  307. and _email_re.match(middle)
  308. ):
  309. middle = f'<a href="mailto:{middle}">{middle}</a>'
  310. elif extra_schemes is not None:
  311. for scheme in extra_schemes:
  312. if middle != scheme and middle.startswith(scheme):
  313. middle = f'<a href="{middle}"{rel_attr}{target_attr}>{middle}</a>'
  314. words[i] = f"{head}{middle}{tail}"
  315. return "".join(words)
  316. def generate_lorem_ipsum(
  317. n: int = 5, html: bool = True, min: int = 20, max: int = 100
  318. ) -> str:
  319. """Generate some lorem ipsum for the template."""
  320. from .constants import LOREM_IPSUM_WORDS
  321. words = LOREM_IPSUM_WORDS.split()
  322. result = []
  323. for _ in range(n):
  324. next_capitalized = True
  325. last_comma = last_fullstop = 0
  326. word = None
  327. last = None
  328. p = []
  329. # each paragraph contains out of 20 to 100 words.
  330. for idx, _ in enumerate(range(randrange(min, max))):
  331. while True:
  332. word = choice(words)
  333. if word != last:
  334. last = word
  335. break
  336. if next_capitalized:
  337. word = word.capitalize()
  338. next_capitalized = False
  339. # add commas
  340. if idx - randrange(3, 8) > last_comma:
  341. last_comma = idx
  342. last_fullstop += 2
  343. word += ","
  344. # add end of sentences
  345. if idx - randrange(10, 20) > last_fullstop:
  346. last_comma = last_fullstop = idx
  347. word += "."
  348. next_capitalized = True
  349. p.append(word)
  350. # ensure that the paragraph ends with a dot.
  351. p_str = " ".join(p)
  352. if p_str.endswith(","):
  353. p_str = p_str[:-1] + "."
  354. elif not p_str.endswith("."):
  355. p_str += "."
  356. result.append(p_str)
  357. if not html:
  358. return "\n\n".join(result)
  359. return markupsafe.Markup(
  360. "\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)
  361. )
  362. def url_quote(obj: t.Any, charset: str = "utf-8", for_qs: bool = False) -> str:
  363. """Quote a string for use in a URL using the given charset.
  364. :param obj: String or bytes to quote. Other types are converted to
  365. string then encoded to bytes using the given charset.
  366. :param charset: Encode text to bytes using this charset.
  367. :param for_qs: Quote "/" and use "+" for spaces.
  368. """
  369. if not isinstance(obj, bytes):
  370. if not isinstance(obj, str):
  371. obj = str(obj)
  372. obj = obj.encode(charset)
  373. safe = b"" if for_qs else b"/"
  374. rv = quote_from_bytes(obj, safe)
  375. if for_qs:
  376. rv = rv.replace("%20", "+")
  377. return rv
  378. def unicode_urlencode(obj: t.Any, charset: str = "utf-8", for_qs: bool = False) -> str:
  379. import warnings
  380. warnings.warn(
  381. "'unicode_urlencode' has been renamed to 'url_quote'. The old"
  382. " name will be removed in Jinja 3.1.",
  383. DeprecationWarning,
  384. stacklevel=2,
  385. )
  386. return url_quote(obj, charset=charset, for_qs=for_qs)
  387. @abc.MutableMapping.register
  388. class LRUCache:
  389. """A simple LRU Cache implementation."""
  390. # this is fast for small capacities (something below 1000) but doesn't
  391. # scale. But as long as it's only used as storage for templates this
  392. # won't do any harm.
  393. def __init__(self, capacity: int) -> None:
  394. self.capacity = capacity
  395. self._mapping: t.Dict[t.Any, t.Any] = {}
  396. self._queue: "te.Deque[t.Any]" = deque()
  397. self._postinit()
  398. def _postinit(self) -> None:
  399. # alias all queue methods for faster lookup
  400. self._popleft = self._queue.popleft
  401. self._pop = self._queue.pop
  402. self._remove = self._queue.remove
  403. self._wlock = Lock()
  404. self._append = self._queue.append
  405. def __getstate__(self) -> t.Mapping[str, t.Any]:
  406. return {
  407. "capacity": self.capacity,
  408. "_mapping": self._mapping,
  409. "_queue": self._queue,
  410. }
  411. def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:
  412. self.__dict__.update(d)
  413. self._postinit()
  414. def __getnewargs__(self) -> t.Tuple:
  415. return (self.capacity,)
  416. def copy(self) -> "LRUCache":
  417. """Return a shallow copy of the instance."""
  418. rv = self.__class__(self.capacity)
  419. rv._mapping.update(self._mapping)
  420. rv._queue.extend(self._queue)
  421. return rv
  422. def get(self, key: t.Any, default: t.Any = None) -> t.Any:
  423. """Return an item from the cache dict or `default`"""
  424. try:
  425. return self[key]
  426. except KeyError:
  427. return default
  428. def setdefault(self, key: t.Any, default: t.Any = None) -> t.Any:
  429. """Set `default` if the key is not in the cache otherwise
  430. leave unchanged. Return the value of this key.
  431. """
  432. try:
  433. return self[key]
  434. except KeyError:
  435. self[key] = default
  436. return default
  437. def clear(self) -> None:
  438. """Clear the cache."""
  439. with self._wlock:
  440. self._mapping.clear()
  441. self._queue.clear()
  442. def __contains__(self, key: t.Any) -> bool:
  443. """Check if a key exists in this cache."""
  444. return key in self._mapping
  445. def __len__(self) -> int:
  446. """Return the current size of the cache."""
  447. return len(self._mapping)
  448. def __repr__(self) -> str:
  449. return f"<{type(self).__name__} {self._mapping!r}>"
  450. def __getitem__(self, key: t.Any) -> t.Any:
  451. """Get an item from the cache. Moves the item up so that it has the
  452. highest priority then.
  453. Raise a `KeyError` if it does not exist.
  454. """
  455. with self._wlock:
  456. rv = self._mapping[key]
  457. if self._queue[-1] != key:
  458. try:
  459. self._remove(key)
  460. except ValueError:
  461. # if something removed the key from the container
  462. # when we read, ignore the ValueError that we would
  463. # get otherwise.
  464. pass
  465. self._append(key)
  466. return rv
  467. def __setitem__(self, key: t.Any, value: t.Any) -> None:
  468. """Sets the value for an item. Moves the item up so that it
  469. has the highest priority then.
  470. """
  471. with self._wlock:
  472. if key in self._mapping:
  473. self._remove(key)
  474. elif len(self._mapping) == self.capacity:
  475. del self._mapping[self._popleft()]
  476. self._append(key)
  477. self._mapping[key] = value
  478. def __delitem__(self, key: t.Any) -> None:
  479. """Remove an item from the cache dict.
  480. Raise a `KeyError` if it does not exist.
  481. """
  482. with self._wlock:
  483. del self._mapping[key]
  484. try:
  485. self._remove(key)
  486. except ValueError:
  487. pass
  488. def items(self) -> t.Iterable[t.Tuple[t.Any, t.Any]]:
  489. """Return a list of items."""
  490. result = [(key, self._mapping[key]) for key in list(self._queue)]
  491. result.reverse()
  492. return result
  493. def values(self) -> t.Iterable[t.Any]:
  494. """Return a list of all values."""
  495. return [x[1] for x in self.items()]
  496. def keys(self) -> t.Iterable[t.Any]:
  497. """Return a list of all keys ordered by most recent usage."""
  498. return list(self)
  499. def __iter__(self) -> t.Iterator[t.Any]:
  500. return reversed(tuple(self._queue))
  501. def __reversed__(self) -> t.Iterator[t.Any]:
  502. """Iterate over the keys in the cache dict, oldest items
  503. coming first.
  504. """
  505. return iter(tuple(self._queue))
  506. __copy__ = copy
  507. def select_autoescape(
  508. enabled_extensions: t.Collection[str] = ("html", "htm", "xml"),
  509. disabled_extensions: t.Collection[str] = (),
  510. default_for_string: bool = True,
  511. default: bool = False,
  512. ) -> t.Callable[[t.Optional[str]], bool]:
  513. """Intelligently sets the initial value of autoescaping based on the
  514. filename of the template. This is the recommended way to configure
  515. autoescaping if you do not want to write a custom function yourself.
  516. If you want to enable it for all templates created from strings or
  517. for all templates with `.html` and `.xml` extensions::
  518. from jinja2 import Environment, select_autoescape
  519. env = Environment(autoescape=select_autoescape(
  520. enabled_extensions=('html', 'xml'),
  521. default_for_string=True,
  522. ))
  523. Example configuration to turn it on at all times except if the template
  524. ends with `.txt`::
  525. from jinja2 import Environment, select_autoescape
  526. env = Environment(autoescape=select_autoescape(
  527. disabled_extensions=('txt',),
  528. default_for_string=True,
  529. default=True,
  530. ))
  531. The `enabled_extensions` is an iterable of all the extensions that
  532. autoescaping should be enabled for. Likewise `disabled_extensions` is
  533. a list of all templates it should be disabled for. If a template is
  534. loaded from a string then the default from `default_for_string` is used.
  535. If nothing matches then the initial value of autoescaping is set to the
  536. value of `default`.
  537. For security reasons this function operates case insensitive.
  538. .. versionadded:: 2.9
  539. """
  540. enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)
  541. disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)
  542. def autoescape(template_name: t.Optional[str]) -> bool:
  543. if template_name is None:
  544. return default_for_string
  545. template_name = template_name.lower()
  546. if template_name.endswith(enabled_patterns):
  547. return True
  548. if template_name.endswith(disabled_patterns):
  549. return False
  550. return default
  551. return autoescape
  552. def htmlsafe_json_dumps(
  553. obj: t.Any, dumps: t.Optional[t.Callable[..., str]] = None, **kwargs: t.Any
  554. ) -> markupsafe.Markup:
  555. """Serialize an object to a string of JSON with :func:`json.dumps`,
  556. then replace HTML-unsafe characters with Unicode escapes and mark
  557. the result safe with :class:`~markupsafe.Markup`.
  558. This is available in templates as the ``|tojson`` filter.
  559. The following characters are escaped: ``<``, ``>``, ``&``, ``'``.
  560. The returned string is safe to render in HTML documents and
  561. ``<script>`` tags. The exception is in HTML attributes that are
  562. double quoted; either use single quotes or the ``|forceescape``
  563. filter.
  564. :param obj: The object to serialize to JSON.
  565. :param dumps: The ``dumps`` function to use. Defaults to
  566. ``env.policies["json.dumps_function"]``, which defaults to
  567. :func:`json.dumps`.
  568. :param kwargs: Extra arguments to pass to ``dumps``. Merged onto
  569. ``env.policies["json.dumps_kwargs"]``.
  570. .. versionchanged:: 3.0
  571. The ``dumper`` parameter is renamed to ``dumps``.
  572. .. versionadded:: 2.9
  573. """
  574. if dumps is None:
  575. dumps = json.dumps
  576. return markupsafe.Markup(
  577. dumps(obj, **kwargs)
  578. .replace("<", "\\u003c")
  579. .replace(">", "\\u003e")
  580. .replace("&", "\\u0026")
  581. .replace("'", "\\u0027")
  582. )
  583. class Cycler:
  584. """Cycle through values by yield them one at a time, then restarting
  585. once the end is reached. Available as ``cycler`` in templates.
  586. Similar to ``loop.cycle``, but can be used outside loops or across
  587. multiple loops. For example, render a list of folders and files in a
  588. list, alternating giving them "odd" and "even" classes.
  589. .. code-block:: html+jinja
  590. {% set row_class = cycler("odd", "even") %}
  591. <ul class="browser">
  592. {% for folder in folders %}
  593. <li class="folder {{ row_class.next() }}">{{ folder }}
  594. {% endfor %}
  595. {% for file in files %}
  596. <li class="file {{ row_class.next() }}">{{ file }}
  597. {% endfor %}
  598. </ul>
  599. :param items: Each positional argument will be yielded in the order
  600. given for each cycle.
  601. .. versionadded:: 2.1
  602. """
  603. def __init__(self, *items: t.Any) -> None:
  604. if not items:
  605. raise RuntimeError("at least one item has to be provided")
  606. self.items = items
  607. self.pos = 0
  608. def reset(self) -> None:
  609. """Resets the current item to the first item."""
  610. self.pos = 0
  611. @property
  612. def current(self) -> t.Any:
  613. """Return the current item. Equivalent to the item that will be
  614. returned next time :meth:`next` is called.
  615. """
  616. return self.items[self.pos]
  617. def next(self) -> t.Any:
  618. """Return the current item, then advance :attr:`current` to the
  619. next item.
  620. """
  621. rv = self.current
  622. self.pos = (self.pos + 1) % len(self.items)
  623. return rv
  624. __next__ = next
  625. class Joiner:
  626. """A joining helper for templates."""
  627. def __init__(self, sep: str = ", ") -> None:
  628. self.sep = sep
  629. self.used = False
  630. def __call__(self) -> str:
  631. if not self.used:
  632. self.used = True
  633. return ""
  634. return self.sep
  635. class Namespace:
  636. """A namespace object that can hold arbitrary attributes. It may be
  637. initialized from a dictionary or with keyword arguments."""
  638. def __init__(*args: t.Any, **kwargs: t.Any) -> None: # noqa: B902
  639. self, args = args[0], args[1:]
  640. self.__attrs = dict(*args, **kwargs)
  641. def __getattribute__(self, name: str) -> t.Any:
  642. # __class__ is needed for the awaitable check in async mode
  643. if name in {"_Namespace__attrs", "__class__"}:
  644. return object.__getattribute__(self, name)
  645. try:
  646. return self.__attrs[name]
  647. except KeyError:
  648. raise AttributeError(name) from None
  649. def __setitem__(self, name: str, value: t.Any) -> None:
  650. self.__attrs[name] = value
  651. def __repr__(self) -> str:
  652. return f"<Namespace {self.__attrs!r}>"
  653. class Markup(markupsafe.Markup):
  654. def __new__(cls, base="", encoding=None, errors="strict"): # type: ignore
  655. warnings.warn(
  656. "'jinja2.Markup' is deprecated and will be removed in Jinja"
  657. " 3.1. Import 'markupsafe.Markup' instead.",
  658. DeprecationWarning,
  659. stacklevel=2,
  660. )
  661. return super().__new__(cls, base, encoding, errors)
  662. def escape(s: t.Any) -> str:
  663. warnings.warn(
  664. "'jinja2.escape' is deprecated and will be removed in Jinja"
  665. " 3.1. Import 'markupsafe.escape' instead.",
  666. DeprecationWarning,
  667. stacklevel=2,
  668. )
  669. return markupsafe.escape(s)