environment.py 60 KB

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