environment.py 60 KB

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