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.

647 lines
20 KiB

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