utils.py 22 KB

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