U a@sdZddlZddlZddlZddlZddlZddlmZddlm Z ddlm Z ddlm Z ddl m Z ddlmZd d lmZd d lmZd d lmZd d lmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlm Z d dlm!Z!d dlm"Z"d dlm#Z#d dlm$Z$d dlm%Z%d dl&m'Z'd dl&m(Z(d dl&m)Z)d d l&m*Z*d d!l&m+Z+d d"l,m-Z-d d#l,m.Z.d d$l,m/Z/d d%lm0Z0d d&l1m2Z2d d'l3m4Z4d d(l3m5Z5d d)l3m6Z6d d*l7m8Z8d d+l7m9Z9d d,l7m:Z:d d-l7m;Z;d d.l7mZ>ej?r|ddl@ZAd d1lBmCZCd d2lDmEZEd d3lFmGZGejHd4d5d6ZIe d7d8ejJeIejKeId9d:d;ZLeMejNejOejPejQeRfdd?ZSejNejOejNejOejPejQeRfd   z8'newline_sequence' must be one of '\n', '\r\n', or '\r'.) issubclass undefinedr)AssertionErrorblock_start_stringvariable_start_stringcomment_start_stringnewline_sequence)rKr?r?r@_environment_config_check}s"  r`c@sXeZdZUdZdZdZdZejde d<dZ e Z ej de d<eZej ee d<ej de d <eeeeeeeeeeeed d edddd d ddfeeeeeeejeejeeed eejej eej dfeej eejej!dej"fej eej!ejegeffejde#eejdedddZ$ej eej dfddddZ%ej"ddddZ&e'e'e'e'e'e'e'e'e'e'e'e'e'e'e'e'e'e'e'feeeeeeejeejeeeejej eej dfeej eejej!dej"fej eej!ejegeffejde#eejdddddZ(e)e*ddd Z+ej,ddd!d"Z-ej"ej eej"fej ej"efd#d$d%Z.ej"eej"d&d'd(Z/ej eefej"ejejej"ejej0eej"fejeeje1eej"d)d*d+Z2dneej"ejejej"ejej0eej"fejeeje1ej"d,d-d.Z3doeej"ejejej"ejej0eej"fejeeje1ej"d,d/d0Z4e5dpeejeejee6j7d1d2d3Z8eejeejee6j7d1d4d5Z9dqeejeejeej,ej:e#eefd1d6d7Z;dreejeejeed1d8d9Zdte6j7ejeejeeed=d>d?Z?eee@d@dAdBZAeBjCduej ee6j7fejeejedCee@dDdEdFZDeBjCdvej ee6j7fejeejedGeedDdHdFZDe5dwej ee6j7fejeejeeeej ee@fdDdIdFZDdxeedJdKdLdMZEdyej eeFjGfejejHeejej!egefejeejej!egdfeddOdPdQZIdzejejHeejej!egefejJedRdSdTZKd{ejedUdVdWdXZLeeedYdZd[ZMe5eejej0eej"fdd\d]d^ZNe5d|ej edfejeejej0eej"fdd_d`daZOe5d}ejPej edfejeejej0eej"fddbdcddZQe5d~ej edejJej edffejeejej0eej"fddedfdgZRdej ee6j7fejej0eej"fejej dddhdidjZSejej0eej"fejTeej"fdkdldmZUdS)r6aThe core component of Jinja is the `Environment`. It contains important shared variables like configuration, filters, tests, globals and others. Instances of this class may be modified if they are not shared and if no template was loaded so far. Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior. Here are the possible initialization parameters: `block_start_string` The string marking the beginning of a block. Defaults to ``'{%'``. `block_end_string` The string marking the end of a block. Defaults to ``'%}'``. `variable_start_string` The string marking the beginning of a print statement. Defaults to ``'{{'``. `variable_end_string` The string marking the end of a print statement. Defaults to ``'}}'``. `comment_start_string` The string marking the beginning of a comment. Defaults to ``'{#'``. `comment_end_string` The string marking the end of a comment. Defaults to ``'#}'``. `line_statement_prefix` If given and a string, this will be used as prefix for line based statements. See also :ref:`line-statements`. `line_comment_prefix` If given and a string, this will be used as prefix for line based comments. See also :ref:`line-statements`. .. versionadded:: 2.2 `trim_blocks` If this is set to ``True`` the first newline after a block is removed (block, not variable tag!). Defaults to `False`. `lstrip_blocks` If this is set to ``True`` leading spaces and tabs are stripped from the start of a line to a block. Defaults to `False`. `newline_sequence` The sequence that starts a newline. Must be one of ``'\r'``, ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a useful default for Linux and OS X systems as well as web applications. `keep_trailing_newline` Preserve the trailing newline when rendering templates. The default is ``False``, which causes a single newline, if present, to be stripped from the end of the template. .. versionadded:: 2.7 `extensions` List of Jinja extensions to use. This can either be import paths as strings or extension classes. For more information have a look at :ref:`the extensions documentation `. `optimized` should the optimizer be enabled? Default is ``True``. `undefined` :class:`Undefined` or a subclass of it that is used to represent undefined values in the template. `finalize` A callable that can be used to process the result of a variable expression before it is output. For example one can convert ``None`` implicitly into an empty string here. `autoescape` If set to ``True`` the XML/HTML autoescaping feature is enabled by default. For more details about autoescaping see :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also be a callable that is passed the template name and has to return ``True`` or ``False`` depending on autoescape should be enabled by default. .. versionchanged:: 2.4 `autoescape` can now be a function `loader` The template loader for this environment. `cache_size` The size of the cache. Per default this is ``400`` which means that if more than 400 templates are loaded the loader will clean out the least recently used template. If the cache size is set to ``0`` templates are recompiled all the time, if the cache size is ``-1`` the cache will not be cleaned. .. versionchanged:: 2.8 The cache size was increased to 400 from a low 50. `auto_reload` Some loaders load templates from locations where the template sources may change (ie: file system or database). If ``auto_reload`` is set to ``True`` (default) every time a template is requested the loader checks if the source changed and if yes, it will reload the template. For higher performance it's possible to disable that. `bytecode_cache` If set to a bytecode cache object, this object will provide a cache for the internal Jinja bytecode so that templates don't have to be parsed if they were not changed. See :ref:`bytecode-cache` for more information. `enable_async` If set to true this enables async template execution which allows using async functions and generators. FN linked_tor code_generator_class context_classrBtemplate_classr?Tite.Literal['\n', '\r\n', '\r']r3.r4r2)r\block_end_stringr]variable_end_stringr^comment_end_stringline_statement_prefixline_comment_prefix trim_blocks lstrip_blocksr_keep_trailing_newlinerL optimizedrZfinalize autoescapeloader cache_size auto_reloadbytecode_cache enable_asynccCs||_||_||_||_||_||_||_||_| |_| |_ | |_ | |_ ||_ ||_ ||_||_t|_t|_t|_||_t||_||_||_t|_t|| |_||_ t!|dSN)"r\rfr]rgr^rhrirjrkrlr_rmrZrnrorprcopyfiltersrtestsrglobalsrqrErFrtrsrZpoliciesrUrLis_asyncr`)selfr\rfr]rgr^rhrirjrkrlr_rmrLrnrZrorprqrrrsrtrur?r?r@__init__#s6%      zEnvironment.__init__)rTr<cCs|jt||gdS)z\Adds an extension after the environment was created. .. versionadded:: 2.5 N)rLupdaterU)r|rTr?r?r@ add_extensionoszEnvironment.add_extension) attributesr<cKs,|D]\}}t||st|||qdS)zAdd the items to the instance of the environment if they do not exist yet. This is used by :ref:`extensions ` to register callbacks and configuration values without breaking inheritance. N)itemshasattrsetattr)r|rkeyvaluer?r?r@extendvs zEnvironment.extend)r\rfr]rgr^rhrirjrkrlrLrnrZrorprqrrrsrtr<cCstt}|d=|d=|d=t|j}|j|jd|_||_| D]\}}|t k rJt |||qJ|t k r|t ||_ n t|j |_ i|_|j D]\}}|||j|<q| t k r|jt|| t|S)agCreate a new overlay environment that shares all the data with the current environment except for cache and the overridden attributes. Extensions cannot be removed for an overlayed environment. An overlayed environment automatically gets all the extensions of the environment it is linked to plus optional extra extensions. Creating overlays should happen after the initial environment was set up completely. Not all attributes are truly linked, some are just copied over so modifications on the original environment may not shine through. r|rrrLT)rHlocalsobject__new__ __class____dict__r~ overlayedrarr1rrErFrJrLbindrUr`)r|r\rfr]rgr^rhrirjrkrlrLrnrZrorprqrrrsrtr;rvrrr?r?r@overlays$!    zEnvironment.overlayr<cCst|S)zThe lexer for this environment.r!r|r?r?r@lexerszEnvironment.lexercCstt|jdddS)z)Iterates over the extensions by priority.cSs|jSrv)priorityxr?r?r@z-Environment.iter_extensions..)r)itersortedrLvaluesrr?r?r@iter_extensionsszEnvironment.iter_extensions)objargumentr<c Csz ||WStttfk rt|trrz t|}Wntk rJYn(Xzt||WYStk rpYnX|j||dYSXdS)z:Get an item or attribute of an object but prefer the item.rnameN)AttributeError TypeError LookupErrorrMrN ExceptiongetattrrZ)r|rrattrr?r?r@getitems   zEnvironment.getitem)r attributer<c CsZz t||WStk r YnXz ||WStttfk rT|j||dYSXdS)zGet an item or attribute of an object but prefer the attribute. Unlike :meth:`getitem` the attribute *must* be a string. rN)rrrrrZ)r|rrr?r?r@rs  zEnvironment.getattr)rrr;kwargscontexteval_ctx is_filterr<c CsP|r|j}d} n |j}d} ||} | dkrd| d|d} t|trz |Wn2tk r} z| d| d} W5d} ~ XYnXt| |f|dk r|nd}|dk r|ni}t | } | tj kr|dkrtd | d | d |nV| tj kr.|dkr |dk r|j }nt|}| d |n| tjkrF| d || ||S) NfiltertestzNo z named .z (z-; did you forget to quote the callable name?)r?zAttempted to invoke a context z without context.r)rxrygetrMr)_fail_with_undefined_errorrrr*Zfrom_objrinsertZ eval_contextrr%rK)r|rrr;rrrrZenv_mapZ type_namefuncmsgeZpass_argr?r?r@_filter_test_commons@    "        zEnvironment._filter_test_common)rrr;rrrr<c Cs|||||||dS)a/Invoke a filter on a value the same way the compiler does. This might return a coroutine if the filter is running from an environment in async mode and the filter supports async execution. It's your responsibility to await this if needed. .. versionadded:: 2.7 Trr|rrr;rrrr?r?r@ call_filterszEnvironment.call_filterc Cs|||||||dS)aInvoke a test on a value the same way the compiler does. This might return a coroutine if the test is running from an environment in async mode and the test supports async execution. It's your responsibility to await this if needed. .. versionchanged:: 3.0 Tests support ``@pass_context``, etc. decorators. Added the ``context`` and ``eval_ctx`` parameters. .. versionadded:: 2.7 Frrr?r?r@ call_test-szEnvironment.call_test)sourcerfilenamer<cCs6z||||WStk r0|j|dYnXdS)aParse the sourcecode and return the abstract syntax tree. This tree of nodes is used by the compiler to convert the template into executable source- or bytecode. This is useful for debugging or to extract information from templates. If you are :ref:`developing Jinja extensions ` this gives you a good overview of the node tree generated. rN)_parserhandle_exceptionr|rrrr?r?r@parseFszEnvironment.parsecCst||||S)z8Internal parsing function used by `parse` and `compile`.)r&rrr?r?r@rZszEnvironment._parsecCs@t|}z|j|||WStk r:|j|dYnXdS)aLex the given sourcecode and return a generator that yields tokens as tuples in the form ``(lineno, token_type, value)``. This can be useful for :ref:`extension development ` and debugging templates. This does not perform preprocessing. If you want the preprocessing of the extensions to be applied you have to filter source through the :meth:`preprocess` method. rN)rNrZ tokeniterrrrr?r?r@lex`s zEnvironment.lexcstfdd|t|S)zPreprocesses the source with all extensions. This is automatically called for all parsing and compiling methods but *not* for :meth:`lex` because there you usually only want the actual source tokenized. cs||Srv) preprocess)srrrr?r@rrz(Environment.preprocess..)rrrNrr?rr@rus  zEnvironment.preprocess)rrrstater<cCsR||||}|j||||}|D]$}||}t|ts(t|||}q(|S)zCalled by the parser to do the preprocessing and filtering for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. )rrtokenizerZ filter_streamrMr$)r|rrrrstreamextr?r?r@ _tokenizes    zEnvironment._tokenize)rrr defer_initr<cCst||||||jdS)z|Internal hook that can be overridden to hook a different generate method in. .. versionadded:: 2.5 )rrn)r rn)r|rrrrr?r?r@ _generates zEnvironment._generate)rrr<cCs t||dS)z{Internal hook that can be overridden to hook a different compile method in. .. versionadded:: 2.5 exec)compile)r|rrr?r?r@_compileszEnvironment._compilezte.Literal[False])rrrrawrr<cCsdSrvr?r|rrrrrr?r?r@rs zEnvironment.compilezte.Literal[True]cCsdSrvr?rr?r?r@rs cCs|d}zRt|tr"|}||||}|j||||d}|r>|WS|dkrJd}|||WStk rv|j|dYnXdS)aCompile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated filename of the template on the file system. If the template came from a database or memory this can be omitted. The return value of this method is a python code object. If the `raw` parameter is `True` the return value will be a string with python code equivalent to the bytecode returned otherwise. This method is mainly used internally. `defer_init` is use internally to aid the module code generator. This causes the generated code to be able to import without the global environment variable to be set. .. versionadded:: 2.4 `defer_init` parameter added. N)rz