PageRenderTime 54ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/test/rql_test/connections/http_support/jinja2/utils.py

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