environment.py 60 KB

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