environment.py
This file
Path
src/jinja2/environment.py
1,666 lines · 59.4 KiB · Python
Last changed by
drop end of life python versions (#2096)David Lordbefore adoption49c48a0
History of this fileTake it
1"""Classes for managing templates and their runtime and compile time2options.3"""45import os6import typing7import typing as t8import weakref9from collections import ChainMap10from contextlib import aclosing11from functools import lru_cache12from functools import partial13from functools import reduce14from types import CodeType1516from markupsafe import Markup1718from . import nodes19from .compiler import CodeGenerator20from .compiler import generate21from .defaults import BLOCK_END_STRING22from .defaults import BLOCK_START_STRING23from .defaults import COMMENT_END_STRING24from .defaults import COMMENT_START_STRING25from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined]26from .defaults import DEFAULT_NAMESPACE27from .defaults import DEFAULT_POLICIES28from .defaults import DEFAULT_TESTS # type: ignore[attr-defined]29from .defaults import KEEP_TRAILING_NEWLINE30from .defaults import LINE_COMMENT_PREFIX31from .defaults import LINE_STATEMENT_PREFIX32from .defaults import LSTRIP_BLOCKS33from .defaults import NEWLINE_SEQUENCE34from .defaults import TRIM_BLOCKS35from .defaults import VARIABLE_END_STRING36from .defaults import VARIABLE_START_STRING37from .exceptions import TemplateNotFound38from .exceptions import TemplateRuntimeError39from .exceptions import TemplatesNotFound40from .exceptions import TemplateSyntaxError41from .exceptions import UndefinedError42from .lexer import get_lexer43from .lexer import Lexer44from .lexer import TokenStream45from .nodes import EvalContext46from .parser import Parser47from .runtime import Context48from .runtime import new_context49from .runtime import Undefined50from .utils import _PassArg51from .utils import concat52from .utils import consume53from .utils import import_string54from .utils import internalcode55from .utils import LRUCache56from .utils import missing5758if t.TYPE_CHECKING:59 import typing_extensions as te6061 from .bccache import BytecodeCache62 from .ext import Extension63 from .loaders import BaseLoader6465_env_bound = t.TypeVar("_env_bound", bound="Environment")666768# for direct template usage we have up to ten living environments69@lru_cache(maxsize=10)70def get_spontaneous_environment(cls: type[_env_bound], *args: t.Any) -> _env_bound:71 """Return a new spontaneous environment. A spontaneous environment72 is used for templates created directly rather than through an73 existing environment.7475 :param cls: Environment class to create.76 :param args: Positional arguments passed to environment.77 """78 env = cls(*args)79 env.shared = True80 return env818283def create_cache(84 size: int,85) -> t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"] | None:86 """Return the cache class for the given size."""87 if size == 0:88 return None8990 if size < 0:91 return {}9293 return LRUCache(size) # type: ignore949596def copy_cache(97 cache: t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"] | None,98) -> t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"] | None:99 """Create an empty copy of the given cache."""100 if cache is None:101 return None102103 if type(cache) is dict: # noqa E721104 return {}105106 return LRUCache(cache.capacity) # type: ignore107108109def load_extensions(110 environment: "Environment",111 extensions: t.Sequence[str | type["Extension"]],112) -> dict[str, "Extension"]:113 """Load the extensions from the list and bind it to the environment.114 Returns a dict of instantiated extensions.115 """116 result = {}117118 for extension in extensions:119 if isinstance(extension, str):120 extension = t.cast(type["Extension"], import_string(extension))121122 result[extension.identifier] = extension(environment)123124 return result125126127def _environment_config_check(environment: _env_bound) -> _env_bound:128 """Perform a sanity check on the environment."""129 assert issubclass(environment.undefined, Undefined), (130 "'undefined' must be a subclass of 'jinja2.Undefined'."131 )132 assert (133 environment.block_start_string134 != environment.variable_start_string135 != environment.comment_start_string136 ), "block, variable and comment start strings must be different."137 assert environment.newline_sequence in {138 "\r",139 "\r\n",140 "\n",141 }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'."142 return environment143144145class Environment:146 r"""The core component of Jinja is the `Environment`. It contains147 important shared variables like configuration, filters, tests,148 globals and others. Instances of this class may be modified if149 they are not shared and if no template was loaded so far.150 Modifications on environments after the first template was loaded151 will lead to surprising effects and undefined behavior.152153 Here are the possible initialization parameters:154155 `block_start_string`156 The string marking the beginning of a block. Defaults to ``'{%'``.157158 `block_end_string`159 The string marking the end of a block. Defaults to ``'%}'``.160161 `variable_start_string`162 The string marking the beginning of a print statement.163 Defaults to ``'{{'``.164165 `variable_end_string`166 The string marking the end of a print statement. Defaults to167 ``'}}'``.168169 `comment_start_string`170 The string marking the beginning of a comment. Defaults to ``'{#'``.171172 `comment_end_string`173 The string marking the end of a comment. Defaults to ``'#}'``.174175 `line_statement_prefix`176 If given and a string, this will be used as prefix for line based177 statements. See also :ref:`line-statements`.178179 `line_comment_prefix`180 If given and a string, this will be used as prefix for line based181 comments. See also :ref:`line-statements`.182183 .. versionadded:: 2.2184185 `trim_blocks`186 If this is set to ``True`` the first newline after a block is187 removed (block, not variable tag!). Defaults to `False`.188189 `lstrip_blocks`190 If this is set to ``True`` leading spaces and tabs are stripped191 from the start of a line to a block. Defaults to `False`.192193 `newline_sequence`194 The sequence that starts a newline. Must be one of ``'\r'``,195 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a196 useful default for Linux and OS X systems as well as web197 applications.198199 `keep_trailing_newline`200 Preserve the trailing newline when rendering templates.201 The default is ``False``, which causes a single newline,202 if present, to be stripped from the end of the template.203204 .. versionadded:: 2.7205206 `extensions`207 List of Jinja extensions to use. This can either be import paths208 as strings or extension classes. For more information have a209 look at :ref:`the extensions documentation <jinja-extensions>`.210211 `optimized`212 should the optimizer be enabled? Default is ``True``.213214 `undefined`215 :class:`Undefined` or a subclass of it that is used to represent216 undefined values in the template.217218 `finalize`219 A callable that can be used to process the result of a variable220 expression before it is output. For example one can convert221 ``None`` implicitly into an empty string here.222223 `autoescape`224 If set to ``True`` the XML/HTML autoescaping feature is enabled by225 default. For more details about autoescaping see226 :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also227 be a callable that is passed the template name and has to228 return ``True`` or ``False`` depending on autoescape should be229 enabled by default.230231 .. versionchanged:: 2.4232 `autoescape` can now be a function233234 `loader`235 The template loader for this environment.236237 `cache_size`238 The size of the cache. Per default this is ``400`` which means239 that if more than 400 templates are loaded the loader will clean240 out the least recently used template. If the cache size is set to241 ``0`` templates are recompiled all the time, if the cache size is242 ``-1`` the cache will not be cleaned.243244 .. versionchanged:: 2.8245 The cache size was increased to 400 from a low 50.246247 `auto_reload`248 Some loaders load templates from locations where the template249 sources may change (ie: file system or database). If250 ``auto_reload`` is set to ``True`` (default) every time a template is251 requested the loader checks if the source changed and if yes, it252 will reload the template. For higher performance it's possible to253 disable that.254255 `bytecode_cache`256 If set to a bytecode cache object, this object will provide a257 cache for the internal Jinja bytecode so that templates don't258 have to be parsed if they were not changed.259260 See :ref:`bytecode-cache` for more information.261262 `enable_async`263 If set to true this enables async template execution which264 allows using async functions and generators.265 """266267 #: if this environment is sandboxed. Modifying this variable won't make268 #: the environment sandboxed though. For a real sandboxed environment269 #: have a look at jinja2.sandbox. This flag alone controls the code270 #: generation by the compiler.271 sandboxed = False272273 #: True if the environment is just an overlay274 overlayed = False275276 #: the environment this environment is linked to if it is an overlay277 linked_to: t.Optional["Environment"] = None278279 #: shared environments have this set to `True`. A shared environment280 #: must not be modified281 shared = False282283 #: the class that is used for code generation. See284 #: :class:`~jinja2.compiler.CodeGenerator` for more information.285 code_generator_class: type["CodeGenerator"] = CodeGenerator286287 concat = "".join288289 #: the context class that is used for templates. See290 #: :class:`~jinja2.runtime.Context` for more information.291 context_class: type[Context] = Context292293 template_class: type["Template"]294295 def __init__(296 self,297 block_start_string: str = BLOCK_START_STRING,298 block_end_string: str = BLOCK_END_STRING,299 variable_start_string: str = VARIABLE_START_STRING,300 variable_end_string: str = VARIABLE_END_STRING,301 comment_start_string: str = COMMENT_START_STRING,302 comment_end_string: str = COMMENT_END_STRING,303 line_statement_prefix: str | None = LINE_STATEMENT_PREFIX,304 line_comment_prefix: str | None = LINE_COMMENT_PREFIX,305 trim_blocks: bool = TRIM_BLOCKS,306 lstrip_blocks: bool = LSTRIP_BLOCKS,307 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,308 keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,309 extensions: t.Sequence[str | type["Extension"]] = (),310 optimized: bool = True,311 undefined: type[Undefined] = Undefined,312 finalize: t.Callable[..., t.Any] | None = None,313 autoescape: bool | t.Callable[[str | None], bool] = False,314 loader: t.Optional["BaseLoader"] = None,315 cache_size: int = 400,316 auto_reload: bool = True,317 bytecode_cache: t.Optional["BytecodeCache"] = None,318 enable_async: bool = False,319 ):320 # !!Important notice!!321 # The constructor accepts quite a few arguments that should be322 # passed by keyword rather than position. However it's important to323 # not change the order of arguments because it's used at least324 # internally in those cases:325 # - spontaneous environments (i18n extension and Template)326 # - unittests327 # If parameter changes are required only add parameters at the end328 # and don't change the arguments (or the defaults!) of the arguments329 # existing already.330331 # lexer / parser information332 self.block_start_string = block_start_string333 self.block_end_string = block_end_string334 self.variable_start_string = variable_start_string335 self.variable_end_string = variable_end_string336 self.comment_start_string = comment_start_string337 self.comment_end_string = comment_end_string338 self.line_statement_prefix = line_statement_prefix339 self.line_comment_prefix = line_comment_prefix340 self.trim_blocks = trim_blocks341 self.lstrip_blocks = lstrip_blocks342 self.newline_sequence = newline_sequence343 self.keep_trailing_newline = keep_trailing_newline344345 # runtime information346 self.undefined: type[Undefined] = undefined347 self.optimized = optimized348 self.finalize = finalize349 self.autoescape = autoescape350351 # defaults352 self.filters = DEFAULT_FILTERS.copy()353 self.tests = DEFAULT_TESTS.copy()354 self.globals = DEFAULT_NAMESPACE.copy()355356 # set the loader provided357 self.loader = loader358 self.cache = create_cache(cache_size)359 self.bytecode_cache = bytecode_cache360 self.auto_reload = auto_reload361362 # configurable policies363 self.policies = DEFAULT_POLICIES.copy()364365 # load extensions366 self.extensions = load_extensions(self, extensions)367368 self.is_async = enable_async369 _environment_config_check(self)370371 def add_extension(self, extension: str | type["Extension"]) -> None:372 """Adds an extension after the environment was created.373374 .. versionadded:: 2.5375 """376 self.extensions.update(load_extensions(self, [extension]))377378 def extend(self, **attributes: t.Any) -> None:379 """Add the items to the instance of the environment if they do not exist380 yet. This is used by :ref:`extensions <writing-extensions>` to register381 callbacks and configuration values without breaking inheritance.382 """383 for key, value in attributes.items():384 if not hasattr(self, key):385 setattr(self, key, value)386387 def overlay(388 self,389 block_start_string: str = missing,390 block_end_string: str = missing,391 variable_start_string: str = missing,392 variable_end_string: str = missing,393 comment_start_string: str = missing,394 comment_end_string: str = missing,395 line_statement_prefix: str | None = missing,396 line_comment_prefix: str | None = missing,397 trim_blocks: bool = missing,398 lstrip_blocks: bool = missing,399 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing,400 keep_trailing_newline: bool = missing,401 extensions: t.Sequence[str | type["Extension"]] = missing,402 optimized: bool = missing,403 undefined: type[Undefined] = missing,404 finalize: t.Callable[..., t.Any] | None = missing,405 autoescape: bool | t.Callable[[str | None], bool] = missing,406 loader: t.Optional["BaseLoader"] = missing,407 cache_size: int = missing,408 auto_reload: bool = missing,409 bytecode_cache: t.Optional["BytecodeCache"] = missing,410 enable_async: bool = missing,411 ) -> "te.Self":412 """Create a new overlay environment that shares all the data with the413 current environment except for cache and the overridden attributes.414 Extensions cannot be removed for an overlayed environment. An overlayed415 environment automatically gets all the extensions of the environment it416 is linked to plus optional extra extensions.417418 Creating overlays should happen after the initial environment was set419 up completely. Not all attributes are truly linked, some are just420 copied over so modifications on the original environment may not shine421 through.422423 .. versionchanged:: 3.1.5424 ``enable_async`` is applied correctly.425426 .. versionchanged:: 3.1.2427 Added the ``newline_sequence``, ``keep_trailing_newline``,428 and ``enable_async`` parameters to match ``__init__``.429 """430 args = dict(locals())431 del args["self"], args["cache_size"], args["extensions"], args["enable_async"]432433 rv = object.__new__(self.__class__)434 rv.__dict__.update(self.__dict__)435 rv.overlayed = True436 rv.linked_to = self437438 for key, value in args.items():439 if value is not missing:440 setattr(rv, key, value)441442 if cache_size is not missing:443 rv.cache = create_cache(cache_size)444 else:445 rv.cache = copy_cache(self.cache)446447 rv.extensions = {}448 for key, value in self.extensions.items():449 rv.extensions[key] = value.bind(rv)450 if extensions is not missing:451 rv.extensions.update(load_extensions(rv, extensions))452453 if enable_async is not missing:454 rv.is_async = enable_async455456 return _environment_config_check(rv)457458 @property459 def lexer(self) -> Lexer:460 """The lexer for this environment."""461 return get_lexer(self)462463 def iter_extensions(self) -> t.Iterator["Extension"]:464 """Iterates over the extensions by priority."""465 return iter(sorted(self.extensions.values(), key=lambda x: x.priority))466467 def getitem(self, obj: t.Any, argument: str | t.Any) -> t.Any | Undefined:468 """Get an item or attribute of an object but prefer the item."""469 try:470 return obj[argument]471 except (AttributeError, TypeError, LookupError):472 if isinstance(argument, str):473 try:474 attr = str(argument)475 except Exception:476 pass477 else:478 try:479 return getattr(obj, attr)480 except AttributeError:481 pass482 return self.undefined(obj=obj, name=argument)483484 def getattr(self, obj: t.Any, attribute: str) -> t.Any:485 """Get an item or attribute of an object but prefer the attribute.486 Unlike :meth:`getitem` the attribute *must* be a string.487 """488 try:489 return getattr(obj, attribute)490 except AttributeError:491 pass492 try:493 return obj[attribute]494 except (TypeError, LookupError, AttributeError):495 return self.undefined(obj=obj, name=attribute)496497 def _filter_test_common(498 self,499 name: str | Undefined,500 value: t.Any,501 args: t.Sequence[t.Any] | None,502 kwargs: t.Mapping[str, t.Any] | None,503 context: Context | None,504 eval_ctx: EvalContext | None,505 is_filter: bool,506 ) -> t.Any:507 if is_filter:508 env_map = self.filters509 type_name = "filter"510 else:511 env_map = self.tests512 type_name = "test"513514 func = env_map.get(name) # type: ignore515516 if func is None:517 msg = f"No {type_name} named {name!r}."518519 if isinstance(name, Undefined):520 try:521 name._fail_with_undefined_error()522 except Exception as e:523 msg = f"{msg} ({e}; did you forget to quote the callable name?)"524525 raise TemplateRuntimeError(msg)526527 args = [value, *(args if args is not None else ())]528 kwargs = kwargs if kwargs is not None else {}529 pass_arg = _PassArg.from_obj(func)530531 if pass_arg is _PassArg.context:532 if context is None:533 raise TemplateRuntimeError(534 f"Attempted to invoke a context {type_name} without context."535 )536537 args.insert(0, context)538 elif pass_arg is _PassArg.eval_context:539 if eval_ctx is None:540 if context is not None:541 eval_ctx = context.eval_ctx542 else:543 eval_ctx = EvalContext(self)544545 args.insert(0, eval_ctx)546 elif pass_arg is _PassArg.environment:547 args.insert(0, self)548549 return func(*args, **kwargs)550551 def call_filter(552 self,553 name: str,554 value: t.Any,555 args: t.Sequence[t.Any] | None = None,556 kwargs: t.Mapping[str, t.Any] | None = None,557 context: Context | None = None,558 eval_ctx: EvalContext | None = None,559 ) -> t.Any:560 """Invoke a filter on a value the same way the compiler does.561562 This might return a coroutine if the filter is running from an563 environment in async mode and the filter supports async564 execution. It's your responsibility to await this if needed.565566 .. versionadded:: 2.7567 """568 return self._filter_test_common(569 name, value, args, kwargs, context, eval_ctx, True570 )571572 def call_test(573 self,574 name: str,575 value: t.Any,576 args: t.Sequence[t.Any] | None = None,577 kwargs: t.Mapping[str, t.Any] | None = None,578 context: Context | None = None,579 eval_ctx: EvalContext | None = None,580 ) -> t.Any:581 """Invoke a test on a value the same way the compiler does.582583 This might return a coroutine if the test is running from an584 environment in async mode and the test supports async execution.585 It's your responsibility to await this if needed.586587 .. versionchanged:: 3.0588 Tests support ``@pass_context``, etc. decorators. Added589 the ``context`` and ``eval_ctx`` parameters.590591 .. versionadded:: 2.7592 """593 return self._filter_test_common(594 name, value, args, kwargs, context, eval_ctx, False595 )596597 @internalcode598 def parse(599 self,600 source: str,601 name: str | None = None,602 filename: str | None = None,603 ) -> nodes.Template:604 """Parse the sourcecode and return the abstract syntax tree. This605 tree of nodes is used by the compiler to convert the template into606 executable source- or bytecode. This is useful for debugging or to607 extract information from templates.608609 If you are :ref:`developing Jinja extensions <writing-extensions>`610 this gives you a good overview of the node tree generated.611 """612 try:613 return self._parse(source, name, filename)614 except TemplateSyntaxError:615 self.handle_exception(source=source)616617 def _parse(618 self, source: str, name: str | None, filename: str | None619 ) -> nodes.Template:620 """Internal parsing function used by `parse` and `compile`."""621 return Parser(self, source, name, filename).parse()622623 def lex(624 self,625 source: str,626 name: str | None = None,627 filename: str | None = None,628 ) -> t.Iterator[tuple[int, str, str]]:629 """Lex the given sourcecode and return a generator that yields630 tokens as tuples in the form ``(lineno, token_type, value)``.631 This can be useful for :ref:`extension development <writing-extensions>`632 and debugging templates.633634 This does not perform preprocessing. If you want the preprocessing635 of the extensions to be applied you have to filter source through636 the :meth:`preprocess` method.637 """638 source = str(source)639 try:640 return self.lexer.tokeniter(source, name, filename)641 except TemplateSyntaxError:642 self.handle_exception(source=source)643644 def preprocess(645 self,646 source: str,647 name: str | None = None,648 filename: str | None = None,649 ) -> str:650 """Preprocesses the source with all extensions. This is automatically651 called for all parsing and compiling methods but *not* for :meth:`lex`652 because there you usually only want the actual source tokenized.653 """654 return reduce(655 lambda s, e: e.preprocess(s, name, filename),656 self.iter_extensions(),657 str(source),658 )659660 def _tokenize(661 self,662 source: str,663 name: str | None,664 filename: str | None = None,665 state: str | None = None,666 ) -> TokenStream:667 """Called by the parser to do the preprocessing and filtering668 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.669 """670 source = self.preprocess(source, name, filename)671 stream = self.lexer.tokenize(source, name, filename, state)672673 for ext in self.iter_extensions():674 stream = ext.filter_stream(stream) # type: ignore675676 if not isinstance(stream, TokenStream):677 stream = TokenStream(stream, name, filename)678679 return stream680681 def _generate(682 self,683 source: nodes.Template,684 name: str | None,685 filename: str | None,686 defer_init: bool = False,687 ) -> str:688 """Internal hook that can be overridden to hook a different generate689 method in.690691 .. versionadded:: 2.5692 """693 return generate( # type: ignore694 source,695 self,696 name,697 filename,698 defer_init=defer_init,699 optimized=self.optimized,700 )701702 def _compile(self, source: str, filename: str) -> CodeType:703 """Internal hook that can be overridden to hook a different compile704 method in.705706 .. versionadded:: 2.5707 """708 return compile(source, filename, "exec")709710 @typing.overload711 def compile(712 self,713 source: str | nodes.Template,714 name: str | None = None,715 filename: str | None = None,716 raw: "te.Literal[False]" = False,717 defer_init: bool = False,718 ) -> CodeType: ...719720 @typing.overload721 def compile(722 self,723 source: str | nodes.Template,724 name: str | None = None,725 filename: str | None = None,726 raw: "te.Literal[True]" = ...,727 defer_init: bool = False,728 ) -> str: ...729730 @internalcode731 def compile(732 self,733 source: str | nodes.Template,734 name: str | None = None,735 filename: str | None = None,736 raw: bool = False,737 defer_init: bool = False,738 ) -> str | CodeType:739 """Compile a node or template source code. The `name` parameter is740 the load name of the template after it was joined using741 :meth:`join_path` if necessary, not the filename on the file system.742 the `filename` parameter is the estimated filename of the template on743 the file system. If the template came from a database or memory this744 can be omitted.745746 The return value of this method is a python code object. If the `raw`747 parameter is `True` the return value will be a string with python748 code equivalent to the bytecode returned otherwise. This method is749 mainly used internally.750751 `defer_init` is use internally to aid the module code generator. This752 causes the generated code to be able to import without the global753 environment variable to be set.754755 .. versionadded:: 2.4756 `defer_init` parameter added.757 """758 source_hint = None759 try:760 if isinstance(source, str):761 source_hint = source762 source = self._parse(source, name, filename)763 source = self._generate(source, name, filename, defer_init=defer_init)764 if raw:765 return source766 if filename is None:767 filename = "<template>"768 return self._compile(source, filename)769 except TemplateSyntaxError:770 self.handle_exception(source=source_hint)771772 def compile_expression(773 self, source: str, undefined_to_none: bool = True774 ) -> "TemplateExpression":775 """A handy helper method that returns a callable that accepts keyword776 arguments that appear as variables in the expression. If called it777 returns the result of the expression.778779 This is useful if applications want to use the same rules as Jinja780 in template "configuration files" or similar situations.781782 Example usage:783784 >>> env = Environment()785 >>> expr = env.compile_expression('foo == 42')786 >>> expr(foo=23)787 False788 >>> expr(foo=42)789 True790791 Per default the return value is converted to `None` if the792 expression returns an undefined value. This can be changed793 by setting `undefined_to_none` to `False`.794795 >>> env.compile_expression('var')() is None796 True797 >>> env.compile_expression('var', undefined_to_none=False)()798 Undefined799800 .. versionadded:: 2.1801 """802 parser = Parser(self, source, state="variable")803 try:804 expr = parser.parse_expression()805 if not parser.stream.eos:806 raise TemplateSyntaxError(807 "chunk after expression", parser.stream.current.lineno, None, None808 )809 expr.set_environment(self)810 except TemplateSyntaxError:811 self.handle_exception(source=source)812813 body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]814 template = self.from_string(nodes.Template(body, lineno=1))815 return TemplateExpression(template, undefined_to_none)816817 def compile_templates(818 self,819 target: t.Union[str, "os.PathLike[str]"],820 extensions: t.Collection[str] | None = None,821 filter_func: t.Callable[[str], bool] | None = None,822 zip: str | None = "deflated",823 log_function: t.Callable[[str], None] | None = None,824 ignore_errors: bool = True,825 ) -> None:826 """Finds all the templates the loader can find, compiles them827 and stores them in `target`. If `zip` is `None`, instead of in a828 zipfile, the templates will be stored in a directory.829 By default a deflate zip algorithm is used. To switch to830 the stored algorithm, `zip` can be set to ``'stored'``.831832 `extensions` and `filter_func` are passed to :meth:`list_templates`.833 Each template returned will be compiled to the target folder or834 zipfile.835836 By default template compilation errors are ignored. In case a837 log function is provided, errors are logged. If you want template838 syntax errors to abort the compilation you can set `ignore_errors`839 to `False` and you will get an exception on syntax errors.840841 .. versionadded:: 2.4842 """843 from .loaders import ModuleLoader844845 if log_function is None:846847 def log_function(x: str) -> None:848 pass849850 assert log_function is not None851 assert self.loader is not None, "No loader configured."852853 def write_file(filename: str, data: str) -> None:854 if zip:855 info = ZipInfo(filename)856 info.external_attr = 0o755 << 16857 zip_file.writestr(info, data)858 else:859 with open(os.path.join(target, filename), "wb") as f:860 f.write(data.encode("utf8"))861862 if zip is not None:863 from zipfile import ZIP_DEFLATED864 from zipfile import ZIP_STORED865 from zipfile import ZipFile866 from zipfile import ZipInfo867868 zip_file = ZipFile(869 target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]870 )871 log_function(f"Compiling into Zip archive {target!r}")872 else:873 if not os.path.isdir(target):874 os.makedirs(target)875 log_function(f"Compiling into folder {target!r}")876877 try:878 for name in self.list_templates(extensions, filter_func):879 source, filename, _ = self.loader.get_source(self, name)880 try:881 code = self.compile(source, name, filename, True, True)882 except TemplateSyntaxError as e:883 if not ignore_errors:884 raise885 log_function(f'Could not compile "{name}": {e}')886 continue887888 filename = ModuleLoader.get_module_filename(name)889890 write_file(filename, code)891 log_function(f'Compiled "{name}" as {filename}')892 finally:893 if zip:894 zip_file.close()895896 log_function("Finished compiling templates")897898 def list_templates(899 self,900 extensions: t.Collection[str] | None = None,901 filter_func: t.Callable[[str], bool] | None = None,902 ) -> list[str]:903 """Returns a list of templates for this environment. This requires904 that the loader supports the loader's905 :meth:`~BaseLoader.list_templates` method.906907 If there are other files in the template folder besides the908 actual templates, the returned list can be filtered. There are two909 ways: either `extensions` is set to a list of file extensions for910 templates, or a `filter_func` can be provided which is a callable that911 is passed a template name and should return `True` if it should end up912 in the result list.913914 If the loader does not support that, a :exc:`TypeError` is raised.915916 .. versionadded:: 2.4917 """918 assert self.loader is not None, "No loader configured."919 names = self.loader.list_templates()920921 if extensions is not None:922 if filter_func is not None:923 raise TypeError(924 "either extensions or filter_func can be passed, but not both"925 )926927 def filter_func(x: str) -> bool:928 return "." in x and x.rsplit(".", 1)[1] in extensions929930 if filter_func is not None:931 names = [name for name in names if filter_func(name)]932933 return names934935 def handle_exception(self, source: str | None = None) -> "te.NoReturn":936 """Exception handling helper. This is used internally to either raise937 rewritten exceptions or return a rendered traceback for the template.938 """939 from .debug import rewrite_traceback_stack940941 raise rewrite_traceback_stack(source=source)942943 def join_path(self, template: str, parent: str) -> str:944 """Join a template with the parent. By default all the lookups are945 relative to the loader root so this method returns the `template`946 parameter unchanged, but if the paths should be relative to the947 parent template, this function can be used to calculate the real948 template name.949950 Subclasses may override this method and implement template path951 joining here.952 """953 return template954955 @internalcode956 def _load_template(957 self, name: str, globals: t.MutableMapping[str, t.Any] | None958 ) -> "Template":959 if self.loader is None:960 raise TypeError("no loader for this environment specified")961 cache_key = (weakref.ref(self.loader), name)962 if self.cache is not None:963 template = self.cache.get(cache_key)964 if template is not None and (965 not self.auto_reload or template.is_up_to_date966 ):967 # template.globals is a ChainMap, modifying it will only968 # affect the template, not the environment globals.969 if globals:970 template.globals.update(globals)971972 return template973974 template = self.loader.load(self, name, self.make_globals(globals))975976 if self.cache is not None:977 self.cache[cache_key] = template978 return template979980 @internalcode981 def get_template(982 self,983 name: t.Union[str, "Template"],984 parent: str | None = None,985 globals: t.MutableMapping[str, t.Any] | None = None,986 ) -> "Template":987 """Load a template by name with :attr:`loader` and return a988 :class:`Template`. If the template does not exist a989 :exc:`TemplateNotFound` exception is raised.990991 :param name: Name of the template to load. When loading992 templates from the filesystem, "/" is used as the path993 separator, even on Windows.994 :param parent: The name of the parent template importing this995 template. :meth:`join_path` can be used to implement name996 transformations with this.997 :param globals: Extend the environment :attr:`globals` with998 these extra variables available for all renders of this999 template. If the template has already been loaded and1000 cached, its globals are updated with any new items.10011002 .. versionchanged:: 3.01003 If a template is loaded from cache, ``globals`` will update1004 the template's globals instead of ignoring the new values.10051006 .. versionchanged:: 2.41007 If ``name`` is a :class:`Template` object it is returned1008 unchanged.1009 """1010 if isinstance(name, Template):1011 return name1012 if parent is not None:1013 name = self.join_path(name, parent)10141015 return self._load_template(name, globals)10161017 @internalcode1018 def select_template(1019 self,1020 names: t.Iterable[t.Union[str, "Template"]],1021 parent: str | None = None,1022 globals: t.MutableMapping[str, t.Any] | None = None,1023 ) -> "Template":1024 """Like :meth:`get_template`, but tries loading multiple names.1025 If none of the names can be loaded a :exc:`TemplatesNotFound`1026 exception is raised.10271028 :param names: List of template names to try loading in order.1029 :param parent: The name of the parent template importing this1030 template. :meth:`join_path` can be used to implement name1031 transformations with this.1032 :param globals: Extend the environment :attr:`globals` with1033 these extra variables available for all renders of this1034 template. If the template has already been loaded and1035 cached, its globals are updated with any new items.10361037 .. versionchanged:: 3.01038 If a template is loaded from cache, ``globals`` will update1039 the template's globals instead of ignoring the new values.10401041 .. versionchanged:: 2.111042 If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`1043 is raised instead. If no templates were found and ``names``1044 contains :class:`Undefined`, the message is more helpful.10451046 .. versionchanged:: 2.41047 If ``names`` contains a :class:`Template` object it is1048 returned unchanged.10491050 .. versionadded:: 2.31051 """1052 if isinstance(names, Undefined):1053 names._fail_with_undefined_error()10541055 if not names:1056 raise TemplatesNotFound(1057 message="Tried to select from an empty list of templates."1058 )10591060 for name in names:1061 if isinstance(name, Template):1062 return name1063 if parent is not None:1064 name = self.join_path(name, parent)1065 try:1066 return self._load_template(name, globals)1067 except (TemplateNotFound, UndefinedError):1068 pass1069 raise TemplatesNotFound(names) # type: ignore10701071 @internalcode1072 def get_or_select_template(1073 self,1074 template_name_or_list: t.Union[str, "Template", list[t.Union[str, "Template"]]],1075 parent: str | None = None,1076 globals: t.MutableMapping[str, t.Any] | None = None,1077 ) -> "Template":1078 """Use :meth:`select_template` if an iterable of template names1079 is given, or :meth:`get_template` if one name is given.10801081 .. versionadded:: 2.31082 """1083 if isinstance(template_name_or_list, (str, Undefined)):1084 return self.get_template(template_name_or_list, parent, globals)1085 elif isinstance(template_name_or_list, Template):1086 return template_name_or_list1087 return self.select_template(template_name_or_list, parent, globals)10881089 def from_string(1090 self,1091 source: str | nodes.Template,1092 globals: t.MutableMapping[str, t.Any] | None = None,1093 template_class: type["Template"] | None = None,1094 ) -> "Template":1095 """Load a template from a source string without using1096 :attr:`loader`.10971098 :param source: Jinja source to compile into a template.1099 :param globals: Extend the environment :attr:`globals` with1100 these extra variables available for all renders of this1101 template. If the template has already been loaded and1102 cached, its globals are updated with any new items.1103 :param template_class: Return an instance of this1104 :class:`Template` class.1105 """1106 gs = self.make_globals(globals)1107 cls = template_class or self.template_class1108 return cls.from_code(self, self.compile(source), gs, None)11091110 def make_globals(1111 self, d: t.MutableMapping[str, t.Any] | None1112 ) -> t.MutableMapping[str, t.Any]:1113 """Make the globals map for a template. Any given template1114 globals overlay the environment :attr:`globals`.11151116 Returns a :class:`collections.ChainMap`. This allows any changes1117 to a template's globals to only affect that template, while1118 changes to the environment's globals are still reflected.1119 However, avoid modifying any globals after a template is loaded.11201121 :param d: Dict of template-specific globals.11221123 .. versionchanged:: 3.01124 Use :class:`collections.ChainMap` to always prevent mutating1125 environment globals.1126 """1127 if d is None:1128 d = {}11291130 return ChainMap(d, self.globals)113111321133class Template:1134 """A compiled template that can be rendered.11351136 Use the methods on :class:`Environment` to create or load templates.1137 The environment is used to configure how templates are compiled and1138 behave.11391140 It is also possible to create a template object directly. This is1141 not usually recommended. The constructor takes most of the same1142 arguments as :class:`Environment`. All templates created with the1143 same environment arguments share the same ephemeral ``Environment``1144 instance behind the scenes.11451146 A template object should be considered immutable. Modifications on1147 the object are not supported.1148 """11491150 #: Type of environment to create when creating a template directly1151 #: rather than through an existing environment.1152 environment_class: type[Environment] = Environment11531154 environment: Environment1155 globals: t.MutableMapping[str, t.Any]1156 name: str | None1157 filename: str | None1158 blocks: dict[str, t.Callable[[Context], t.Iterator[str]]]1159 root_render_func: t.Callable[[Context], t.Iterator[str]]1160 _module: t.Optional["TemplateModule"]1161 _debug_info: str1162 _uptodate: t.Callable[[], bool] | None11631164 def __new__(1165 cls,1166 source: str | nodes.Template,1167 block_start_string: str = BLOCK_START_STRING,1168 block_end_string: str = BLOCK_END_STRING,1169 variable_start_string: str = VARIABLE_START_STRING,1170 variable_end_string: str = VARIABLE_END_STRING,1171 comment_start_string: str = COMMENT_START_STRING,1172 comment_end_string: str = COMMENT_END_STRING,1173 line_statement_prefix: str | None = LINE_STATEMENT_PREFIX,1174 line_comment_prefix: str | None = LINE_COMMENT_PREFIX,1175 trim_blocks: bool = TRIM_BLOCKS,1176 lstrip_blocks: bool = LSTRIP_BLOCKS,1177 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,1178 keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,1179 extensions: t.Sequence[str | type["Extension"]] = (),1180 optimized: bool = True,1181 undefined: type[Undefined] = Undefined,1182 finalize: t.Callable[..., t.Any] | None = None,1183 autoescape: bool | t.Callable[[str | None], bool] = False,1184 enable_async: bool = False,1185 ) -> t.Any: # it returns a `Template`, but this breaks the sphinx build...1186 env = get_spontaneous_environment(1187 cls.environment_class, # type: ignore1188 block_start_string,1189 block_end_string,1190 variable_start_string,1191 variable_end_string,1192 comment_start_string,1193 comment_end_string,1194 line_statement_prefix,1195 line_comment_prefix,1196 trim_blocks,1197 lstrip_blocks,1198 newline_sequence,1199 keep_trailing_newline,1200 frozenset(extensions),1201 optimized,1202 undefined, # type: ignore1203 finalize,1204 autoescape,1205 None,1206 0,1207 False,1208 None,1209 enable_async,1210 )1211 return env.from_string(source, template_class=cls)12121213 @classmethod1214 def from_code(1215 cls,1216 environment: Environment,1217 code: CodeType,1218 globals: t.MutableMapping[str, t.Any],1219 uptodate: t.Callable[[], bool] | None = None,1220 ) -> "Template":1221 """Creates a template object from compiled code and the globals. This1222 is used by the loaders and environment to create a template object.1223 """1224 namespace = {"environment": environment, "__file__": code.co_filename}1225 exec(code, namespace)1226 rv = cls._from_namespace(environment, namespace, globals)1227 rv._uptodate = uptodate1228 return rv12291230 @classmethod1231 def from_module_dict(1232 cls,1233 environment: Environment,1234 module_dict: t.MutableMapping[str, t.Any],1235 globals: t.MutableMapping[str, t.Any],1236 ) -> "Template":1237 """Creates a template object from a module. This is used by the1238 module loader to create a template object.12391240 .. versionadded:: 2.41241 """1242 return cls._from_namespace(environment, module_dict, globals)12431244 @classmethod1245 def _from_namespace(1246 cls,1247 environment: Environment,1248 namespace: t.MutableMapping[str, t.Any],1249 globals: t.MutableMapping[str, t.Any],1250 ) -> "Template":1251 t: Template = object.__new__(cls)1252 t.environment = environment1253 t.globals = globals1254 t.name = namespace["name"]1255 t.filename = namespace["__file__"]1256 t.blocks = namespace["blocks"]12571258 # render function and module1259 t.root_render_func = namespace["root"]1260 t._module = None12611262 # debug and loader helpers1263 t._debug_info = namespace["debug_info"]1264 t._uptodate = None12651266 # store the reference1267 namespace["environment"] = environment1268 namespace["__jinja_template__"] = t12691270 return t12711272 def render(self, *args: t.Any, **kwargs: t.Any) -> str:1273 """This method accepts the same arguments as the `dict` constructor:1274 A dict, a dict subclass or some keyword arguments. If no arguments1275 are given the context will be empty. These two calls do the same::12761277 template.render(knights='that say nih')1278 template.render({'knights': 'that say nih'})12791280 This will return the rendered template as a string.1281 """1282 if self.environment.is_async:1283 import asyncio12841285 return asyncio.run(self.render_async(*args, **kwargs))12861287 ctx = self.new_context(dict(*args, **kwargs))12881289 try:1290 return self.environment.concat(self.root_render_func(ctx)) # type: ignore1291 except Exception:1292 self.environment.handle_exception()12931294 async def render_async(self, *args: t.Any, **kwargs: t.Any) -> str:1295 """This works similar to :meth:`render` but returns a coroutine1296 that when awaited returns the entire rendered template string. This1297 requires the async feature to be enabled.12981299 Example usage::13001301 await template.render_async(knights='that say nih; asynchronously')1302 """1303 if not self.environment.is_async:1304 raise RuntimeError(1305 "The environment was not created with async mode enabled."1306 )13071308 ctx = self.new_context(dict(*args, **kwargs))13091310 try:1311 return self.environment.concat( # type: ignore1312 [n async for n in self.root_render_func(ctx)] # type: ignore1313 )1314 except Exception:1315 return self.environment.handle_exception()13161317 def stream(self, *args: t.Any, **kwargs: t.Any) -> "TemplateStream":1318 """Works exactly like :meth:`generate` but returns a1319 :class:`TemplateStream`.1320 """1321 return TemplateStream(self.generate(*args, **kwargs))13221323 def generate(self, *args: t.Any, **kwargs: t.Any) -> t.Iterator[str]:1324 """For very large templates it can be useful to not render the whole1325 template at once but evaluate each statement after another and yield1326 piece for piece. This method basically does exactly that and returns1327 a generator that yields one item after another as strings.13281329 It accepts the same arguments as :meth:`render`.1330 """1331 if self.environment.is_async:1332 import asyncio13331334 async def to_list() -> list[str]:1335 return [x async for x in self.generate_async(*args, **kwargs)]13361337 yield from asyncio.run(to_list())1338 return13391340 ctx = self.new_context(dict(*args, **kwargs))13411342 try:1343 yield from self.root_render_func(ctx)1344 except Exception:1345 yield self.environment.handle_exception()13461347 async def generate_async(1348 self, *args: t.Any, **kwargs: t.Any1349 ) -> t.AsyncGenerator[str, object]:1350 """An async version of :meth:`generate`. Works very similarly but1351 returns an async iterator instead.1352 """1353 if not self.environment.is_async:1354 raise RuntimeError(1355 "The environment was not created with async mode enabled."1356 )13571358 ctx = self.new_context(dict(*args, **kwargs))13591360 try:1361 agen: t.AsyncGenerator[str, None] = self.root_render_func(ctx) # type: ignore[assignment]13621363 async with aclosing(agen):1364 async for event in agen:1365 yield event1366 except Exception:1367 yield self.environment.handle_exception()13681369 def new_context(1370 self,1371 vars: dict[str, t.Any] | None = None,1372 shared: bool = False,1373 locals: t.Mapping[str, t.Any] | None = None,1374 ) -> Context:1375 """Create a new :class:`Context` for this template. The vars1376 provided will be passed to the template. Per default the globals1377 are added to the context. If shared is set to `True` the data1378 is passed as is to the context without adding the globals.13791380 `locals` can be a dict of local variables for internal usage.1381 """1382 return new_context(1383 self.environment, self.name, self.blocks, vars, shared, self.globals, locals1384 )13851386 def make_module(1387 self,1388 vars: dict[str, t.Any] | None = None,1389 shared: bool = False,1390 locals: t.Mapping[str, t.Any] | None = None,1391 ) -> "TemplateModule":1392 """This method works like the :attr:`module` attribute when called1393 without arguments but it will evaluate the template on every call1394 rather than caching it. It's also possible to provide1395 a dict which is then used as context. The arguments are the same1396 as for the :meth:`new_context` method.1397 """1398 ctx = self.new_context(vars, shared, locals)1399 return TemplateModule(self, ctx)14001401 async def make_module_async(1402 self,1403 vars: dict[str, t.Any] | None = None,1404 shared: bool = False,1405 locals: t.Mapping[str, t.Any] | None = None,1406 ) -> "TemplateModule":1407 """As template module creation can invoke template code for1408 asynchronous executions this method must be used instead of the1409 normal :meth:`make_module` one. Likewise the module attribute1410 becomes unavailable in async mode.1411 """1412 ctx = self.new_context(vars, shared, locals)1413 return TemplateModule(1414 self,1415 ctx,1416 [x async for x in self.root_render_func(ctx)], # type: ignore1417 )14181419 @internalcode1420 def _get_default_module(self, ctx: Context | None = None) -> "TemplateModule":1421 """If a context is passed in, this means that the template was1422 imported. Imported templates have access to the current1423 template's globals by default, but they can only be accessed via1424 the context during runtime.14251426 If there are new globals, we need to create a new module because1427 the cached module is already rendered and will not have access1428 to globals from the current context. This new module is not1429 cached because the template can be imported elsewhere, and it1430 should have access to only the current template's globals.1431 """1432 if self.environment.is_async:1433 raise RuntimeError("Module is not available in async mode.")14341435 if ctx is not None:1436 keys = ctx.globals_keys - self.globals.keys()14371438 if keys:1439 return self.make_module({k: ctx.parent[k] for k in keys})14401441 if self._module is None:1442 self._module = self.make_module()14431444 return self._module14451446 async def _get_default_module_async(1447 self, ctx: Context | None = None1448 ) -> "TemplateModule":1449 if ctx is not None:1450 keys = ctx.globals_keys - self.globals.keys()14511452 if keys:1453 return await self.make_module_async({k: ctx.parent[k] for k in keys})14541455 if self._module is None:1456 self._module = await self.make_module_async()14571458 return self._module14591460 @property1461 def module(self) -> "TemplateModule":1462 """The template as module. This is used for imports in the1463 template runtime but is also useful if one wants to access1464 exported template variables from the Python layer:14651466 >>> t = Template('{% macro foo() %}42{% endmacro %}23')1467 >>> str(t.module)1468 '23'1469 >>> t.module.foo() == u'42'1470 True14711472 This attribute is not available if async mode is enabled.1473 """1474 return self._get_default_module()14751476 def get_corresponding_lineno(self, lineno: int) -> int:1477 """Return the source line number of a line number in the1478 generated bytecode as they are not in sync.1479 """1480 for template_line, code_line in reversed(self.debug_info):1481 if code_line <= lineno:1482 return template_line1483 return 114841485 @property1486 def is_up_to_date(self) -> bool:1487 """If this variable is `False` there is a newer version available."""1488 if self._uptodate is None:1489 return True1490 return self._uptodate()14911492 @property1493 def debug_info(self) -> list[tuple[int, int]]:1494 """The debug info mapping."""1495 if self._debug_info:1496 return [1497 tuple(map(int, x.split("="))) # type: ignore1498 for x in self._debug_info.split("&")1499 ]15001501 return []15021503 def __repr__(self) -> str:1504 if self.name is None:1505 name = f"memory:{id(self):x}"1506 else:1507 name = repr(self.name)1508 return f"<{type(self).__name__} {name}>"150915101511class TemplateModule:1512 """Represents an imported template. All the exported names of the1513 template are available as attributes on this object. Additionally1514 converting it into a string renders the contents.1515 """15161517 def __init__(1518 self,1519 template: Template,1520 context: Context,1521 body_stream: t.Iterable[str] | None = None,1522 ) -> None:1523 if body_stream is None:1524 if context.environment.is_async:1525 raise RuntimeError(1526 "Async mode requires a body stream to be passed to"1527 " a template module. Use the async methods of the"1528 " API you are using."1529 )15301531 body_stream = list(template.root_render_func(context))15321533 self._body_stream = body_stream1534 self.__dict__.update(context.get_exported())1535 self.__name__ = template.name15361537 def __html__(self) -> Markup:1538 return Markup(concat(self._body_stream))15391540 def __str__(self) -> str:1541 return concat(self._body_stream)15421543 def __repr__(self) -> str:1544 if self.__name__ is None:1545 name = f"memory:{id(self):x}"1546 else:1547 name = repr(self.__name__)1548 return f"<{type(self).__name__} {name}>"154915501551class TemplateExpression:1552 """The :meth:`jinja2.Environment.compile_expression` method returns an1553 instance of this object. It encapsulates the expression-like access1554 to the template with an expression it wraps.1555 """15561557 def __init__(self, template: Template, undefined_to_none: bool) -> None:1558 self._template = template1559 self._undefined_to_none = undefined_to_none15601561 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any | None:1562 context = self._template.new_context(dict(*args, **kwargs))1563 consume(self._template.root_render_func(context))1564 rv = context.vars["result"]1565 if self._undefined_to_none and isinstance(rv, Undefined):1566 rv = None1567 return rv156815691570class TemplateStream:1571 """A template stream works pretty much like an ordinary python generator1572 but it can buffer multiple items to reduce the number of total iterations.1573 Per default the output is unbuffered which means that for every unbuffered1574 instruction in the template one string is yielded.15751576 If buffering is enabled with a buffer size of 5, five items are combined1577 into a new string. This is mainly useful if you are streaming1578 big templates to a client via WSGI which flushes after each iteration.1579 """15801581 def __init__(self, gen: t.Iterator[str]) -> None:1582 self._gen = gen1583 self.disable_buffering()15841585 def dump(1586 self,1587 fp: str | t.IO[bytes],1588 encoding: str | None = None,1589 errors: str | None = "strict",1590 ) -> None:1591 """Dump the complete stream into a file or file-like object.1592 Per default strings are written, if you want to encode1593 before writing specify an `encoding`.15941595 Example usage::15961597 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1598 """1599 close = False16001601 if isinstance(fp, str):1602 if encoding is None:1603 encoding = "utf-8"16041605 real_fp: t.IO[bytes] = open(fp, "wb")1606 close = True1607 else:1608 real_fp = fp16091610 try:1611 if encoding is not None:1612 iterable = (x.encode(encoding, errors) for x in self) # type: ignore1613 else:1614 iterable = self # type: ignore16151616 if hasattr(real_fp, "writelines"):1617 real_fp.writelines(iterable)1618 else:1619 for item in iterable:1620 real_fp.write(item)1621 finally:1622 if close:1623 real_fp.close()16241625 def disable_buffering(self) -> None:1626 """Disable the output buffering."""1627 self._next = partial(next, self._gen)1628 self.buffered = False16291630 def _buffered_generator(self, size: int) -> t.Iterator[str]:1631 buf: list[str] = []1632 c_size = 01633 push = buf.append16341635 while True:1636 try:1637 while c_size < size:1638 c = next(self._gen)1639 push(c)1640 if c:1641 c_size += 11642 except StopIteration:1643 if not c_size:1644 return1645 yield concat(buf)1646 del buf[:]1647 c_size = 016481649 def enable_buffering(self, size: int = 5) -> None:1650 """Enable buffering. Buffer `size` items before yielding them."""1651 if size <= 1:1652 raise ValueError("buffer size too small")16531654 self.buffered = True1655 self._next = partial(next, self._buffered_generator(size))16561657 def __iter__(self) -> "TemplateStream":1658 return self16591660 def __next__(self) -> str:1661 return self._next() # type: ignore166216631664# hook in default template class. if anyone reads this comment: ignore that1665# it's possible to use custom templates ;-)1666Environment.template_class = Template