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.

1675 lines
60KB

  1. """Classes for managing templates and their runtime and compile time
  2. options.
  3. """
  4. import os
  5. import sys
  6. import typing
  7. import typing as t
  8. import weakref
  9. from collections import ChainMap
  10. from functools import lru_cache
  11. from functools import partial
  12. from functools import reduce
  13. from types import CodeType
  14. from markupsafe import Markup
  15. from . import nodes
  16. from .compiler import CodeGenerator
  17. from .compiler import generate
  18. from .defaults import BLOCK_END_STRING
  19. from .defaults import BLOCK_START_STRING
  20. from .defaults import COMMENT_END_STRING
  21. from .defaults import COMMENT_START_STRING
  22. from .defaults import DEFAULT_FILTERS
  23. from .defaults import DEFAULT_NAMESPACE
  24. from .defaults import DEFAULT_POLICIES
  25. from .defaults import DEFAULT_TESTS
  26. from .defaults import KEEP_TRAILING_NEWLINE
  27. from .defaults import LINE_COMMENT_PREFIX
  28. from .defaults import LINE_STATEMENT_PREFIX
  29. from .defaults import LSTRIP_BLOCKS
  30. from .defaults import NEWLINE_SEQUENCE
  31. from .defaults import TRIM_BLOCKS
  32. from .defaults import VARIABLE_END_STRING
  33. from .defaults import VARIABLE_START_STRING
  34. from .exceptions import TemplateNotFound
  35. from .exceptions import TemplateRuntimeError
  36. from .exceptions import TemplatesNotFound
  37. from .exceptions import TemplateSyntaxError
  38. from .exceptions import UndefinedError
  39. from .lexer import get_lexer
  40. from .lexer import Lexer
  41. from .lexer import TokenStream
  42. from .nodes import EvalContext
  43. from .parser import Parser
  44. from .runtime import Context
  45. from .runtime import new_context
  46. from .runtime import Undefined
  47. from .utils import _PassArg
  48. from .utils import concat
  49. from .utils import consume
  50. from .utils import import_string
  51. from .utils import internalcode
  52. from .utils import LRUCache
  53. from .utils import missing
  54. if t.TYPE_CHECKING:
  55. import typing_extensions as te
  56. from .bccache import BytecodeCache
  57. from .ext import Extension
  58. from .loaders import BaseLoader
  59. _env_bound = t.TypeVar("_env_bound", bound="Environment")
  60. # for direct template usage we have up to ten living environments
  61. @lru_cache(maxsize=10)
  62. def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_bound:
  63. """Return a new spontaneous environment. A spontaneous environment
  64. is used for templates created directly rather than through an
  65. existing environment.
  66. :param cls: Environment class to create.
  67. :param args: Positional arguments passed to environment.
  68. """
  69. env = cls(*args)
  70. env.shared = True
  71. return env
  72. def create_cache(
  73. size: int,
  74. ) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:
  75. """Return the cache class for the given size."""
  76. if size == 0:
  77. return None
  78. if size < 0:
  79. return {}
  80. return LRUCache(size) # type: ignore
  81. def copy_cache(
  82. cache: t.Optional[t.MutableMapping],
  83. ) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:
  84. """Create an empty copy of the given cache."""
  85. if cache is None:
  86. return None
  87. if type(cache) is dict:
  88. return {}
  89. return LRUCache(cache.capacity) # type: ignore
  90. def load_extensions(
  91. environment: "Environment",
  92. extensions: t.Sequence[t.Union[str, t.Type["Extension"]]],
  93. ) -> t.Dict[str, "Extension"]:
  94. """Load the extensions from the list and bind it to the environment.
  95. Returns a dict of instantiated extensions.
  96. """
  97. result = {}
  98. for extension in extensions:
  99. if isinstance(extension, str):
  100. extension = t.cast(t.Type["Extension"], import_string(extension))
  101. result[extension.identifier] = extension(environment)
  102. return result
  103. def _environment_config_check(environment: "Environment") -> "Environment":
  104. """Perform a sanity check on the environment."""
  105. assert issubclass(
  106. environment.undefined, Undefined
  107. ), "'undefined' must be a subclass of 'jinja2.Undefined'."
  108. assert (
  109. environment.block_start_string
  110. != environment.variable_start_string
  111. != environment.comment_start_string
  112. ), "block, variable and comment start strings must be different."
  113. assert environment.newline_sequence in {
  114. "\r",
  115. "\r\n",
  116. "\n",
  117. }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'."
  118. return environment
  119. class Environment:
  120. r"""The core component of Jinja is the `Environment`. It contains
  121. important shared variables like configuration, filters, tests,
  122. globals and others. Instances of this class may be modified if
  123. they are not shared and if no template was loaded so far.
  124. Modifications on environments after the first template was loaded
  125. will lead to surprising effects and undefined behavior.
  126. Here are the possible initialization parameters:
  127. `block_start_string`
  128. The string marking the beginning of a block. Defaults to ``'{%'``.
  129. `block_end_string`
  130. The string marking the end of a block. Defaults to ``'%}'``.
  131. `variable_start_string`
  132. The string marking the beginning of a print statement.
  133. Defaults to ``'{{'``.
  134. `variable_end_string`
  135. The string marking the end of a print statement. Defaults to
  136. ``'}}'``.
  137. `comment_start_string`
  138. The string marking the beginning of a comment. Defaults to ``'{#'``.
  139. `comment_end_string`
  140. The string marking the end of a comment. Defaults to ``'#}'``.
  141. `line_statement_prefix`
  142. If given and a string, this will be used as prefix for line based
  143. statements. See also :ref:`line-statements`.
  144. `line_comment_prefix`
  145. If given and a string, this will be used as prefix for line based
  146. comments. See also :ref:`line-statements`.
  147. .. versionadded:: 2.2
  148. `trim_blocks`
  149. If this is set to ``True`` the first newline after a block is
  150. removed (block, not variable tag!). Defaults to `False`.
  151. `lstrip_blocks`
  152. If this is set to ``True`` leading spaces and tabs are stripped
  153. from the start of a line to a block. Defaults to `False`.
  154. `newline_sequence`
  155. The sequence that starts a newline. Must be one of ``'\r'``,
  156. ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
  157. useful default for Linux and OS X systems as well as web
  158. applications.
  159. `keep_trailing_newline`
  160. Preserve the trailing newline when rendering templates.
  161. The default is ``False``, which causes a single newline,
  162. if present, to be stripped from the end of the template.
  163. .. versionadded:: 2.7
  164. `extensions`
  165. List of Jinja extensions to use. This can either be import paths
  166. as strings or extension classes. For more information have a
  167. look at :ref:`the extensions documentation <jinja-extensions>`.
  168. `optimized`
  169. should the optimizer be enabled? Default is ``True``.
  170. `undefined`
  171. :class:`Undefined` or a subclass of it that is used to represent
  172. undefined values in the template.
  173. `finalize`
  174. A callable that can be used to process the result of a variable
  175. expression before it is output. For example one can convert
  176. ``None`` implicitly into an empty string here.
  177. `autoescape`
  178. If set to ``True`` the XML/HTML autoescaping feature is enabled by
  179. default. For more details about autoescaping see
  180. :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also
  181. be a callable that is passed the template name and has to
  182. return ``True`` or ``False`` depending on autoescape should be
  183. enabled by default.
  184. .. versionchanged:: 2.4
  185. `autoescape` can now be a function
  186. `loader`
  187. The template loader for this environment.
  188. `cache_size`
  189. The size of the cache. Per default this is ``400`` which means
  190. that if more than 400 templates are loaded the loader will clean
  191. out the least recently used template. If the cache size is set to
  192. ``0`` templates are recompiled all the time, if the cache size is
  193. ``-1`` the cache will not be cleaned.
  194. .. versionchanged:: 2.8
  195. The cache size was increased to 400 from a low 50.
  196. `auto_reload`
  197. Some loaders load templates from locations where the template
  198. sources may change (ie: file system or database). If
  199. ``auto_reload`` is set to ``True`` (default) every time a template is
  200. requested the loader checks if the source changed and if yes, it
  201. will reload the template. For higher performance it's possible to
  202. disable that.
  203. `bytecode_cache`
  204. If set to a bytecode cache object, this object will provide a
  205. cache for the internal Jinja bytecode so that templates don't
  206. have to be parsed if they were not changed.
  207. See :ref:`bytecode-cache` for more information.
  208. `enable_async`
  209. If set to true this enables async template execution which
  210. allows using async functions and generators.
  211. """
  212. #: if this environment is sandboxed. Modifying this variable won't make
  213. #: the environment sandboxed though. For a real sandboxed environment
  214. #: have a look at jinja2.sandbox. This flag alone controls the code
  215. #: generation by the compiler.
  216. sandboxed = False
  217. #: True if the environment is just an overlay
  218. overlayed = False
  219. #: the environment this environment is linked to if it is an overlay
  220. linked_to: t.Optional["Environment"] = None
  221. #: shared environments have this set to `True`. A shared environment
  222. #: must not be modified
  223. shared = False
  224. #: the class that is used for code generation. See
  225. #: :class:`~jinja2.compiler.CodeGenerator` for more information.
  226. code_generator_class: t.Type["CodeGenerator"] = CodeGenerator
  227. #: the context class that is used for templates. See
  228. #: :class:`~jinja2.runtime.Context` for more information.
  229. context_class: t.Type[Context] = Context
  230. template_class: t.Type["Template"]
  231. def __init__(
  232. self,
  233. block_start_string: str = BLOCK_START_STRING,
  234. block_end_string: str = BLOCK_END_STRING,
  235. variable_start_string: str = VARIABLE_START_STRING,
  236. variable_end_string: str = VARIABLE_END_STRING,
  237. comment_start_string: str = COMMENT_START_STRING,
  238. comment_end_string: str = COMMENT_END_STRING,
  239. line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,
  240. line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,
  241. trim_blocks: bool = TRIM_BLOCKS,
  242. lstrip_blocks: bool = LSTRIP_BLOCKS,
  243. newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,
  244. keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,
  245. extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),
  246. optimized: bool = True,
  247. undefined: t.Type[Undefined] = Undefined,
  248. finalize: t.Optional[t.Callable[..., t.Any]] = None,
  249. autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,
  250. loader: t.Optional["BaseLoader"] = None,
  251. cache_size: int = 400,
  252. auto_reload: bool = True,
  253. bytecode_cache: t.Optional["BytecodeCache"] = None,
  254. enable_async: bool = False,
  255. ):
  256. # !!Important notice!!
  257. # The constructor accepts quite a few arguments that should be
  258. # passed by keyword rather than position. However it's important to
  259. # not change the order of arguments because it's used at least
  260. # internally in those cases:
  261. # - spontaneous environments (i18n extension and Template)
  262. # - unittests
  263. # If parameter changes are required only add parameters at the end
  264. # and don't change the arguments (or the defaults!) of the arguments
  265. # existing already.
  266. # lexer / parser information
  267. self.block_start_string = block_start_string
  268. self.block_end_string = block_end_string
  269. self.variable_start_string = variable_start_string
  270. self.variable_end_string = variable_end_string
  271. self.comment_start_string = comment_start_string
  272. self.comment_end_string = comment_end_string
  273. self.line_statement_prefix = line_statement_prefix
  274. self.line_comment_prefix = line_comment_prefix
  275. self.trim_blocks = trim_blocks
  276. self.lstrip_blocks = lstrip_blocks
  277. self.newline_sequence = newline_sequence
  278. self.keep_trailing_newline = keep_trailing_newline
  279. # runtime information
  280. self.undefined: t.Type[Undefined] = undefined
  281. self.optimized = optimized
  282. self.finalize = finalize
  283. self.autoescape = autoescape
  284. # defaults
  285. self.filters = DEFAULT_FILTERS.copy()
  286. self.tests = DEFAULT_TESTS.copy()
  287. self.globals = DEFAULT_NAMESPACE.copy()
  288. # set the loader provided
  289. self.loader = loader
  290. self.cache = create_cache(cache_size)
  291. self.bytecode_cache = bytecode_cache
  292. self.auto_reload = auto_reload
  293. # configurable policies
  294. self.policies = DEFAULT_POLICIES.copy()
  295. # load extensions
  296. self.extensions = load_extensions(self, extensions)
  297. self.is_async = enable_async
  298. _environment_config_check(self)
  299. def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None:
  300. """Adds an extension after the environment was created.
  301. .. versionadded:: 2.5
  302. """
  303. self.extensions.update(load_extensions(self, [extension]))
  304. def extend(self, **attributes: t.Any) -> None:
  305. """Add the items to the instance of the environment if they do not exist
  306. yet. This is used by :ref:`extensions <writing-extensions>` to register
  307. callbacks and configuration values without breaking inheritance.
  308. """
  309. for key, value in attributes.items():
  310. if not hasattr(self, key):
  311. setattr(self, key, value)
  312. def overlay(
  313. self,
  314. block_start_string: str = missing,
  315. block_end_string: str = missing,
  316. variable_start_string: str = missing,
  317. variable_end_string: str = missing,
  318. comment_start_string: str = missing,
  319. comment_end_string: str = missing,
  320. line_statement_prefix: t.Optional[str] = missing,
  321. line_comment_prefix: t.Optional[str] = missing,
  322. trim_blocks: bool = missing,
  323. lstrip_blocks: bool = missing,
  324. extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing,
  325. optimized: bool = missing,
  326. undefined: t.Type[Undefined] = missing,
  327. finalize: t.Optional[t.Callable[..., t.Any]] = missing,
  328. autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing,
  329. loader: t.Optional["BaseLoader"] = missing,
  330. cache_size: int = missing,
  331. auto_reload: bool = missing,
  332. bytecode_cache: t.Optional["BytecodeCache"] = missing,
  333. ) -> "Environment":
  334. """Create a new overlay environment that shares all the data with the
  335. current environment except for cache and the overridden attributes.
  336. Extensions cannot be removed for an overlayed environment. An overlayed
  337. environment automatically gets all the extensions of the environment it
  338. is linked to plus optional extra extensions.
  339. Creating overlays should happen after the initial environment was set
  340. up completely. Not all attributes are truly linked, some are just
  341. copied over so modifications on the original environment may not shine
  342. through.
  343. """
  344. args = dict(locals())
  345. del args["self"], args["cache_size"], args["extensions"]
  346. rv = object.__new__(self.__class__)
  347. rv.__dict__.update(self.__dict__)
  348. rv.overlayed = True
  349. rv.linked_to = self
  350. for key, value in args.items():
  351. if value is not missing:
  352. setattr(rv, key, value)
  353. if cache_size is not missing:
  354. rv.cache = create_cache(cache_size)
  355. else:
  356. rv.cache = copy_cache(self.cache)
  357. rv.extensions = {}
  358. for key, value in self.extensions.items():
  359. rv.extensions[key] = value.bind(rv)
  360. if extensions is not missing:
  361. rv.extensions.update(load_extensions(rv, extensions))
  362. return _environment_config_check(rv)
  363. @property
  364. def lexer(self) -> Lexer:
  365. """The lexer for this environment."""
  366. return get_lexer(self)
  367. def iter_extensions(self) -> t.Iterator["Extension"]:
  368. """Iterates over the extensions by priority."""
  369. return iter(sorted(self.extensions.values(), key=lambda x: x.priority))
  370. def getitem(
  371. self, obj: t.Any, argument: t.Union[str, t.Any]
  372. ) -> t.Union[t.Any, Undefined]:
  373. """Get an item or attribute of an object but prefer the item."""
  374. try:
  375. return obj[argument]
  376. except (AttributeError, TypeError, LookupError):
  377. if isinstance(argument, str):
  378. try:
  379. attr = str(argument)
  380. except Exception:
  381. pass
  382. else:
  383. try:
  384. return getattr(obj, attr)
  385. except AttributeError:
  386. pass
  387. return self.undefined(obj=obj, name=argument)
  388. def getattr(self, obj: t.Any, attribute: str) -> t.Any:
  389. """Get an item or attribute of an object but prefer the attribute.
  390. Unlike :meth:`getitem` the attribute *must* be a string.
  391. """
  392. try:
  393. return getattr(obj, attribute)
  394. except AttributeError:
  395. pass
  396. try:
  397. return obj[attribute]
  398. except (TypeError, LookupError, AttributeError):
  399. return self.undefined(obj=obj, name=attribute)
  400. def _filter_test_common(
  401. self,
  402. name: t.Union[str, Undefined],
  403. value: t.Any,
  404. args: t.Optional[t.Sequence[t.Any]],
  405. kwargs: t.Optional[t.Mapping[str, t.Any]],
  406. context: t.Optional[Context],
  407. eval_ctx: t.Optional[EvalContext],
  408. is_filter: bool,
  409. ) -> t.Any:
  410. if is_filter:
  411. env_map = self.filters
  412. type_name = "filter"
  413. else:
  414. env_map = self.tests
  415. type_name = "test"
  416. func = env_map.get(name) # type: ignore
  417. if func is None:
  418. msg = f"No {type_name} named {name!r}."
  419. if isinstance(name, Undefined):
  420. try:
  421. name._fail_with_undefined_error()
  422. except Exception as e:
  423. msg = f"{msg} ({e}; did you forget to quote the callable name?)"
  424. raise TemplateRuntimeError(msg)
  425. args = [value, *(args if args is not None else ())]
  426. kwargs = kwargs if kwargs is not None else {}
  427. pass_arg = _PassArg.from_obj(func)
  428. if pass_arg is _PassArg.context:
  429. if context is None:
  430. raise TemplateRuntimeError(
  431. f"Attempted to invoke a context {type_name} without context."
  432. )
  433. args.insert(0, context)
  434. elif pass_arg is _PassArg.eval_context:
  435. if eval_ctx is None:
  436. if context is not None:
  437. eval_ctx = context.eval_ctx
  438. else:
  439. eval_ctx = EvalContext(self)
  440. args.insert(0, eval_ctx)
  441. elif pass_arg is _PassArg.environment:
  442. args.insert(0, self)
  443. return func(*args, **kwargs)
  444. def call_filter(
  445. self,
  446. name: str,
  447. value: t.Any,
  448. args: t.Optional[t.Sequence[t.Any]] = None,
  449. kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
  450. context: t.Optional[Context] = None,
  451. eval_ctx: t.Optional[EvalContext] = None,
  452. ) -> t.Any:
  453. """Invoke a filter on a value the same way the compiler does.
  454. This might return a coroutine if the filter is running from an
  455. environment in async mode and the filter supports async
  456. execution. It's your responsibility to await this if needed.
  457. .. versionadded:: 2.7
  458. """
  459. return self._filter_test_common(
  460. name, value, args, kwargs, context, eval_ctx, True
  461. )
  462. def call_test(
  463. self,
  464. name: str,
  465. value: t.Any,
  466. args: t.Optional[t.Sequence[t.Any]] = None,
  467. kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
  468. context: t.Optional[Context] = None,
  469. eval_ctx: t.Optional[EvalContext] = None,
  470. ) -> t.Any:
  471. """Invoke a test on a value the same way the compiler does.
  472. This might return a coroutine if the test is running from an
  473. environment in async mode and the test supports async execution.
  474. It's your responsibility to await this if needed.
  475. .. versionchanged:: 3.0
  476. Tests support ``@pass_context``, etc. decorators. Added
  477. the ``context`` and ``eval_ctx`` parameters.
  478. .. versionadded:: 2.7
  479. """
  480. return self._filter_test_common(
  481. name, value, args, kwargs, context, eval_ctx, False
  482. )
  483. @internalcode
  484. def parse(
  485. self,
  486. source: str,
  487. name: t.Optional[str] = None,
  488. filename: t.Optional[str] = None,
  489. ) -> nodes.Template:
  490. """Parse the sourcecode and return the abstract syntax tree. This
  491. tree of nodes is used by the compiler to convert the template into
  492. executable source- or bytecode. This is useful for debugging or to
  493. extract information from templates.
  494. If you are :ref:`developing Jinja extensions <writing-extensions>`
  495. this gives you a good overview of the node tree generated.
  496. """
  497. try:
  498. return self._parse(source, name, filename)
  499. except TemplateSyntaxError:
  500. self.handle_exception(source=source)
  501. def _parse(
  502. self, source: str, name: t.Optional[str], filename: t.Optional[str]
  503. ) -> nodes.Template:
  504. """Internal parsing function used by `parse` and `compile`."""
  505. return Parser(self, source, name, filename).parse()
  506. def lex(
  507. self,
  508. source: str,
  509. name: t.Optional[str] = None,
  510. filename: t.Optional[str] = None,
  511. ) -> t.Iterator[t.Tuple[int, str, str]]:
  512. """Lex the given sourcecode and return a generator that yields
  513. tokens as tuples in the form ``(lineno, token_type, value)``.
  514. This can be useful for :ref:`extension development <writing-extensions>`
  515. and debugging templates.
  516. This does not perform preprocessing. If you want the preprocessing
  517. of the extensions to be applied you have to filter source through
  518. the :meth:`preprocess` method.
  519. """
  520. source = str(source)
  521. try:
  522. return self.lexer.tokeniter(source, name, filename)
  523. except TemplateSyntaxError:
  524. self.handle_exception(source=source)
  525. def preprocess(
  526. self,
  527. source: str,
  528. name: t.Optional[str] = None,
  529. filename: t.Optional[str] = None,
  530. ) -> str:
  531. """Preprocesses the source with all extensions. This is automatically
  532. called for all parsing and compiling methods but *not* for :meth:`lex`
  533. because there you usually only want the actual source tokenized.
  534. """
  535. return reduce(
  536. lambda s, e: e.preprocess(s, name, filename),
  537. self.iter_extensions(),
  538. str(source),
  539. )
  540. def _tokenize(
  541. self,
  542. source: str,
  543. name: t.Optional[str],
  544. filename: t.Optional[str] = None,
  545. state: t.Optional[str] = None,
  546. ) -> TokenStream:
  547. """Called by the parser to do the preprocessing and filtering
  548. for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
  549. """
  550. source = self.preprocess(source, name, filename)
  551. stream = self.lexer.tokenize(source, name, filename, state)
  552. for ext in self.iter_extensions():
  553. stream = ext.filter_stream(stream) # type: ignore
  554. if not isinstance(stream, TokenStream):
  555. stream = TokenStream(stream, name, filename) # type: ignore
  556. return stream
  557. def _generate(
  558. self,
  559. source: nodes.Template,
  560. name: t.Optional[str],
  561. filename: t.Optional[str],
  562. defer_init: bool = False,
  563. ) -> str:
  564. """Internal hook that can be overridden to hook a different generate
  565. method in.
  566. .. versionadded:: 2.5
  567. """
  568. return generate( # type: ignore
  569. source,
  570. self,
  571. name,
  572. filename,
  573. defer_init=defer_init,
  574. optimized=self.optimized,
  575. )
  576. def _compile(self, source: str, filename: str) -> CodeType:
  577. """Internal hook that can be overridden to hook a different compile
  578. method in.
  579. .. versionadded:: 2.5
  580. """
  581. return compile(source, filename, "exec") # type: ignore
  582. @typing.overload
  583. def compile( # type: ignore
  584. self,
  585. source: t.Union[str, nodes.Template],
  586. name: t.Optional[str] = None,
  587. filename: t.Optional[str] = None,
  588. raw: "te.Literal[False]" = False,
  589. defer_init: bool = False,
  590. ) -> CodeType:
  591. ...
  592. @typing.overload
  593. def compile(
  594. self,
  595. source: t.Union[str, nodes.Template],
  596. name: t.Optional[str] = None,
  597. filename: t.Optional[str] = None,
  598. raw: "te.Literal[True]" = ...,
  599. defer_init: bool = False,
  600. ) -> str:
  601. ...
  602. @internalcode
  603. def compile(
  604. self,
  605. source: t.Union[str, nodes.Template],
  606. name: t.Optional[str] = None,
  607. filename: t.Optional[str] = None,
  608. raw: bool = False,
  609. defer_init: bool = False,
  610. ) -> t.Union[str, CodeType]:
  611. """Compile a node or template source code. The `name` parameter is
  612. the load name of the template after it was joined using
  613. :meth:`join_path` if necessary, not the filename on the file system.
  614. the `filename` parameter is the estimated filename of the template on
  615. the file system. If the template came from a database or memory this
  616. can be omitted.
  617. The return value of this method is a python code object. If the `raw`
  618. parameter is `True` the return value will be a string with python
  619. code equivalent to the bytecode returned otherwise. This method is
  620. mainly used internally.
  621. `defer_init` is use internally to aid the module code generator. This
  622. causes the generated code to be able to import without the global
  623. environment variable to be set.
  624. .. versionadded:: 2.4
  625. `defer_init` parameter added.
  626. """
  627. source_hint = None
  628. try:
  629. if isinstance(source, str):
  630. source_hint = source
  631. source = self._parse(source, name, filename)
  632. source = self._generate(source, name, filename, defer_init=defer_init)
  633. if raw:
  634. return source
  635. if filename is None:
  636. filename = "<template>"
  637. return self._compile(source, filename)
  638. except TemplateSyntaxError:
  639. self.handle_exception(source=source_hint)
  640. def compile_expression(
  641. self, source: str, undefined_to_none: bool = True
  642. ) -> "TemplateExpression":
  643. """A handy helper method that returns a callable that accepts keyword
  644. arguments that appear as variables in the expression. If called it
  645. returns the result of the expression.
  646. This is useful if applications want to use the same rules as Jinja
  647. in template "configuration files" or similar situations.
  648. Example usage:
  649. >>> env = Environment()
  650. >>> expr = env.compile_expression('foo == 42')
  651. >>> expr(foo=23)
  652. False
  653. >>> expr(foo=42)
  654. True
  655. Per default the return value is converted to `None` if the
  656. expression returns an undefined value. This can be changed
  657. by setting `undefined_to_none` to `False`.
  658. >>> env.compile_expression('var')() is None
  659. True
  660. >>> env.compile_expression('var', undefined_to_none=False)()
  661. Undefined
  662. .. versionadded:: 2.1
  663. """
  664. parser = Parser(self, source, state="variable")
  665. try:
  666. expr = parser.parse_expression()
  667. if not parser.stream.eos:
  668. raise TemplateSyntaxError(
  669. "chunk after expression", parser.stream.current.lineno, None, None
  670. )
  671. expr.set_environment(self)
  672. except TemplateSyntaxError:
  673. self.handle_exception(source=source)
  674. body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]
  675. template = self.from_string(nodes.Template(body, lineno=1))
  676. return TemplateExpression(template, undefined_to_none)
  677. def compile_templates(
  678. self,
  679. target: t.Union[str, os.PathLike],
  680. extensions: t.Optional[t.Collection[str]] = None,
  681. filter_func: t.Optional[t.Callable[[str], bool]] = None,
  682. zip: t.Optional[str] = "deflated",
  683. log_function: t.Optional[t.Callable[[str], None]] = None,
  684. ignore_errors: bool = True,
  685. ) -> None:
  686. """Finds all the templates the loader can find, compiles them
  687. and stores them in `target`. If `zip` is `None`, instead of in a
  688. zipfile, the templates will be stored in a directory.
  689. By default a deflate zip algorithm is used. To switch to
  690. the stored algorithm, `zip` can be set to ``'stored'``.
  691. `extensions` and `filter_func` are passed to :meth:`list_templates`.
  692. Each template returned will be compiled to the target folder or
  693. zipfile.
  694. By default template compilation errors are ignored. In case a
  695. log function is provided, errors are logged. If you want template
  696. syntax errors to abort the compilation you can set `ignore_errors`
  697. to `False` and you will get an exception on syntax errors.
  698. .. versionadded:: 2.4
  699. """
  700. from .loaders import ModuleLoader
  701. if log_function is None:
  702. def log_function(x: str) -> None:
  703. pass
  704. assert log_function is not None
  705. assert self.loader is not None, "No loader configured."
  706. def write_file(filename: str, data: str) -> None:
  707. if zip:
  708. info = ZipInfo(filename)
  709. info.external_attr = 0o755 << 16
  710. zip_file.writestr(info, data)
  711. else:
  712. with open(os.path.join(target, filename), "wb") as f:
  713. f.write(data.encode("utf8"))
  714. if zip is not None:
  715. from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED
  716. zip_file = ZipFile(
  717. target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]
  718. )
  719. log_function(f"Compiling into Zip archive {target!r}")
  720. else:
  721. if not os.path.isdir(target):
  722. os.makedirs(target)
  723. log_function(f"Compiling into folder {target!r}")
  724. try:
  725. for name in self.list_templates(extensions, filter_func):
  726. source, filename, _ = self.loader.get_source(self, name)
  727. try:
  728. code = self.compile(source, name, filename, True, True)
  729. except TemplateSyntaxError as e:
  730. if not ignore_errors:
  731. raise
  732. log_function(f'Could not compile "{name}": {e}')
  733. continue
  734. filename = ModuleLoader.get_module_filename(name)
  735. write_file(filename, code)
  736. log_function(f'Compiled "{name}" as {filename}')
  737. finally:
  738. if zip:
  739. zip_file.close()
  740. log_function("Finished compiling templates")
  741. def list_templates(
  742. self,
  743. extensions: t.Optional[t.Collection[str]] = None,
  744. filter_func: t.Optional[t.Callable[[str], bool]] = None,
  745. ) -> t.List[str]:
  746. """Returns a list of templates for this environment. This requires
  747. that the loader supports the loader's
  748. :meth:`~BaseLoader.list_templates` method.
  749. If there are other files in the template folder besides the
  750. actual templates, the returned list can be filtered. There are two
  751. ways: either `extensions` is set to a list of file extensions for
  752. templates, or a `filter_func` can be provided which is a callable that
  753. is passed a template name and should return `True` if it should end up
  754. in the result list.
  755. If the loader does not support that, a :exc:`TypeError` is raised.
  756. .. versionadded:: 2.4
  757. """
  758. assert self.loader is not None, "No loader configured."
  759. names = self.loader.list_templates()
  760. if extensions is not None:
  761. if filter_func is not None:
  762. raise TypeError(
  763. "either extensions or filter_func can be passed, but not both"
  764. )
  765. def filter_func(x: str) -> bool:
  766. return "." in x and x.rsplit(".", 1)[1] in extensions # type: ignore
  767. if filter_func is not None:
  768. names = [name for name in names if filter_func(name)]
  769. return names
  770. def handle_exception(self, source: t.Optional[str] = None) -> "te.NoReturn":
  771. """Exception handling helper. This is used internally to either raise
  772. rewritten exceptions or return a rendered traceback for the template.
  773. """
  774. from .debug import rewrite_traceback_stack
  775. raise rewrite_traceback_stack(source=source)
  776. def join_path(self, template: str, parent: str) -> str:
  777. """Join a template with the parent. By default all the lookups are
  778. relative to the loader root so this method returns the `template`
  779. parameter unchanged, but if the paths should be relative to the
  780. parent template, this function can be used to calculate the real
  781. template name.
  782. Subclasses may override this method and implement template path
  783. joining here.
  784. """
  785. return template
  786. @internalcode
  787. def _load_template(
  788. self, name: str, globals: t.Optional[t.Mapping[str, t.Any]]
  789. ) -> "Template":
  790. if self.loader is None:
  791. raise TypeError("no loader for this environment specified")
  792. cache_key = (weakref.ref(self.loader), name)
  793. if self.cache is not None:
  794. template = self.cache.get(cache_key)
  795. if template is not None and (
  796. not self.auto_reload or template.is_up_to_date
  797. ):
  798. # template.globals is a ChainMap, modifying it will only
  799. # affect the template, not the environment globals.
  800. if globals:
  801. template.globals.update(globals)
  802. return template
  803. template = self.loader.load(self, name, self.make_globals(globals))
  804. if self.cache is not None:
  805. self.cache[cache_key] = template
  806. return template
  807. @internalcode
  808. def get_template(
  809. self,
  810. name: t.Union[str, "Template"],
  811. parent: t.Optional[str] = None,
  812. globals: t.Optional[t.Mapping[str, t.Any]] = None,
  813. ) -> "Template":
  814. """Load a template by name with :attr:`loader` and return a
  815. :class:`Template`. If the template does not exist a
  816. :exc:`TemplateNotFound` exception is raised.
  817. :param name: Name of the template to load.
  818. :param parent: The name of the parent template importing this
  819. template. :meth:`join_path` can be used to implement name
  820. transformations with this.
  821. :param globals: Extend the environment :attr:`globals` with
  822. these extra variables available for all renders of this
  823. template. If the template has already been loaded and
  824. cached, its globals are updated with any new items.
  825. .. versionchanged:: 3.0
  826. If a template is loaded from cache, ``globals`` will update
  827. the template's globals instead of ignoring the new values.
  828. .. versionchanged:: 2.4
  829. If ``name`` is a :class:`Template` object it is returned
  830. unchanged.
  831. """
  832. if isinstance(name, Template):
  833. return name
  834. if parent is not None:
  835. name = self.join_path(name, parent)
  836. return self._load_template(name, globals)
  837. @internalcode
  838. def select_template(
  839. self,
  840. names: t.Iterable[t.Union[str, "Template"]],
  841. parent: t.Optional[str] = None,
  842. globals: t.Optional[t.Mapping[str, t.Any]] = None,
  843. ) -> "Template":
  844. """Like :meth:`get_template`, but tries loading multiple names.
  845. If none of the names can be loaded a :exc:`TemplatesNotFound`
  846. exception is raised.
  847. :param names: List of template names to try loading in order.
  848. :param parent: The name of the parent template importing this
  849. template. :meth:`join_path` can be used to implement name
  850. transformations with this.
  851. :param globals: Extend the environment :attr:`globals` with
  852. these extra variables available for all renders of this
  853. template. If the template has already been loaded and
  854. cached, its globals are updated with any new items.
  855. .. versionchanged:: 3.0
  856. If a template is loaded from cache, ``globals`` will update
  857. the template's globals instead of ignoring the new values.
  858. .. versionchanged:: 2.11
  859. If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`
  860. is raised instead. If no templates were found and ``names``
  861. contains :class:`Undefined`, the message is more helpful.
  862. .. versionchanged:: 2.4
  863. If ``names`` contains a :class:`Template` object it is
  864. returned unchanged.
  865. .. versionadded:: 2.3
  866. """
  867. if isinstance(names, Undefined):
  868. names._fail_with_undefined_error()
  869. if not names:
  870. raise TemplatesNotFound(
  871. message="Tried to select from an empty list of templates."
  872. )
  873. for name in names:
  874. if isinstance(name, Template):
  875. return name
  876. if parent is not None:
  877. name = self.join_path(name, parent)
  878. try:
  879. return self._load_template(name, globals)
  880. except (TemplateNotFound, UndefinedError):
  881. pass
  882. raise TemplatesNotFound(names) # type: ignore
  883. @internalcode
  884. def get_or_select_template(
  885. self,
  886. template_name_or_list: t.Union[
  887. str, "Template", t.List[t.Union[str, "Template"]]
  888. ],
  889. parent: t.Optional[str] = None,
  890. globals: t.Optional[t.Mapping[str, t.Any]] = None,
  891. ) -> "Template":
  892. """Use :meth:`select_template` if an iterable of template names
  893. is given, or :meth:`get_template` if one name is given.
  894. .. versionadded:: 2.3
  895. """
  896. if isinstance(template_name_or_list, (str, Undefined)):
  897. return self.get_template(template_name_or_list, parent, globals)
  898. elif isinstance(template_name_or_list, Template):
  899. return template_name_or_list
  900. return self.select_template(template_name_or_list, parent, globals)
  901. def from_string(
  902. self,
  903. source: t.Union[str, nodes.Template],
  904. globals: t.Optional[t.Mapping[str, t.Any]] = None,
  905. template_class: t.Optional[t.Type["Template"]] = None,
  906. ) -> "Template":
  907. """Load a template from a source string without using
  908. :attr:`loader`.
  909. :param source: Jinja source to compile into a template.
  910. :param globals: Extend the environment :attr:`globals` with
  911. these extra variables available for all renders of this
  912. template. If the template has already been loaded and
  913. cached, its globals are updated with any new items.
  914. :param template_class: Return an instance of this
  915. :class:`Template` class.
  916. """
  917. gs = self.make_globals(globals)
  918. cls = template_class or self.template_class
  919. return cls.from_code(self, self.compile(source), gs, None)
  920. def make_globals(
  921. self, d: t.Optional[t.Mapping[str, t.Any]]
  922. ) -> t.MutableMapping[str, t.Any]:
  923. """Make the globals map for a template. Any given template
  924. globals overlay the environment :attr:`globals`.
  925. Returns a :class:`collections.ChainMap`. This allows any changes
  926. to a template's globals to only affect that template, while
  927. changes to the environment's globals are still reflected.
  928. However, avoid modifying any globals after a template is loaded.
  929. :param d: Dict of template-specific globals.
  930. .. versionchanged:: 3.0
  931. Use :class:`collections.ChainMap` to always prevent mutating
  932. environment globals.
  933. """
  934. if d is None:
  935. d = {}
  936. return ChainMap(d, self.globals)
  937. class Template:
  938. """The central template object. This class represents a compiled template
  939. and is used to evaluate it.
  940. Normally the template object is generated from an :class:`Environment` but
  941. it also has a constructor that makes it possible to create a template
  942. instance directly using the constructor. It takes the same arguments as
  943. the environment constructor but it's not possible to specify a loader.
  944. Every template object has a few methods and members that are guaranteed
  945. to exist. However it's important that a template object should be
  946. considered immutable. Modifications on the object are not supported.
  947. Template objects created from the constructor rather than an environment
  948. do have an `environment` attribute that points to a temporary environment
  949. that is probably shared with other templates created with the constructor
  950. and compatible settings.
  951. >>> template = Template('Hello {{ name }}!')
  952. >>> template.render(name='John Doe') == u'Hello John Doe!'
  953. True
  954. >>> stream = template.stream(name='John Doe')
  955. >>> next(stream) == u'Hello John Doe!'
  956. True
  957. >>> next(stream)
  958. Traceback (most recent call last):
  959. ...
  960. StopIteration
  961. """
  962. #: Type of environment to create when creating a template directly
  963. #: rather than through an existing environment.
  964. environment_class: t.Type[Environment] = Environment
  965. environment: Environment
  966. globals: t.MutableMapping[str, t.Any]
  967. name: t.Optional[str]
  968. filename: t.Optional[str]
  969. blocks: t.Dict[str, t.Callable[[Context], t.Iterator[str]]]
  970. root_render_func: t.Callable[[Context], t.Iterator[str]]
  971. _module: t.Optional["TemplateModule"]
  972. _debug_info: str
  973. _uptodate: t.Optional[t.Callable[[], bool]]
  974. def __new__(
  975. cls,
  976. source: t.Union[str, nodes.Template],
  977. block_start_string: str = BLOCK_START_STRING,
  978. block_end_string: str = BLOCK_END_STRING,
  979. variable_start_string: str = VARIABLE_START_STRING,
  980. variable_end_string: str = VARIABLE_END_STRING,
  981. comment_start_string: str = COMMENT_START_STRING,
  982. comment_end_string: str = COMMENT_END_STRING,
  983. line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,
  984. line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,
  985. trim_blocks: bool = TRIM_BLOCKS,
  986. lstrip_blocks: bool = LSTRIP_BLOCKS,
  987. newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,
  988. keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,
  989. extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),
  990. optimized: bool = True,
  991. undefined: t.Type[Undefined] = Undefined,
  992. finalize: t.Optional[t.Callable[..., t.Any]] = None,
  993. autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,
  994. enable_async: bool = False,
  995. ) -> t.Any: # it returns a `Template`, but this breaks the sphinx build...
  996. env = get_spontaneous_environment(
  997. cls.environment_class, # type: ignore
  998. block_start_string,
  999. block_end_string,
  1000. variable_start_string,
  1001. variable_end_string,
  1002. comment_start_string,
  1003. comment_end_string,
  1004. line_statement_prefix,
  1005. line_comment_prefix,
  1006. trim_blocks,
  1007. lstrip_blocks,
  1008. newline_sequence,
  1009. keep_trailing_newline,
  1010. frozenset(extensions),
  1011. optimized,
  1012. undefined, # type: ignore
  1013. finalize,
  1014. autoescape,
  1015. None,
  1016. 0,
  1017. False,
  1018. None,
  1019. enable_async,
  1020. )
  1021. return env.from_string(source, template_class=cls)
  1022. @classmethod
  1023. def from_code(
  1024. cls,
  1025. environment: Environment,
  1026. code: CodeType,
  1027. globals: t.MutableMapping[str, t.Any],
  1028. uptodate: t.Optional[t.Callable[[], bool]] = None,
  1029. ) -> "Template":
  1030. """Creates a template object from compiled code and the globals. This
  1031. is used by the loaders and environment to create a template object.
  1032. """
  1033. namespace = {"environment": environment, "__file__": code.co_filename}
  1034. exec(code, namespace)
  1035. rv = cls._from_namespace(environment, namespace, globals)
  1036. rv._uptodate = uptodate
  1037. return rv
  1038. @classmethod
  1039. def from_module_dict(
  1040. cls,
  1041. environment: Environment,
  1042. module_dict: t.MutableMapping[str, t.Any],
  1043. globals: t.MutableMapping[str, t.Any],
  1044. ) -> "Template":
  1045. """Creates a template object from a module. This is used by the
  1046. module loader to create a template object.
  1047. .. versionadded:: 2.4
  1048. """
  1049. return cls._from_namespace(environment, module_dict, globals)
  1050. @classmethod
  1051. def _from_namespace(
  1052. cls,
  1053. environment: Environment,
  1054. namespace: t.MutableMapping[str, t.Any],
  1055. globals: t.MutableMapping[str, t.Any],
  1056. ) -> "Template":
  1057. t: "Template" = object.__new__(cls)
  1058. t.environment = environment
  1059. t.globals = globals
  1060. t.name = namespace["name"]
  1061. t.filename = namespace["__file__"]
  1062. t.blocks = namespace["blocks"]
  1063. # render function and module
  1064. t.root_render_func = namespace["root"] # type: ignore
  1065. t._module = None
  1066. # debug and loader helpers
  1067. t._debug_info = namespace["debug_info"]
  1068. t._uptodate = None
  1069. # store the reference
  1070. namespace["environment"] = environment
  1071. namespace["__jinja_template__"] = t
  1072. return t
  1073. def render(self, *args: t.Any, **kwargs: t.Any) -> str:
  1074. """This method accepts the same arguments as the `dict` constructor:
  1075. A dict, a dict subclass or some keyword arguments. If no arguments
  1076. are given the context will be empty. These two calls do the same::
  1077. template.render(knights='that say nih')
  1078. template.render({'knights': 'that say nih'})
  1079. This will return the rendered template as a string.
  1080. """
  1081. if self.environment.is_async:
  1082. import asyncio
  1083. close = False
  1084. if sys.version_info < (3, 7):
  1085. loop = asyncio.get_event_loop()
  1086. else:
  1087. try:
  1088. loop = asyncio.get_running_loop()
  1089. except RuntimeError:
  1090. loop = asyncio.new_event_loop()
  1091. close = True
  1092. try:
  1093. return loop.run_until_complete(self.render_async(*args, **kwargs))
  1094. finally:
  1095. if close:
  1096. loop.close()
  1097. ctx = self.new_context(dict(*args, **kwargs))
  1098. try:
  1099. return concat(self.root_render_func(ctx)) # type: ignore
  1100. except Exception:
  1101. self.environment.handle_exception()
  1102. async def render_async(self, *args: t.Any, **kwargs: t.Any) -> str:
  1103. """This works similar to :meth:`render` but returns a coroutine
  1104. that when awaited returns the entire rendered template string. This
  1105. requires the async feature to be enabled.
  1106. Example usage::
  1107. await template.render_async(knights='that say nih; asynchronously')
  1108. """
  1109. if not self.environment.is_async:
  1110. raise RuntimeError(
  1111. "The environment was not created with async mode enabled."
  1112. )
  1113. ctx = self.new_context(dict(*args, **kwargs))
  1114. try:
  1115. return concat([n async for n in self.root_render_func(ctx)]) # type: ignore
  1116. except Exception:
  1117. return self.environment.handle_exception()
  1118. def stream(self, *args: t.Any, **kwargs: t.Any) -> "TemplateStream":
  1119. """Works exactly like :meth:`generate` but returns a
  1120. :class:`TemplateStream`.
  1121. """
  1122. return TemplateStream(self.generate(*args, **kwargs))
  1123. def generate(self, *args: t.Any, **kwargs: t.Any) -> t.Iterator[str]:
  1124. """For very large templates it can be useful to not render the whole
  1125. template at once but evaluate each statement after another and yield
  1126. piece for piece. This method basically does exactly that and returns
  1127. a generator that yields one item after another as strings.
  1128. It accepts the same arguments as :meth:`render`.
  1129. """
  1130. if self.environment.is_async:
  1131. import asyncio
  1132. async def to_list() -> t.List[str]:
  1133. return [x async for x in self.generate_async(*args, **kwargs)]
  1134. if sys.version_info < (3, 7):
  1135. loop = asyncio.get_event_loop()
  1136. out = loop.run_until_complete(to_list())
  1137. else:
  1138. out = asyncio.run(to_list())
  1139. yield from out
  1140. return
  1141. ctx = self.new_context(dict(*args, **kwargs))
  1142. try:
  1143. yield from self.root_render_func(ctx) # type: ignore
  1144. except Exception:
  1145. yield self.environment.handle_exception()
  1146. async def generate_async(
  1147. self, *args: t.Any, **kwargs: t.Any
  1148. ) -> t.AsyncIterator[str]:
  1149. """An async version of :meth:`generate`. Works very similarly but
  1150. returns an async iterator instead.
  1151. """
  1152. if not self.environment.is_async:
  1153. raise RuntimeError(
  1154. "The environment was not created with async mode enabled."
  1155. )
  1156. ctx = self.new_context(dict(*args, **kwargs))
  1157. try:
  1158. async for event in self.root_render_func(ctx): # type: ignore
  1159. yield event
  1160. except Exception:
  1161. yield self.environment.handle_exception()
  1162. def new_context(
  1163. self,
  1164. vars: t.Optional[t.Dict[str, t.Any]] = None,
  1165. shared: bool = False,
  1166. locals: t.Optional[t.Mapping[str, t.Any]] = None,
  1167. ) -> Context:
  1168. """Create a new :class:`Context` for this template. The vars
  1169. provided will be passed to the template. Per default the globals
  1170. are added to the context. If shared is set to `True` the data
  1171. is passed as is to the context without adding the globals.
  1172. `locals` can be a dict of local variables for internal usage.
  1173. """
  1174. return new_context(
  1175. self.environment, self.name, self.blocks, vars, shared, self.globals, locals
  1176. )
  1177. def make_module(
  1178. self,
  1179. vars: t.Optional[t.Dict[str, t.Any]] = None,
  1180. shared: bool = False,
  1181. locals: t.Optional[t.Mapping[str, t.Any]] = None,
  1182. ) -> "TemplateModule":
  1183. """This method works like the :attr:`module` attribute when called
  1184. without arguments but it will evaluate the template on every call
  1185. rather than caching it. It's also possible to provide
  1186. a dict which is then used as context. The arguments are the same
  1187. as for the :meth:`new_context` method.
  1188. """
  1189. ctx = self.new_context(vars, shared, locals)
  1190. return TemplateModule(self, ctx)
  1191. async def make_module_async(
  1192. self,
  1193. vars: t.Optional[t.Dict[str, t.Any]] = None,
  1194. shared: bool = False,
  1195. locals: t.Optional[t.Mapping[str, t.Any]] = None,
  1196. ) -> "TemplateModule":
  1197. """As template module creation can invoke template code for
  1198. asynchronous executions this method must be used instead of the
  1199. normal :meth:`make_module` one. Likewise the module attribute
  1200. becomes unavailable in async mode.
  1201. """
  1202. ctx = self.new_context(vars, shared, locals)
  1203. return TemplateModule(
  1204. self, ctx, [x async for x in self.root_render_func(ctx)] # type: ignore
  1205. )
  1206. @internalcode
  1207. def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule":
  1208. """If a context is passed in, this means that the template was
  1209. imported. Imported templates have access to the current
  1210. template's globals by default, but they can only be accessed via
  1211. the context during runtime.
  1212. If there are new globals, we need to create a new module because
  1213. the cached module is already rendered and will not have access
  1214. to globals from the current context. This new module is not
  1215. cached because the template can be imported elsewhere, and it
  1216. should have access to only the current template's globals.
  1217. """
  1218. if self.environment.is_async:
  1219. raise RuntimeError("Module is not available in async mode.")
  1220. if ctx is not None:
  1221. keys = ctx.globals_keys - self.globals.keys()
  1222. if keys:
  1223. return self.make_module({k: ctx.parent[k] for k in keys})
  1224. if self._module is None:
  1225. self._module = self.make_module()
  1226. return self._module
  1227. async def _get_default_module_async(
  1228. self, ctx: t.Optional[Context] = None
  1229. ) -> "TemplateModule":
  1230. if ctx is not None:
  1231. keys = ctx.globals_keys - self.globals.keys()
  1232. if keys:
  1233. return await self.make_module_async({k: ctx.parent[k] for k in keys})
  1234. if self._module is None:
  1235. self._module = await self.make_module_async()
  1236. return self._module
  1237. @property
  1238. def module(self) -> "TemplateModule":
  1239. """The template as module. This is used for imports in the
  1240. template runtime but is also useful if one wants to access
  1241. exported template variables from the Python layer:
  1242. >>> t = Template('{% macro foo() %}42{% endmacro %}23')
  1243. >>> str(t.module)
  1244. '23'
  1245. >>> t.module.foo() == u'42'
  1246. True
  1247. This attribute is not available if async mode is enabled.
  1248. """
  1249. return self._get_default_module()
  1250. def get_corresponding_lineno(self, lineno: int) -> int:
  1251. """Return the source line number of a line number in the
  1252. generated bytecode as they are not in sync.
  1253. """
  1254. for template_line, code_line in reversed(self.debug_info):
  1255. if code_line <= lineno:
  1256. return template_line
  1257. return 1
  1258. @property
  1259. def is_up_to_date(self) -> bool:
  1260. """If this variable is `False` there is a newer version available."""
  1261. if self._uptodate is None:
  1262. return True
  1263. return self._uptodate()
  1264. @property
  1265. def debug_info(self) -> t.List[t.Tuple[int, int]]:
  1266. """The debug info mapping."""
  1267. if self._debug_info:
  1268. return [
  1269. tuple(map(int, x.split("="))) # type: ignore
  1270. for x in self._debug_info.split("&")
  1271. ]
  1272. return []
  1273. def __repr__(self) -> str:
  1274. if self.name is None:
  1275. name = f"memory:{id(self):x}"
  1276. else:
  1277. name = repr(self.name)
  1278. return f"<{type(self).__name__} {name}>"
  1279. class TemplateModule:
  1280. """Represents an imported template. All the exported names of the
  1281. template are available as attributes on this object. Additionally
  1282. converting it into a string renders the contents.
  1283. """
  1284. def __init__(
  1285. self,
  1286. template: Template,
  1287. context: Context,
  1288. body_stream: t.Optional[t.Iterable[str]] = None,
  1289. ) -> None:
  1290. if body_stream is None:
  1291. if context.environment.is_async:
  1292. raise RuntimeError(
  1293. "Async mode requires a body stream to be passed to"
  1294. " a template module. Use the async methods of the"
  1295. " API you are using."
  1296. )
  1297. body_stream = list(template.root_render_func(context)) # type: ignore
  1298. self._body_stream = body_stream
  1299. self.__dict__.update(context.get_exported())
  1300. self.__name__ = template.name
  1301. def __html__(self) -> Markup:
  1302. return Markup(concat(self._body_stream))
  1303. def __str__(self) -> str:
  1304. return concat(self._body_stream)
  1305. def __repr__(self) -> str:
  1306. if self.__name__ is None:
  1307. name = f"memory:{id(self):x}"
  1308. else:
  1309. name = repr(self.__name__)
  1310. return f"<{type(self).__name__} {name}>"
  1311. class TemplateExpression:
  1312. """The :meth:`jinja2.Environment.compile_expression` method returns an
  1313. instance of this object. It encapsulates the expression-like access
  1314. to the template with an expression it wraps.
  1315. """
  1316. def __init__(self, template: Template, undefined_to_none: bool) -> None:
  1317. self._template = template
  1318. self._undefined_to_none = undefined_to_none
  1319. def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Optional[t.Any]:
  1320. context = self._template.new_context(dict(*args, **kwargs))
  1321. consume(self._template.root_render_func(context)) # type: ignore
  1322. rv = context.vars["result"]
  1323. if self._undefined_to_none and isinstance(rv, Undefined):
  1324. rv = None
  1325. return rv
  1326. class TemplateStream:
  1327. """A template stream works pretty much like an ordinary python generator
  1328. but it can buffer multiple items to reduce the number of total iterations.
  1329. Per default the output is unbuffered which means that for every unbuffered
  1330. instruction in the template one string is yielded.
  1331. If buffering is enabled with a buffer size of 5, five items are combined
  1332. into a new string. This is mainly useful if you are streaming
  1333. big templates to a client via WSGI which flushes after each iteration.
  1334. """
  1335. def __init__(self, gen: t.Iterator[str]) -> None:
  1336. self._gen = gen
  1337. self.disable_buffering()
  1338. def dump(
  1339. self,
  1340. fp: t.Union[str, t.IO],
  1341. encoding: t.Optional[str] = None,
  1342. errors: t.Optional[str] = "strict",
  1343. ) -> None:
  1344. """Dump the complete stream into a file or file-like object.
  1345. Per default strings are written, if you want to encode
  1346. before writing specify an `encoding`.
  1347. Example usage::
  1348. Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
  1349. """
  1350. close = False
  1351. if isinstance(fp, str):
  1352. if encoding is None:
  1353. encoding = "utf-8"
  1354. fp = open(fp, "wb")
  1355. close = True
  1356. try:
  1357. if encoding is not None:
  1358. iterable = (x.encode(encoding, errors) for x in self) # type: ignore
  1359. else:
  1360. iterable = self # type: ignore
  1361. if hasattr(fp, "writelines"):
  1362. fp.writelines(iterable)
  1363. else:
  1364. for item in iterable:
  1365. fp.write(item)
  1366. finally:
  1367. if close:
  1368. fp.close()
  1369. def disable_buffering(self) -> None:
  1370. """Disable the output buffering."""
  1371. self._next = partial(next, self._gen)
  1372. self.buffered = False
  1373. def _buffered_generator(self, size: int) -> t.Iterator[str]:
  1374. buf: t.List[str] = []
  1375. c_size = 0
  1376. push = buf.append
  1377. while True:
  1378. try:
  1379. while c_size < size:
  1380. c = next(self._gen)
  1381. push(c)
  1382. if c:
  1383. c_size += 1
  1384. except StopIteration:
  1385. if not c_size:
  1386. return
  1387. yield concat(buf)
  1388. del buf[:]
  1389. c_size = 0
  1390. def enable_buffering(self, size: int = 5) -> None:
  1391. """Enable buffering. Buffer `size` items before yielding them."""
  1392. if size <= 1:
  1393. raise ValueError("buffer size too small")
  1394. self.buffered = True
  1395. self._next = partial(next, self._buffered_generator(size))
  1396. def __iter__(self) -> "TemplateStream":
  1397. return self
  1398. def __next__(self) -> str:
  1399. return self._next() # type: ignore
  1400. # hook in default template class. if anyone reads this comment: ignore that
  1401. # it's possible to use custom templates ;-)
  1402. Environment.template_class = Template