1
0

runtime.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. # -*- coding: utf-8 -*-
  2. """The runtime functions and state used by compiled templates."""
  3. import sys
  4. from itertools import chain
  5. from types import MethodType
  6. from markupsafe import escape # noqa: F401
  7. from markupsafe import Markup
  8. from markupsafe import soft_unicode
  9. from ._compat import abc
  10. from ._compat import imap
  11. from ._compat import implements_iterator
  12. from ._compat import implements_to_string
  13. from ._compat import iteritems
  14. from ._compat import PY2
  15. from ._compat import string_types
  16. from ._compat import text_type
  17. from ._compat import with_metaclass
  18. from .exceptions import TemplateNotFound # noqa: F401
  19. from .exceptions import TemplateRuntimeError # noqa: F401
  20. from .exceptions import UndefinedError
  21. from .nodes import EvalContext
  22. from .utils import concat
  23. from .utils import evalcontextfunction
  24. from .utils import internalcode
  25. from .utils import missing
  26. from .utils import Namespace # noqa: F401
  27. from .utils import object_type_repr
  28. # these variables are exported to the template runtime
  29. exported = [
  30. "LoopContext",
  31. "TemplateReference",
  32. "Macro",
  33. "Markup",
  34. "TemplateRuntimeError",
  35. "missing",
  36. "concat",
  37. "escape",
  38. "markup_join",
  39. "unicode_join",
  40. "to_string",
  41. "identity",
  42. "TemplateNotFound",
  43. "Namespace",
  44. "Undefined",
  45. ]
  46. #: the name of the function that is used to convert something into
  47. #: a string. We can just use the text type here.
  48. to_string = text_type
  49. def identity(x):
  50. """Returns its argument. Useful for certain things in the
  51. environment.
  52. """
  53. return x
  54. def markup_join(seq):
  55. """Concatenation that escapes if necessary and converts to unicode."""
  56. buf = []
  57. iterator = imap(soft_unicode, seq)
  58. for arg in iterator:
  59. buf.append(arg)
  60. if hasattr(arg, "__html__"):
  61. return Markup(u"").join(chain(buf, iterator))
  62. return concat(buf)
  63. def unicode_join(seq):
  64. """Simple args to unicode conversion and concatenation."""
  65. return concat(imap(text_type, seq))
  66. def new_context(
  67. environment,
  68. template_name,
  69. blocks,
  70. vars=None,
  71. shared=None,
  72. globals=None,
  73. locals=None,
  74. ):
  75. """Internal helper for context creation."""
  76. if vars is None:
  77. vars = {}
  78. if shared:
  79. parent = vars
  80. else:
  81. parent = dict(globals or (), **vars)
  82. if locals:
  83. # if the parent is shared a copy should be created because
  84. # we don't want to modify the dict passed
  85. if shared:
  86. parent = dict(parent)
  87. for key, value in iteritems(locals):
  88. if value is not missing:
  89. parent[key] = value
  90. return environment.context_class(environment, parent, template_name, blocks)
  91. class TemplateReference(object):
  92. """The `self` in templates."""
  93. def __init__(self, context):
  94. self.__context = context
  95. def __getitem__(self, name):
  96. blocks = self.__context.blocks[name]
  97. return BlockReference(name, self.__context, blocks, 0)
  98. def __repr__(self):
  99. return "<%s %r>" % (self.__class__.__name__, self.__context.name)
  100. def _get_func(x):
  101. return getattr(x, "__func__", x)
  102. class ContextMeta(type):
  103. def __new__(mcs, name, bases, d):
  104. rv = type.__new__(mcs, name, bases, d)
  105. if bases == ():
  106. return rv
  107. resolve = _get_func(rv.resolve)
  108. default_resolve = _get_func(Context.resolve)
  109. resolve_or_missing = _get_func(rv.resolve_or_missing)
  110. default_resolve_or_missing = _get_func(Context.resolve_or_missing)
  111. # If we have a changed resolve but no changed default or missing
  112. # resolve we invert the call logic.
  113. if (
  114. resolve is not default_resolve
  115. and resolve_or_missing is default_resolve_or_missing
  116. ):
  117. rv._legacy_resolve_mode = True
  118. elif (
  119. resolve is default_resolve
  120. and resolve_or_missing is default_resolve_or_missing
  121. ):
  122. rv._fast_resolve_mode = True
  123. return rv
  124. def resolve_or_missing(context, key, missing=missing):
  125. if key in context.vars:
  126. return context.vars[key]
  127. if key in context.parent:
  128. return context.parent[key]
  129. return missing
  130. class Context(with_metaclass(ContextMeta)):
  131. """The template context holds the variables of a template. It stores the
  132. values passed to the template and also the names the template exports.
  133. Creating instances is neither supported nor useful as it's created
  134. automatically at various stages of the template evaluation and should not
  135. be created by hand.
  136. The context is immutable. Modifications on :attr:`parent` **must not**
  137. happen and modifications on :attr:`vars` are allowed from generated
  138. template code only. Template filters and global functions marked as
  139. :func:`contextfunction`\\s get the active context passed as first argument
  140. and are allowed to access the context read-only.
  141. The template context supports read only dict operations (`get`,
  142. `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
  143. `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
  144. method that doesn't fail with a `KeyError` but returns an
  145. :class:`Undefined` object for missing variables.
  146. """
  147. # XXX: we want to eventually make this be a deprecation warning and
  148. # remove it.
  149. _legacy_resolve_mode = False
  150. _fast_resolve_mode = False
  151. def __init__(self, environment, parent, name, blocks):
  152. self.parent = parent
  153. self.vars = {}
  154. self.environment = environment
  155. self.eval_ctx = EvalContext(self.environment, name)
  156. self.exported_vars = set()
  157. self.name = name
  158. # create the initial mapping of blocks. Whenever template inheritance
  159. # takes place the runtime will update this mapping with the new blocks
  160. # from the template.
  161. self.blocks = dict((k, [v]) for k, v in iteritems(blocks))
  162. # In case we detect the fast resolve mode we can set up an alias
  163. # here that bypasses the legacy code logic.
  164. if self._fast_resolve_mode:
  165. self.resolve_or_missing = MethodType(resolve_or_missing, self)
  166. def super(self, name, current):
  167. """Render a parent block."""
  168. try:
  169. blocks = self.blocks[name]
  170. index = blocks.index(current) + 1
  171. blocks[index]
  172. except LookupError:
  173. return self.environment.undefined(
  174. "there is no parent block called %r." % name, name="super"
  175. )
  176. return BlockReference(name, self, blocks, index)
  177. def get(self, key, default=None):
  178. """Returns an item from the template context, if it doesn't exist
  179. `default` is returned.
  180. """
  181. try:
  182. return self[key]
  183. except KeyError:
  184. return default
  185. def resolve(self, key):
  186. """Looks up a variable like `__getitem__` or `get` but returns an
  187. :class:`Undefined` object with the name of the name looked up.
  188. """
  189. if self._legacy_resolve_mode:
  190. rv = resolve_or_missing(self, key)
  191. else:
  192. rv = self.resolve_or_missing(key)
  193. if rv is missing:
  194. return self.environment.undefined(name=key)
  195. return rv
  196. def resolve_or_missing(self, key):
  197. """Resolves a variable like :meth:`resolve` but returns the
  198. special `missing` value if it cannot be found.
  199. """
  200. if self._legacy_resolve_mode:
  201. rv = self.resolve(key)
  202. if isinstance(rv, Undefined):
  203. rv = missing
  204. return rv
  205. return resolve_or_missing(self, key)
  206. def get_exported(self):
  207. """Get a new dict with the exported variables."""
  208. return dict((k, self.vars[k]) for k in self.exported_vars)
  209. def get_all(self):
  210. """Return the complete context as dict including the exported
  211. variables. For optimizations reasons this might not return an
  212. actual copy so be careful with using it.
  213. """
  214. if not self.vars:
  215. return self.parent
  216. if not self.parent:
  217. return self.vars
  218. return dict(self.parent, **self.vars)
  219. @internalcode
  220. def call(__self, __obj, *args, **kwargs): # noqa: B902
  221. """Call the callable with the arguments and keyword arguments
  222. provided but inject the active context or environment as first
  223. argument if the callable is a :func:`contextfunction` or
  224. :func:`environmentfunction`.
  225. """
  226. if __debug__:
  227. __traceback_hide__ = True # noqa
  228. # Allow callable classes to take a context
  229. if hasattr(__obj, "__call__"): # noqa: B004
  230. fn = __obj.__call__
  231. for fn_type in (
  232. "contextfunction",
  233. "evalcontextfunction",
  234. "environmentfunction",
  235. ):
  236. if hasattr(fn, fn_type):
  237. __obj = fn
  238. break
  239. if callable(__obj):
  240. if getattr(__obj, "contextfunction", False) is True:
  241. args = (__self,) + args
  242. elif getattr(__obj, "evalcontextfunction", False) is True:
  243. args = (__self.eval_ctx,) + args
  244. elif getattr(__obj, "environmentfunction", False) is True:
  245. args = (__self.environment,) + args
  246. try:
  247. return __obj(*args, **kwargs)
  248. except StopIteration:
  249. return __self.environment.undefined(
  250. "value was undefined because "
  251. "a callable raised a "
  252. "StopIteration exception"
  253. )
  254. def derived(self, locals=None):
  255. """Internal helper function to create a derived context. This is
  256. used in situations where the system needs a new context in the same
  257. template that is independent.
  258. """
  259. context = new_context(
  260. self.environment, self.name, {}, self.get_all(), True, None, locals
  261. )
  262. context.eval_ctx = self.eval_ctx
  263. context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))
  264. return context
  265. def _all(meth): # noqa: B902
  266. def proxy(self):
  267. return getattr(self.get_all(), meth)()
  268. proxy.__doc__ = getattr(dict, meth).__doc__
  269. proxy.__name__ = meth
  270. return proxy
  271. keys = _all("keys")
  272. values = _all("values")
  273. items = _all("items")
  274. # not available on python 3
  275. if PY2:
  276. iterkeys = _all("iterkeys")
  277. itervalues = _all("itervalues")
  278. iteritems = _all("iteritems")
  279. del _all
  280. def __contains__(self, name):
  281. return name in self.vars or name in self.parent
  282. def __getitem__(self, key):
  283. """Lookup a variable or raise `KeyError` if the variable is
  284. undefined.
  285. """
  286. item = self.resolve_or_missing(key)
  287. if item is missing:
  288. raise KeyError(key)
  289. return item
  290. def __repr__(self):
  291. return "<%s %s of %r>" % (
  292. self.__class__.__name__,
  293. repr(self.get_all()),
  294. self.name,
  295. )
  296. abc.Mapping.register(Context)
  297. class BlockReference(object):
  298. """One block on a template reference."""
  299. def __init__(self, name, context, stack, depth):
  300. self.name = name
  301. self._context = context
  302. self._stack = stack
  303. self._depth = depth
  304. @property
  305. def super(self):
  306. """Super the block."""
  307. if self._depth + 1 >= len(self._stack):
  308. return self._context.environment.undefined(
  309. "there is no parent block called %r." % self.name, name="super"
  310. )
  311. return BlockReference(self.name, self._context, self._stack, self._depth + 1)
  312. @internalcode
  313. def __call__(self):
  314. rv = concat(self._stack[self._depth](self._context))
  315. if self._context.eval_ctx.autoescape:
  316. rv = Markup(rv)
  317. return rv
  318. @implements_iterator
  319. class LoopContext:
  320. """A wrapper iterable for dynamic ``for`` loops, with information
  321. about the loop and iteration.
  322. """
  323. #: Current iteration of the loop, starting at 0.
  324. index0 = -1
  325. _length = None
  326. _after = missing
  327. _current = missing
  328. _before = missing
  329. _last_changed_value = missing
  330. def __init__(self, iterable, undefined, recurse=None, depth0=0):
  331. """
  332. :param iterable: Iterable to wrap.
  333. :param undefined: :class:`Undefined` class to use for next and
  334. previous items.
  335. :param recurse: The function to render the loop body when the
  336. loop is marked recursive.
  337. :param depth0: Incremented when looping recursively.
  338. """
  339. self._iterable = iterable
  340. self._iterator = self._to_iterator(iterable)
  341. self._undefined = undefined
  342. self._recurse = recurse
  343. #: How many levels deep a recursive loop currently is, starting at 0.
  344. self.depth0 = depth0
  345. @staticmethod
  346. def _to_iterator(iterable):
  347. return iter(iterable)
  348. @property
  349. def length(self):
  350. """Length of the iterable.
  351. If the iterable is a generator or otherwise does not have a
  352. size, it is eagerly evaluated to get a size.
  353. """
  354. if self._length is not None:
  355. return self._length
  356. try:
  357. self._length = len(self._iterable)
  358. except TypeError:
  359. iterable = list(self._iterator)
  360. self._iterator = self._to_iterator(iterable)
  361. self._length = len(iterable) + self.index + (self._after is not missing)
  362. return self._length
  363. def __len__(self):
  364. return self.length
  365. @property
  366. def depth(self):
  367. """How many levels deep a recursive loop currently is, starting at 1."""
  368. return self.depth0 + 1
  369. @property
  370. def index(self):
  371. """Current iteration of the loop, starting at 1."""
  372. return self.index0 + 1
  373. @property
  374. def revindex0(self):
  375. """Number of iterations from the end of the loop, ending at 0.
  376. Requires calculating :attr:`length`.
  377. """
  378. return self.length - self.index
  379. @property
  380. def revindex(self):
  381. """Number of iterations from the end of the loop, ending at 1.
  382. Requires calculating :attr:`length`.
  383. """
  384. return self.length - self.index0
  385. @property
  386. def first(self):
  387. """Whether this is the first iteration of the loop."""
  388. return self.index0 == 0
  389. def _peek_next(self):
  390. """Return the next element in the iterable, or :data:`missing`
  391. if the iterable is exhausted. Only peeks one item ahead, caching
  392. the result in :attr:`_last` for use in subsequent checks. The
  393. cache is reset when :meth:`__next__` is called.
  394. """
  395. if self._after is not missing:
  396. return self._after
  397. self._after = next(self._iterator, missing)
  398. return self._after
  399. @property
  400. def last(self):
  401. """Whether this is the last iteration of the loop.
  402. Causes the iterable to advance early. See
  403. :func:`itertools.groupby` for issues this can cause.
  404. The :func:`groupby` filter avoids that issue.
  405. """
  406. return self._peek_next() is missing
  407. @property
  408. def previtem(self):
  409. """The item in the previous iteration. Undefined during the
  410. first iteration.
  411. """
  412. if self.first:
  413. return self._undefined("there is no previous item")
  414. return self._before
  415. @property
  416. def nextitem(self):
  417. """The item in the next iteration. Undefined during the last
  418. iteration.
  419. Causes the iterable to advance early. See
  420. :func:`itertools.groupby` for issues this can cause.
  421. The :func:`groupby` filter avoids that issue.
  422. """
  423. rv = self._peek_next()
  424. if rv is missing:
  425. return self._undefined("there is no next item")
  426. return rv
  427. def cycle(self, *args):
  428. """Return a value from the given args, cycling through based on
  429. the current :attr:`index0`.
  430. :param args: One or more values to cycle through.
  431. """
  432. if not args:
  433. raise TypeError("no items for cycling given")
  434. return args[self.index0 % len(args)]
  435. def changed(self, *value):
  436. """Return ``True`` if previously called with a different value
  437. (including when called for the first time).
  438. :param value: One or more values to compare to the last call.
  439. """
  440. if self._last_changed_value != value:
  441. self._last_changed_value = value
  442. return True
  443. return False
  444. def __iter__(self):
  445. return self
  446. def __next__(self):
  447. if self._after is not missing:
  448. rv = self._after
  449. self._after = missing
  450. else:
  451. rv = next(self._iterator)
  452. self.index0 += 1
  453. self._before = self._current
  454. self._current = rv
  455. return rv, self
  456. @internalcode
  457. def __call__(self, iterable):
  458. """When iterating over nested data, render the body of the loop
  459. recursively with the given inner iterable data.
  460. The loop must have the ``recursive`` marker for this to work.
  461. """
  462. if self._recurse is None:
  463. raise TypeError(
  464. "The loop must have the 'recursive' marker to be called recursively."
  465. )
  466. return self._recurse(iterable, self._recurse, depth=self.depth)
  467. def __repr__(self):
  468. return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)
  469. class Macro(object):
  470. """Wraps a macro function."""
  471. def __init__(
  472. self,
  473. environment,
  474. func,
  475. name,
  476. arguments,
  477. catch_kwargs,
  478. catch_varargs,
  479. caller,
  480. default_autoescape=None,
  481. ):
  482. self._environment = environment
  483. self._func = func
  484. self._argument_count = len(arguments)
  485. self.name = name
  486. self.arguments = arguments
  487. self.catch_kwargs = catch_kwargs
  488. self.catch_varargs = catch_varargs
  489. self.caller = caller
  490. self.explicit_caller = "caller" in arguments
  491. if default_autoescape is None:
  492. default_autoescape = environment.autoescape
  493. self._default_autoescape = default_autoescape
  494. @internalcode
  495. @evalcontextfunction
  496. def __call__(self, *args, **kwargs):
  497. # This requires a bit of explanation, In the past we used to
  498. # decide largely based on compile-time information if a macro is
  499. # safe or unsafe. While there was a volatile mode it was largely
  500. # unused for deciding on escaping. This turns out to be
  501. # problematic for macros because whether a macro is safe depends not
  502. # on the escape mode when it was defined, but rather when it was used.
  503. #
  504. # Because however we export macros from the module system and
  505. # there are historic callers that do not pass an eval context (and
  506. # will continue to not pass one), we need to perform an instance
  507. # check here.
  508. #
  509. # This is considered safe because an eval context is not a valid
  510. # argument to callables otherwise anyway. Worst case here is
  511. # that if no eval context is passed we fall back to the compile
  512. # time autoescape flag.
  513. if args and isinstance(args[0], EvalContext):
  514. autoescape = args[0].autoescape
  515. args = args[1:]
  516. else:
  517. autoescape = self._default_autoescape
  518. # try to consume the positional arguments
  519. arguments = list(args[: self._argument_count])
  520. off = len(arguments)
  521. # For information why this is necessary refer to the handling
  522. # of caller in the `macro_body` handler in the compiler.
  523. found_caller = False
  524. # if the number of arguments consumed is not the number of
  525. # arguments expected we start filling in keyword arguments
  526. # and defaults.
  527. if off != self._argument_count:
  528. for name in self.arguments[len(arguments) :]:
  529. try:
  530. value = kwargs.pop(name)
  531. except KeyError:
  532. value = missing
  533. if name == "caller":
  534. found_caller = True
  535. arguments.append(value)
  536. else:
  537. found_caller = self.explicit_caller
  538. # it's important that the order of these arguments does not change
  539. # if not also changed in the compiler's `function_scoping` method.
  540. # the order is caller, keyword arguments, positional arguments!
  541. if self.caller and not found_caller:
  542. caller = kwargs.pop("caller", None)
  543. if caller is None:
  544. caller = self._environment.undefined("No caller defined", name="caller")
  545. arguments.append(caller)
  546. if self.catch_kwargs:
  547. arguments.append(kwargs)
  548. elif kwargs:
  549. if "caller" in kwargs:
  550. raise TypeError(
  551. "macro %r was invoked with two values for "
  552. "the special caller argument. This is "
  553. "most likely a bug." % self.name
  554. )
  555. raise TypeError(
  556. "macro %r takes no keyword argument %r"
  557. % (self.name, next(iter(kwargs)))
  558. )
  559. if self.catch_varargs:
  560. arguments.append(args[self._argument_count :])
  561. elif len(args) > self._argument_count:
  562. raise TypeError(
  563. "macro %r takes not more than %d argument(s)"
  564. % (self.name, len(self.arguments))
  565. )
  566. return self._invoke(arguments, autoescape)
  567. def _invoke(self, arguments, autoescape):
  568. """This method is being swapped out by the async implementation."""
  569. rv = self._func(*arguments)
  570. if autoescape:
  571. rv = Markup(rv)
  572. return rv
  573. def __repr__(self):
  574. return "<%s %s>" % (
  575. self.__class__.__name__,
  576. self.name is None and "anonymous" or repr(self.name),
  577. )
  578. @implements_to_string
  579. class Undefined(object):
  580. """The default undefined type. This undefined type can be printed and
  581. iterated over, but every other access will raise an :exc:`UndefinedError`:
  582. >>> foo = Undefined(name='foo')
  583. >>> str(foo)
  584. ''
  585. >>> not foo
  586. True
  587. >>> foo + 42
  588. Traceback (most recent call last):
  589. ...
  590. jinja2.exceptions.UndefinedError: 'foo' is undefined
  591. """
  592. __slots__ = (
  593. "_undefined_hint",
  594. "_undefined_obj",
  595. "_undefined_name",
  596. "_undefined_exception",
  597. )
  598. def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):
  599. self._undefined_hint = hint
  600. self._undefined_obj = obj
  601. self._undefined_name = name
  602. self._undefined_exception = exc
  603. @property
  604. def _undefined_message(self):
  605. """Build a message about the undefined value based on how it was
  606. accessed.
  607. """
  608. if self._undefined_hint:
  609. return self._undefined_hint
  610. if self._undefined_obj is missing:
  611. return "%r is undefined" % self._undefined_name
  612. if not isinstance(self._undefined_name, string_types):
  613. return "%s has no element %r" % (
  614. object_type_repr(self._undefined_obj),
  615. self._undefined_name,
  616. )
  617. return "%r has no attribute %r" % (
  618. object_type_repr(self._undefined_obj),
  619. self._undefined_name,
  620. )
  621. @internalcode
  622. def _fail_with_undefined_error(self, *args, **kwargs):
  623. """Raise an :exc:`UndefinedError` when operations are performed
  624. on the undefined value.
  625. """
  626. raise self._undefined_exception(self._undefined_message)
  627. @internalcode
  628. def __getattr__(self, name):
  629. if name[:2] == "__":
  630. raise AttributeError(name)
  631. return self._fail_with_undefined_error()
  632. __add__ = (
  633. __radd__
  634. ) = (
  635. __mul__
  636. ) = (
  637. __rmul__
  638. ) = (
  639. __div__
  640. ) = (
  641. __rdiv__
  642. ) = (
  643. __truediv__
  644. ) = (
  645. __rtruediv__
  646. ) = (
  647. __floordiv__
  648. ) = (
  649. __rfloordiv__
  650. ) = (
  651. __mod__
  652. ) = (
  653. __rmod__
  654. ) = (
  655. __pos__
  656. ) = (
  657. __neg__
  658. ) = (
  659. __call__
  660. ) = (
  661. __getitem__
  662. ) = (
  663. __lt__
  664. ) = (
  665. __le__
  666. ) = (
  667. __gt__
  668. ) = (
  669. __ge__
  670. ) = (
  671. __int__
  672. ) = (
  673. __float__
  674. ) = (
  675. __complex__
  676. ) = __pow__ = __rpow__ = __sub__ = __rsub__ = _fail_with_undefined_error
  677. def __eq__(self, other):
  678. return type(self) is type(other)
  679. def __ne__(self, other):
  680. return not self.__eq__(other)
  681. def __hash__(self):
  682. return id(type(self))
  683. def __str__(self):
  684. return u""
  685. def __len__(self):
  686. return 0
  687. def __iter__(self):
  688. if 0:
  689. yield None
  690. def __nonzero__(self):
  691. return False
  692. __bool__ = __nonzero__
  693. def __repr__(self):
  694. return "Undefined"
  695. def make_logging_undefined(logger=None, base=None):
  696. """Given a logger object this returns a new undefined class that will
  697. log certain failures. It will log iterations and printing. If no
  698. logger is given a default logger is created.
  699. Example::
  700. logger = logging.getLogger(__name__)
  701. LoggingUndefined = make_logging_undefined(
  702. logger=logger,
  703. base=Undefined
  704. )
  705. .. versionadded:: 2.8
  706. :param logger: the logger to use. If not provided, a default logger
  707. is created.
  708. :param base: the base class to add logging functionality to. This
  709. defaults to :class:`Undefined`.
  710. """
  711. if logger is None:
  712. import logging
  713. logger = logging.getLogger(__name__)
  714. logger.addHandler(logging.StreamHandler(sys.stderr))
  715. if base is None:
  716. base = Undefined
  717. def _log_message(undef):
  718. if undef._undefined_hint is None:
  719. if undef._undefined_obj is missing:
  720. hint = "%s is undefined" % undef._undefined_name
  721. elif not isinstance(undef._undefined_name, string_types):
  722. hint = "%s has no element %s" % (
  723. object_type_repr(undef._undefined_obj),
  724. undef._undefined_name,
  725. )
  726. else:
  727. hint = "%s has no attribute %s" % (
  728. object_type_repr(undef._undefined_obj),
  729. undef._undefined_name,
  730. )
  731. else:
  732. hint = undef._undefined_hint
  733. logger.warning("Template variable warning: %s", hint)
  734. class LoggingUndefined(base):
  735. def _fail_with_undefined_error(self, *args, **kwargs):
  736. try:
  737. return base._fail_with_undefined_error(self, *args, **kwargs)
  738. except self._undefined_exception as e:
  739. logger.error("Template variable error: %s", str(e))
  740. raise e
  741. def __str__(self):
  742. rv = base.__str__(self)
  743. _log_message(self)
  744. return rv
  745. def __iter__(self):
  746. rv = base.__iter__(self)
  747. _log_message(self)
  748. return rv
  749. if PY2:
  750. def __nonzero__(self):
  751. rv = base.__nonzero__(self)
  752. _log_message(self)
  753. return rv
  754. def __unicode__(self):
  755. rv = base.__unicode__(self)
  756. _log_message(self)
  757. return rv
  758. else:
  759. def __bool__(self):
  760. rv = base.__bool__(self)
  761. _log_message(self)
  762. return rv
  763. return LoggingUndefined
  764. # No @implements_to_string decorator here because __str__
  765. # is not overwritten from Undefined in this class.
  766. # This would cause a recursion error in Python 2.
  767. class ChainableUndefined(Undefined):
  768. """An undefined that is chainable, where both ``__getattr__`` and
  769. ``__getitem__`` return itself rather than raising an
  770. :exc:`UndefinedError`.
  771. >>> foo = ChainableUndefined(name='foo')
  772. >>> str(foo.bar['baz'])
  773. ''
  774. >>> foo.bar['baz'] + 42
  775. Traceback (most recent call last):
  776. ...
  777. jinja2.exceptions.UndefinedError: 'foo' is undefined
  778. .. versionadded:: 2.11.0
  779. """
  780. __slots__ = ()
  781. def __html__(self):
  782. return self.__str__()
  783. def __getattr__(self, _):
  784. return self
  785. __getitem__ = __getattr__
  786. @implements_to_string
  787. class DebugUndefined(Undefined):
  788. """An undefined that returns the debug info when printed.
  789. >>> foo = DebugUndefined(name='foo')
  790. >>> str(foo)
  791. '{{ foo }}'
  792. >>> not foo
  793. True
  794. >>> foo + 42
  795. Traceback (most recent call last):
  796. ...
  797. jinja2.exceptions.UndefinedError: 'foo' is undefined
  798. """
  799. __slots__ = ()
  800. def __str__(self):
  801. if self._undefined_hint is None:
  802. if self._undefined_obj is missing:
  803. return u"{{ %s }}" % self._undefined_name
  804. return "{{ no such element: %s[%r] }}" % (
  805. object_type_repr(self._undefined_obj),
  806. self._undefined_name,
  807. )
  808. return u"{{ undefined value printed: %s }}" % self._undefined_hint
  809. @implements_to_string
  810. class StrictUndefined(Undefined):
  811. """An undefined that barks on print and iteration as well as boolean
  812. tests and all kinds of comparisons. In other words: you can do nothing
  813. with it except checking if it's defined using the `defined` test.
  814. >>> foo = StrictUndefined(name='foo')
  815. >>> str(foo)
  816. Traceback (most recent call last):
  817. ...
  818. jinja2.exceptions.UndefinedError: 'foo' is undefined
  819. >>> not foo
  820. Traceback (most recent call last):
  821. ...
  822. jinja2.exceptions.UndefinedError: 'foo' is undefined
  823. >>> foo + 42
  824. Traceback (most recent call last):
  825. ...
  826. jinja2.exceptions.UndefinedError: 'foo' is undefined
  827. """
  828. __slots__ = ()
  829. __iter__ = (
  830. __str__
  831. ) = (
  832. __len__
  833. ) = (
  834. __nonzero__
  835. ) = __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error
  836. # remove remaining slots attributes, after the metaclass did the magic they
  837. # are unneeded and irritating as they contain wrong data for the subclasses.
  838. del (
  839. Undefined.__slots__,
  840. ChainableUndefined.__slots__,
  841. DebugUndefined.__slots__,
  842. StrictUndefined.__slots__,
  843. )