utils.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import os
  4. import re
  5. import warnings
  6. from collections import deque
  7. from random import choice
  8. from random import randrange
  9. from string import ascii_letters as _letters
  10. from string import digits as _digits
  11. from threading import Lock
  12. from markupsafe import escape
  13. from markupsafe import Markup
  14. from ._compat import abc
  15. from ._compat import string_types
  16. from ._compat import text_type
  17. from ._compat import url_quote
  18. # special singleton representing missing values for the runtime
  19. missing = type("MissingType", (), {"__repr__": lambda x: "missing"})()
  20. # internal code
  21. internal_code = set()
  22. concat = u"".join
  23. _slash_escape = "\\/" not in json.dumps("/")
  24. def contextfunction(f):
  25. """This decorator can be used to mark a function or method context callable.
  26. A context callable is passed the active :class:`Context` as first argument when
  27. called from the template. This is useful if a function wants to get access
  28. to the context or functions provided on the context object. For example
  29. a function that returns a sorted list of template variables the current
  30. template exports could look like this::
  31. @contextfunction
  32. def get_exported_names(context):
  33. return sorted(context.exported_vars)
  34. """
  35. f.contextfunction = True
  36. return f
  37. def evalcontextfunction(f):
  38. """This decorator can be used to mark a function or method as an eval
  39. context callable. This is similar to the :func:`contextfunction`
  40. but instead of passing the context, an evaluation context object is
  41. passed. For more information about the eval context, see
  42. :ref:`eval-context`.
  43. .. versionadded:: 2.4
  44. """
  45. f.evalcontextfunction = True
  46. return f
  47. def environmentfunction(f):
  48. """This decorator can be used to mark a function or method as environment
  49. callable. This decorator works exactly like the :func:`contextfunction`
  50. decorator just that the first argument is the active :class:`Environment`
  51. and not context.
  52. """
  53. f.environmentfunction = True
  54. return f
  55. def internalcode(f):
  56. """Marks the function as internally used"""
  57. internal_code.add(f.__code__)
  58. return f
  59. def is_undefined(obj):
  60. """Check if the object passed is undefined. This does nothing more than
  61. performing an instance check against :class:`Undefined` but looks nicer.
  62. This can be used for custom filters or tests that want to react to
  63. undefined variables. For example a custom default filter can look like
  64. this::
  65. def default(var, default=''):
  66. if is_undefined(var):
  67. return default
  68. return var
  69. """
  70. from .runtime import Undefined
  71. return isinstance(obj, Undefined)
  72. def consume(iterable):
  73. """Consumes an iterable without doing anything with it."""
  74. for _ in iterable:
  75. pass
  76. def clear_caches():
  77. """Jinja keeps internal caches for environments and lexers. These are
  78. used so that Jinja doesn't have to recreate environments and lexers all
  79. the time. Normally you don't have to care about that but if you are
  80. measuring memory consumption you may want to clean the caches.
  81. """
  82. from .environment import _spontaneous_environments
  83. from .lexer import _lexer_cache
  84. _spontaneous_environments.clear()
  85. _lexer_cache.clear()
  86. def import_string(import_name, silent=False):
  87. """Imports an object based on a string. This is useful if you want to
  88. use import paths as endpoints or something similar. An import path can
  89. be specified either in dotted notation (``xml.sax.saxutils.escape``)
  90. or with a colon as object delimiter (``xml.sax.saxutils:escape``).
  91. If the `silent` is True the return value will be `None` if the import
  92. fails.
  93. :return: imported object
  94. """
  95. try:
  96. if ":" in import_name:
  97. module, obj = import_name.split(":", 1)
  98. elif "." in import_name:
  99. module, _, obj = import_name.rpartition(".")
  100. else:
  101. return __import__(import_name)
  102. return getattr(__import__(module, None, None, [obj]), obj)
  103. except (ImportError, AttributeError):
  104. if not silent:
  105. raise
  106. def open_if_exists(filename, mode="rb"):
  107. """Returns a file descriptor for the filename if that file exists,
  108. otherwise ``None``.
  109. """
  110. if not os.path.isfile(filename):
  111. return None
  112. return open(filename, mode)
  113. def object_type_repr(obj):
  114. """Returns the name of the object's type. For some recognized
  115. singletons the name of the object is returned instead. (For
  116. example for `None` and `Ellipsis`).
  117. """
  118. if obj is None:
  119. return "None"
  120. elif obj is Ellipsis:
  121. return "Ellipsis"
  122. cls = type(obj)
  123. # __builtin__ in 2.x, builtins in 3.x
  124. if cls.__module__ in ("__builtin__", "builtins"):
  125. name = cls.__name__
  126. else:
  127. name = cls.__module__ + "." + cls.__name__
  128. return "%s object" % name
  129. def pformat(obj, verbose=False):
  130. """Prettyprint an object. Either use the `pretty` library or the
  131. builtin `pprint`.
  132. """
  133. try:
  134. from pretty import pretty
  135. return pretty(obj, verbose=verbose)
  136. except ImportError:
  137. from pprint import pformat
  138. return pformat(obj)
  139. def urlize(text, trim_url_limit=None, rel=None, target=None):
  140. """Converts any URLs in text into clickable links. Works on http://,
  141. https:// and www. links. Links can have trailing punctuation (periods,
  142. commas, close-parens) and leading punctuation (opening parens) and
  143. it'll still do the right thing.
  144. If trim_url_limit is not None, the URLs in link text will be limited
  145. to trim_url_limit characters.
  146. If nofollow is True, the URLs in link text will get a rel="nofollow"
  147. attribute.
  148. If target is not None, a target attribute will be added to the link.
  149. """
  150. trim_url = (
  151. lambda x, limit=trim_url_limit: limit is not None
  152. and (x[:limit] + (len(x) >= limit and "..." or ""))
  153. or x
  154. )
  155. words = re.split(r"(\s+)", text_type(escape(text)))
  156. rel_attr = rel and ' rel="%s"' % text_type(escape(rel)) or ""
  157. target_attr = target and ' target="%s"' % escape(target) or ""
  158. for i, word in enumerate(words):
  159. head, middle, tail = "", word, ""
  160. match = re.match(r"^([(<]|&lt;)+", middle)
  161. if match:
  162. head = match.group()
  163. middle = middle[match.end() :]
  164. # Unlike lead, which is anchored to the start of the string,
  165. # need to check that the string ends with any of the characters
  166. # before trying to match all of them, to avoid backtracking.
  167. if middle.endswith((")", ">", ".", ",", "\n", "&gt;")):
  168. match = re.search(r"([)>.,\n]|&gt;)+$", middle)
  169. if match:
  170. tail = match.group()
  171. middle = middle[: match.start()]
  172. if middle.startswith("www.") or (
  173. "@" not in middle
  174. and not middle.startswith("http://")
  175. and not middle.startswith("https://")
  176. and len(middle) > 0
  177. and middle[0] in _letters + _digits
  178. and (
  179. middle.endswith(".org")
  180. or middle.endswith(".net")
  181. or middle.endswith(".com")
  182. )
  183. ):
  184. middle = '<a href="http://%s"%s%s>%s</a>' % (
  185. middle,
  186. rel_attr,
  187. target_attr,
  188. trim_url(middle),
  189. )
  190. if middle.startswith("http://") or middle.startswith("https://"):
  191. middle = '<a href="%s"%s%s>%s</a>' % (
  192. middle,
  193. rel_attr,
  194. target_attr,
  195. trim_url(middle),
  196. )
  197. if (
  198. "@" in middle
  199. and not middle.startswith("www.")
  200. and ":" not in middle
  201. and re.match(r"^\S+@\w[\w.-]*\.\w+$", middle)
  202. ):
  203. middle = '<a href="mailto:%s">%s</a>' % (middle, middle)
  204. words[i] = head + middle + tail
  205. return u"".join(words)
  206. def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
  207. """Generate some lorem ipsum for the template."""
  208. from .constants import LOREM_IPSUM_WORDS
  209. words = LOREM_IPSUM_WORDS.split()
  210. result = []
  211. for _ in range(n):
  212. next_capitalized = True
  213. last_comma = last_fullstop = 0
  214. word = None
  215. last = None
  216. p = []
  217. # each paragraph contains out of 20 to 100 words.
  218. for idx, _ in enumerate(range(randrange(min, max))):
  219. while True:
  220. word = choice(words)
  221. if word != last:
  222. last = word
  223. break
  224. if next_capitalized:
  225. word = word.capitalize()
  226. next_capitalized = False
  227. # add commas
  228. if idx - randrange(3, 8) > last_comma:
  229. last_comma = idx
  230. last_fullstop += 2
  231. word += ","
  232. # add end of sentences
  233. if idx - randrange(10, 20) > last_fullstop:
  234. last_comma = last_fullstop = idx
  235. word += "."
  236. next_capitalized = True
  237. p.append(word)
  238. # ensure that the paragraph ends with a dot.
  239. p = u" ".join(p)
  240. if p.endswith(","):
  241. p = p[:-1] + "."
  242. elif not p.endswith("."):
  243. p += "."
  244. result.append(p)
  245. if not html:
  246. return u"\n\n".join(result)
  247. return Markup(u"\n".join(u"<p>%s</p>" % escape(x) for x in result))
  248. def unicode_urlencode(obj, charset="utf-8", for_qs=False):
  249. """Quote a string for use in a URL using the given charset.
  250. This function is misnamed, it is a wrapper around
  251. :func:`urllib.parse.quote`.
  252. :param obj: String or bytes to quote. Other types are converted to
  253. string then encoded to bytes using the given charset.
  254. :param charset: Encode text to bytes using this charset.
  255. :param for_qs: Quote "/" and use "+" for spaces.
  256. """
  257. if not isinstance(obj, string_types):
  258. obj = text_type(obj)
  259. if isinstance(obj, text_type):
  260. obj = obj.encode(charset)
  261. safe = b"" if for_qs else b"/"
  262. rv = url_quote(obj, safe)
  263. if not isinstance(rv, text_type):
  264. rv = rv.decode("utf-8")
  265. if for_qs:
  266. rv = rv.replace("%20", "+")
  267. return rv
  268. class LRUCache(object):
  269. """A simple LRU Cache implementation."""
  270. # this is fast for small capacities (something below 1000) but doesn't
  271. # scale. But as long as it's only used as storage for templates this
  272. # won't do any harm.
  273. def __init__(self, capacity):
  274. self.capacity = capacity
  275. self._mapping = {}
  276. self._queue = deque()
  277. self._postinit()
  278. def _postinit(self):
  279. # alias all queue methods for faster lookup
  280. self._popleft = self._queue.popleft
  281. self._pop = self._queue.pop
  282. self._remove = self._queue.remove
  283. self._wlock = Lock()
  284. self._append = self._queue.append
  285. def __getstate__(self):
  286. return {
  287. "capacity": self.capacity,
  288. "_mapping": self._mapping,
  289. "_queue": self._queue,
  290. }
  291. def __setstate__(self, d):
  292. self.__dict__.update(d)
  293. self._postinit()
  294. def __getnewargs__(self):
  295. return (self.capacity,)
  296. def copy(self):
  297. """Return a shallow copy of the instance."""
  298. rv = self.__class__(self.capacity)
  299. rv._mapping.update(self._mapping)
  300. rv._queue.extend(self._queue)
  301. return rv
  302. def get(self, key, default=None):
  303. """Return an item from the cache dict or `default`"""
  304. try:
  305. return self[key]
  306. except KeyError:
  307. return default
  308. def setdefault(self, key, default=None):
  309. """Set `default` if the key is not in the cache otherwise
  310. leave unchanged. Return the value of this key.
  311. """
  312. try:
  313. return self[key]
  314. except KeyError:
  315. self[key] = default
  316. return default
  317. def clear(self):
  318. """Clear the cache."""
  319. self._wlock.acquire()
  320. try:
  321. self._mapping.clear()
  322. self._queue.clear()
  323. finally:
  324. self._wlock.release()
  325. def __contains__(self, key):
  326. """Check if a key exists in this cache."""
  327. return key in self._mapping
  328. def __len__(self):
  329. """Return the current size of the cache."""
  330. return len(self._mapping)
  331. def __repr__(self):
  332. return "<%s %r>" % (self.__class__.__name__, self._mapping)
  333. def __getitem__(self, key):
  334. """Get an item from the cache. Moves the item up so that it has the
  335. highest priority then.
  336. Raise a `KeyError` if it does not exist.
  337. """
  338. self._wlock.acquire()
  339. try:
  340. rv = self._mapping[key]
  341. if self._queue[-1] != key:
  342. try:
  343. self._remove(key)
  344. except ValueError:
  345. # if something removed the key from the container
  346. # when we read, ignore the ValueError that we would
  347. # get otherwise.
  348. pass
  349. self._append(key)
  350. return rv
  351. finally:
  352. self._wlock.release()
  353. def __setitem__(self, key, value):
  354. """Sets the value for an item. Moves the item up so that it
  355. has the highest priority then.
  356. """
  357. self._wlock.acquire()
  358. try:
  359. if key in self._mapping:
  360. self._remove(key)
  361. elif len(self._mapping) == self.capacity:
  362. del self._mapping[self._popleft()]
  363. self._append(key)
  364. self._mapping[key] = value
  365. finally:
  366. self._wlock.release()
  367. def __delitem__(self, key):
  368. """Remove an item from the cache dict.
  369. Raise a `KeyError` if it does not exist.
  370. """
  371. self._wlock.acquire()
  372. try:
  373. del self._mapping[key]
  374. try:
  375. self._remove(key)
  376. except ValueError:
  377. pass
  378. finally:
  379. self._wlock.release()
  380. def items(self):
  381. """Return a list of items."""
  382. result = [(key, self._mapping[key]) for key in list(self._queue)]
  383. result.reverse()
  384. return result
  385. def iteritems(self):
  386. """Iterate over all items."""
  387. warnings.warn(
  388. "'iteritems()' will be removed in version 3.0. Use"
  389. " 'iter(cache.items())' instead.",
  390. DeprecationWarning,
  391. stacklevel=2,
  392. )
  393. return iter(self.items())
  394. def values(self):
  395. """Return a list of all values."""
  396. return [x[1] for x in self.items()]
  397. def itervalue(self):
  398. """Iterate over all values."""
  399. warnings.warn(
  400. "'itervalue()' will be removed in version 3.0. Use"
  401. " 'iter(cache.values())' instead.",
  402. DeprecationWarning,
  403. stacklevel=2,
  404. )
  405. return iter(self.values())
  406. def itervalues(self):
  407. """Iterate over all values."""
  408. warnings.warn(
  409. "'itervalues()' will be removed in version 3.0. Use"
  410. " 'iter(cache.values())' instead.",
  411. DeprecationWarning,
  412. stacklevel=2,
  413. )
  414. return iter(self.values())
  415. def keys(self):
  416. """Return a list of all keys ordered by most recent usage."""
  417. return list(self)
  418. def iterkeys(self):
  419. """Iterate over all keys in the cache dict, ordered by
  420. the most recent usage.
  421. """
  422. warnings.warn(
  423. "'iterkeys()' will be removed in version 3.0. Use"
  424. " 'iter(cache.keys())' instead.",
  425. DeprecationWarning,
  426. stacklevel=2,
  427. )
  428. return iter(self)
  429. def __iter__(self):
  430. return reversed(tuple(self._queue))
  431. def __reversed__(self):
  432. """Iterate over the keys in the cache dict, oldest items
  433. coming first.
  434. """
  435. return iter(tuple(self._queue))
  436. __copy__ = copy
  437. abc.MutableMapping.register(LRUCache)
  438. def select_autoescape(
  439. enabled_extensions=("html", "htm", "xml"),
  440. disabled_extensions=(),
  441. default_for_string=True,
  442. default=False,
  443. ):
  444. """Intelligently sets the initial value of autoescaping based on the
  445. filename of the template. This is the recommended way to configure
  446. autoescaping if you do not want to write a custom function yourself.
  447. If you want to enable it for all templates created from strings or
  448. for all templates with `.html` and `.xml` extensions::
  449. from jinja2 import Environment, select_autoescape
  450. env = Environment(autoescape=select_autoescape(
  451. enabled_extensions=('html', 'xml'),
  452. default_for_string=True,
  453. ))
  454. Example configuration to turn it on at all times except if the template
  455. ends with `.txt`::
  456. from jinja2 import Environment, select_autoescape
  457. env = Environment(autoescape=select_autoescape(
  458. disabled_extensions=('txt',),
  459. default_for_string=True,
  460. default=True,
  461. ))
  462. The `enabled_extensions` is an iterable of all the extensions that
  463. autoescaping should be enabled for. Likewise `disabled_extensions` is
  464. a list of all templates it should be disabled for. If a template is
  465. loaded from a string then the default from `default_for_string` is used.
  466. If nothing matches then the initial value of autoescaping is set to the
  467. value of `default`.
  468. For security reasons this function operates case insensitive.
  469. .. versionadded:: 2.9
  470. """
  471. enabled_patterns = tuple("." + x.lstrip(".").lower() for x in enabled_extensions)
  472. disabled_patterns = tuple("." + x.lstrip(".").lower() for x in disabled_extensions)
  473. def autoescape(template_name):
  474. if template_name is None:
  475. return default_for_string
  476. template_name = template_name.lower()
  477. if template_name.endswith(enabled_patterns):
  478. return True
  479. if template_name.endswith(disabled_patterns):
  480. return False
  481. return default
  482. return autoescape
  483. def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
  484. """Works exactly like :func:`dumps` but is safe for use in ``<script>``
  485. tags. It accepts the same arguments and returns a JSON string. Note that
  486. this is available in templates through the ``|tojson`` filter which will
  487. also mark the result as safe. Due to how this function escapes certain
  488. characters this is safe even if used outside of ``<script>`` tags.
  489. The following characters are escaped in strings:
  490. - ``<``
  491. - ``>``
  492. - ``&``
  493. - ``'``
  494. This makes it safe to embed such strings in any place in HTML with the
  495. notable exception of double quoted attributes. In that case single
  496. quote your attributes or HTML escape it in addition.
  497. """
  498. if dumper is None:
  499. dumper = json.dumps
  500. rv = (
  501. dumper(obj, **kwargs)
  502. .replace(u"<", u"\\u003c")
  503. .replace(u">", u"\\u003e")
  504. .replace(u"&", u"\\u0026")
  505. .replace(u"'", u"\\u0027")
  506. )
  507. return Markup(rv)
  508. class Cycler(object):
  509. """Cycle through values by yield them one at a time, then restarting
  510. once the end is reached. Available as ``cycler`` in templates.
  511. Similar to ``loop.cycle``, but can be used outside loops or across
  512. multiple loops. For example, render a list of folders and files in a
  513. list, alternating giving them "odd" and "even" classes.
  514. .. code-block:: html+jinja
  515. {% set row_class = cycler("odd", "even") %}
  516. <ul class="browser">
  517. {% for folder in folders %}
  518. <li class="folder {{ row_class.next() }}">{{ folder }}
  519. {% endfor %}
  520. {% for file in files %}
  521. <li class="file {{ row_class.next() }}">{{ file }}
  522. {% endfor %}
  523. </ul>
  524. :param items: Each positional argument will be yielded in the order
  525. given for each cycle.
  526. .. versionadded:: 2.1
  527. """
  528. def __init__(self, *items):
  529. if not items:
  530. raise RuntimeError("at least one item has to be provided")
  531. self.items = items
  532. self.pos = 0
  533. def reset(self):
  534. """Resets the current item to the first item."""
  535. self.pos = 0
  536. @property
  537. def current(self):
  538. """Return the current item. Equivalent to the item that will be
  539. returned next time :meth:`next` is called.
  540. """
  541. return self.items[self.pos]
  542. def next(self):
  543. """Return the current item, then advance :attr:`current` to the
  544. next item.
  545. """
  546. rv = self.current
  547. self.pos = (self.pos + 1) % len(self.items)
  548. return rv
  549. __next__ = next
  550. class Joiner(object):
  551. """A joining helper for templates."""
  552. def __init__(self, sep=u", "):
  553. self.sep = sep
  554. self.used = False
  555. def __call__(self):
  556. if not self.used:
  557. self.used = True
  558. return u""
  559. return self.sep
  560. class Namespace(object):
  561. """A namespace object that can hold arbitrary attributes. It may be
  562. initialized from a dictionary or with keyword arguments."""
  563. def __init__(*args, **kwargs): # noqa: B902
  564. self, args = args[0], args[1:]
  565. self.__attrs = dict(*args, **kwargs)
  566. def __getattribute__(self, name):
  567. # __class__ is needed for the awaitable check in async mode
  568. if name in {"_Namespace__attrs", "__class__"}:
  569. return object.__getattribute__(self, name)
  570. try:
  571. return self.__attrs[name]
  572. except KeyError:
  573. raise AttributeError(name)
  574. def __setitem__(self, name, value):
  575. self.__attrs[name] = value
  576. def __repr__(self):
  577. return "<Namespace %r>" % self.__attrs
  578. # does this python version support async for in and async generators?
  579. try:
  580. exec("async def _():\n async for _ in ():\n yield _")
  581. have_async_gen = True
  582. except SyntaxError:
  583. have_async_gen = False
  584. def soft_unicode(s):
  585. from markupsafe import soft_unicode
  586. warnings.warn(
  587. "'jinja2.utils.soft_unicode' will be removed in version 3.0."
  588. " Use 'markupsafe.soft_unicode' instead.",
  589. DeprecationWarning,
  590. stacklevel=2,
  591. )
  592. return soft_unicode(s)