utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2.utils
  4. ~~~~~~~~~~~~
  5. Utility functions.
  6. :copyright: (c) 2010 by the Jinja Team.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import re
  10. import errno
  11. from collections import deque
  12. from threading import Lock
  13. from jinja2._compat import text_type, string_types, implements_iterator, \
  14. url_quote
  15. _word_split_re = re.compile(r'(\s+)')
  16. _punctuation_re = re.compile(
  17. '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (
  18. '|'.join(map(re.escape, ('(', '<', '&lt;'))),
  19. '|'.join(map(re.escape, ('.', ',', ')', '>', '\n', '&gt;')))
  20. )
  21. )
  22. _simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')
  23. _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
  24. _entity_re = re.compile(r'&([^;]+);')
  25. _letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  26. _digits = '0123456789'
  27. # special singleton representing missing values for the runtime
  28. missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()
  29. # internal code
  30. internal_code = set()
  31. concat = u''.join
  32. def contextfunction(f):
  33. """This decorator can be used to mark a function or method context callable.
  34. A context callable is passed the active :class:`Context` as first argument when
  35. called from the template. This is useful if a function wants to get access
  36. to the context or functions provided on the context object. For example
  37. a function that returns a sorted list of template variables the current
  38. template exports could look like this::
  39. @contextfunction
  40. def get_exported_names(context):
  41. return sorted(context.exported_vars)
  42. """
  43. f.contextfunction = True
  44. return f
  45. def evalcontextfunction(f):
  46. """This decorator can be used to mark a function or method as an eval
  47. context callable. This is similar to the :func:`contextfunction`
  48. but instead of passing the context, an evaluation context object is
  49. passed. For more information about the eval context, see
  50. :ref:`eval-context`.
  51. .. versionadded:: 2.4
  52. """
  53. f.evalcontextfunction = True
  54. return f
  55. def environmentfunction(f):
  56. """This decorator can be used to mark a function or method as environment
  57. callable. This decorator works exactly like the :func:`contextfunction`
  58. decorator just that the first argument is the active :class:`Environment`
  59. and not context.
  60. """
  61. f.environmentfunction = True
  62. return f
  63. def internalcode(f):
  64. """Marks the function as internally used"""
  65. internal_code.add(f.__code__)
  66. return f
  67. def is_undefined(obj):
  68. """Check if the object passed is undefined. This does nothing more than
  69. performing an instance check against :class:`Undefined` but looks nicer.
  70. This can be used for custom filters or tests that want to react to
  71. undefined variables. For example a custom default filter can look like
  72. this::
  73. def default(var, default=''):
  74. if is_undefined(var):
  75. return default
  76. return var
  77. """
  78. from jinja2.runtime import Undefined
  79. return isinstance(obj, Undefined)
  80. def consume(iterable):
  81. """Consumes an iterable without doing anything with it."""
  82. for event in iterable:
  83. pass
  84. def clear_caches():
  85. """Jinja2 keeps internal caches for environments and lexers. These are
  86. used so that Jinja2 doesn't have to recreate environments and lexers all
  87. the time. Normally you don't have to care about that but if you are
  88. messuring memory consumption you may want to clean the caches.
  89. """
  90. from jinja2.environment import _spontaneous_environments
  91. from jinja2.lexer import _lexer_cache
  92. _spontaneous_environments.clear()
  93. _lexer_cache.clear()
  94. def import_string(import_name, silent=False):
  95. """Imports an object based on a string. This is useful if you want to
  96. use import paths as endpoints or something similar. An import path can
  97. be specified either in dotted notation (``xml.sax.saxutils.escape``)
  98. or with a colon as object delimiter (``xml.sax.saxutils:escape``).
  99. If the `silent` is True the return value will be `None` if the import
  100. fails.
  101. :return: imported object
  102. """
  103. try:
  104. if ':' in import_name:
  105. module, obj = import_name.split(':', 1)
  106. elif '.' in import_name:
  107. items = import_name.split('.')
  108. module = '.'.join(items[:-1])
  109. obj = items[-1]
  110. else:
  111. return __import__(import_name)
  112. return getattr(__import__(module, None, None, [obj]), obj)
  113. except (ImportError, AttributeError):
  114. if not silent:
  115. raise
  116. def open_if_exists(filename, mode='rb'):
  117. """Returns a file descriptor for the filename if that file exists,
  118. otherwise `None`.
  119. """
  120. try:
  121. return open(filename, mode)
  122. except IOError as e:
  123. if e.errno not in (errno.ENOENT, errno.EISDIR, errno.EINVAL):
  124. raise
  125. def object_type_repr(obj):
  126. """Returns the name of the object's type. For some recognized
  127. singletons the name of the object is returned instead. (For
  128. example for `None` and `Ellipsis`).
  129. """
  130. if obj is None:
  131. return 'None'
  132. elif obj is Ellipsis:
  133. return 'Ellipsis'
  134. # __builtin__ in 2.x, builtins in 3.x
  135. if obj.__class__.__module__ in ('__builtin__', 'builtins'):
  136. name = obj.__class__.__name__
  137. else:
  138. name = obj.__class__.__module__ + '.' + obj.__class__.__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, nofollow=False, 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 = lambda x, limit=trim_url_limit: limit is not None \
  162. and (x[:limit] + (len(x) >=limit and '...'
  163. or '')) or x
  164. words = _word_split_re.split(text_type(escape(text)))
  165. nofollow_attr = nofollow and ' rel="nofollow"' or ''
  166. if target is not None and isinstance(target, string_types):
  167. target_attr = ' target="%s"' % target
  168. else:
  169. target_attr = ''
  170. for i, word in enumerate(words):
  171. match = _punctuation_re.match(word)
  172. if match:
  173. lead, middle, trail = match.groups()
  174. if middle.startswith('www.') or (
  175. '@' not in middle and
  176. not middle.startswith('http://') and
  177. not middle.startswith('https://') and
  178. len(middle) > 0 and
  179. middle[0] in _letters + _digits and (
  180. middle.endswith('.org') or
  181. middle.endswith('.net') or
  182. middle.endswith('.com')
  183. )):
  184. middle = '<a href="http://%s"%s%s>%s</a>' % (middle,
  185. nofollow_attr, target_attr, trim_url(middle))
  186. if middle.startswith('http://') or \
  187. middle.startswith('https://'):
  188. middle = '<a href="%s"%s%s>%s</a>' % (middle,
  189. nofollow_attr, target_attr, trim_url(middle))
  190. if '@' in middle and not middle.startswith('www.') and \
  191. not ':' in middle and _simple_email_re.match(middle):
  192. middle = '<a href="mailto:%s">%s</a>' % (middle, middle)
  193. if lead + middle + trail != word:
  194. words[i] = lead + middle + trail
  195. return u''.join(words)
  196. def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
  197. """Generate some lorem ipsum for the template."""
  198. from jinja2.constants import LOREM_IPSUM_WORDS
  199. from random import choice, randrange
  200. words = LOREM_IPSUM_WORDS.split()
  201. result = []
  202. for _ in range(n):
  203. next_capitalized = True
  204. last_comma = last_fullstop = 0
  205. word = None
  206. last = None
  207. p = []
  208. # each paragraph contains out of 20 to 100 words.
  209. for idx, _ in enumerate(range(randrange(min, max))):
  210. while True:
  211. word = choice(words)
  212. if word != last:
  213. last = word
  214. break
  215. if next_capitalized:
  216. word = word.capitalize()
  217. next_capitalized = False
  218. # add commas
  219. if idx - randrange(3, 8) > last_comma:
  220. last_comma = idx
  221. last_fullstop += 2
  222. word += ','
  223. # add end of sentences
  224. if idx - randrange(10, 20) > last_fullstop:
  225. last_comma = last_fullstop = idx
  226. word += '.'
  227. next_capitalized = True
  228. p.append(word)
  229. # ensure that the paragraph ends with a dot.
  230. p = u' '.join(p)
  231. if p.endswith(','):
  232. p = p[:-1] + '.'
  233. elif not p.endswith('.'):
  234. p += '.'
  235. result.append(p)
  236. if not html:
  237. return u'\n\n'.join(result)
  238. return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))
  239. def unicode_urlencode(obj, charset='utf-8', for_qs=False):
  240. """URL escapes a single bytestring or unicode string with the
  241. given charset if applicable to URL safe quoting under all rules
  242. that need to be considered under all supported Python versions.
  243. If non strings are provided they are converted to their unicode
  244. representation first.
  245. """
  246. if not isinstance(obj, string_types):
  247. obj = text_type(obj)
  248. if isinstance(obj, text_type):
  249. obj = obj.encode(charset)
  250. safe = for_qs and b'' or b'/'
  251. rv = text_type(url_quote(obj, safe))
  252. if for_qs:
  253. rv = rv.replace('%20', '+')
  254. return rv
  255. class LRUCache(object):
  256. """A simple LRU Cache implementation."""
  257. # this is fast for small capacities (something below 1000) but doesn't
  258. # scale. But as long as it's only used as storage for templates this
  259. # won't do any harm.
  260. def __init__(self, capacity):
  261. self.capacity = capacity
  262. self._mapping = {}
  263. self._queue = deque()
  264. self._postinit()
  265. def _postinit(self):
  266. # alias all queue methods for faster lookup
  267. self._popleft = self._queue.popleft
  268. self._pop = self._queue.pop
  269. self._remove = self._queue.remove
  270. self._wlock = Lock()
  271. self._append = self._queue.append
  272. def __getstate__(self):
  273. return {
  274. 'capacity': self.capacity,
  275. '_mapping': self._mapping,
  276. '_queue': self._queue
  277. }
  278. def __setstate__(self, d):
  279. self.__dict__.update(d)
  280. self._postinit()
  281. def __getnewargs__(self):
  282. return (self.capacity,)
  283. def copy(self):
  284. """Return a shallow copy of the instance."""
  285. rv = self.__class__(self.capacity)
  286. rv._mapping.update(self._mapping)
  287. rv._queue = deque(self._queue)
  288. return rv
  289. def get(self, key, default=None):
  290. """Return an item from the cache dict or `default`"""
  291. try:
  292. return self[key]
  293. except KeyError:
  294. return default
  295. def setdefault(self, key, default=None):
  296. """Set `default` if the key is not in the cache otherwise
  297. leave unchanged. Return the value of this key.
  298. """
  299. self._wlock.acquire()
  300. try:
  301. try:
  302. return self[key]
  303. except KeyError:
  304. self[key] = default
  305. return default
  306. finally:
  307. self._wlock.release()
  308. def clear(self):
  309. """Clear the cache."""
  310. self._wlock.acquire()
  311. try:
  312. self._mapping.clear()
  313. self._queue.clear()
  314. finally:
  315. self._wlock.release()
  316. def __contains__(self, key):
  317. """Check if a key exists in this cache."""
  318. return key in self._mapping
  319. def __len__(self):
  320. """Return the current size of the cache."""
  321. return len(self._mapping)
  322. def __repr__(self):
  323. return '<%s %r>' % (
  324. self.__class__.__name__,
  325. self._mapping
  326. )
  327. def __getitem__(self, key):
  328. """Get an item from the cache. Moves the item up so that it has the
  329. highest priority then.
  330. Raise a `KeyError` if it does not exist.
  331. """
  332. self._wlock.acquire()
  333. try:
  334. rv = self._mapping[key]
  335. if self._queue[-1] != key:
  336. try:
  337. self._remove(key)
  338. except ValueError:
  339. # if something removed the key from the container
  340. # when we read, ignore the ValueError that we would
  341. # get otherwise.
  342. pass
  343. self._append(key)
  344. return rv
  345. finally:
  346. self._wlock.release()
  347. def __setitem__(self, key, value):
  348. """Sets the value for an item. Moves the item up so that it
  349. has the highest priority then.
  350. """
  351. self._wlock.acquire()
  352. try:
  353. if key in self._mapping:
  354. self._remove(key)
  355. elif len(self._mapping) == self.capacity:
  356. del self._mapping[self._popleft()]
  357. self._append(key)
  358. self._mapping[key] = value
  359. finally:
  360. self._wlock.release()
  361. def __delitem__(self, key):
  362. """Remove an item from the cache dict.
  363. Raise a `KeyError` if it does not exist.
  364. """
  365. self._wlock.acquire()
  366. try:
  367. del self._mapping[key]
  368. try:
  369. self._remove(key)
  370. except ValueError:
  371. # __getitem__ is not locked, it might happen
  372. pass
  373. finally:
  374. self._wlock.release()
  375. def items(self):
  376. """Return a list of items."""
  377. result = [(key, self._mapping[key]) for key in list(self._queue)]
  378. result.reverse()
  379. return result
  380. def iteritems(self):
  381. """Iterate over all items."""
  382. return iter(self.items())
  383. def values(self):
  384. """Return a list of all values."""
  385. return [x[1] for x in self.items()]
  386. def itervalue(self):
  387. """Iterate over all values."""
  388. return iter(self.values())
  389. def keys(self):
  390. """Return a list of all keys ordered by most recent usage."""
  391. return list(self)
  392. def iterkeys(self):
  393. """Iterate over all keys in the cache dict, ordered by
  394. the most recent usage.
  395. """
  396. return reversed(tuple(self._queue))
  397. __iter__ = iterkeys
  398. def __reversed__(self):
  399. """Iterate over the values in the cache dict, oldest items
  400. coming first.
  401. """
  402. return iter(tuple(self._queue))
  403. __copy__ = copy
  404. # register the LRU cache as mutable mapping if possible
  405. try:
  406. from collections import MutableMapping
  407. MutableMapping.register(LRUCache)
  408. except ImportError:
  409. pass
  410. @implements_iterator
  411. class Cycler(object):
  412. """A cycle helper for templates."""
  413. def __init__(self, *items):
  414. if not items:
  415. raise RuntimeError('at least one item has to be provided')
  416. self.items = items
  417. self.reset()
  418. def reset(self):
  419. """Resets the cycle."""
  420. self.pos = 0
  421. @property
  422. def current(self):
  423. """Returns the current item."""
  424. return self.items[self.pos]
  425. def __next__(self):
  426. """Goes one item ahead and returns it."""
  427. rv = self.current
  428. self.pos = (self.pos + 1) % len(self.items)
  429. return rv
  430. class Joiner(object):
  431. """A joining helper for templates."""
  432. def __init__(self, sep=u', '):
  433. self.sep = sep
  434. self.used = False
  435. def __call__(self):
  436. if not self.used:
  437. self.used = True
  438. return u''
  439. return self.sep
  440. # Imported here because that's where it was in the past
  441. from markupsafe import Markup, escape, soft_unicode