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