o a7@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 d7d8d9ejJeId:ejKd;eIfdeMd;ejNejOejPejQeRfd?ffd@dAZSdBejNejOd;ejNejOejPejQeRfd?ffdCdDZTdEd5dFejUejVeRejJdGfd;ejWeRdGffdHdIZXdTdJdKZYGdLd5d5ZZGdMd?d?Z[GdNdOdOZ\GdPdQdQZ]GdRdSdSZ^e[eZ__dS)UzKClasses for managing templates and their runtime and compile time options. N)ChainMap) lru_cache)partial)reduce)CodeType)Markup)nodes) CodeGenerator)generate)BLOCK_END_STRING)BLOCK_START_STRING)COMMENT_END_STRING)COMMENT_START_STRING)DEFAULT_FILTERS)DEFAULT_NAMESPACE)DEFAULT_POLICIES) DEFAULT_TESTS)KEEP_TRAILING_NEWLINE)LINE_COMMENT_PREFIX)LINE_STATEMENT_PREFIX) LSTRIP_BLOCKS)NEWLINE_SEQUENCE) TRIM_BLOCKS)VARIABLE_END_STRING)VARIABLE_START_STRING)TemplateNotFound)TemplateRuntimeError)TemplatesNotFound)TemplateSyntaxError)UndefinedError get_lexer)Lexer) TokenStream) EvalContext)Parser)Context) new_context) Undefined)_PassArg)concat)consume) import_string) internalcodeLRUCache)missing) BytecodeCache) Extension) BaseLoader _env_bound Environment)bound )maxsizeclsargsreturncGs||}d|_|S)a Return a new spontaneous environment. A spontaneous environment is used for templates created directly rather than through an existing environment. :param cls: Environment class to create. :param args: Positional arguments passed to environment. T)shared)r:r;envr?4/usr/lib/python3/dist-packages/jinja2/environment.pyget_spontaneous_environmentCs rAsizeTemplatecCs |dkrdS|dkr iSt|S)z*Return the cache class for the given size.rNr/)rBr?r?r@ create_cacheQs rDcachecCs&|durdSt|turiSt|jS)z(Create an empty copy of the given cache.N)typedictr0capacity)rEr?r?r@ copy_cache^s   rI environment extensionsr3cCs@i}|D]}t|trttjdt|}||||j<q|S)zuLoad the extensions from the list and bind it to the environment. Returns a dict of instantiated extensions. r3) isinstancestrtcastTyper- identifier)rJrKresult extensionr?r?r@load_extensionsks  rTcCsTt|jts Jd|j|jkr|jksJdJd|jdvs(Jd|S)z*Perform a sanity check on the environment.z5'undefined' must be a subclass of 'jinja2.Undefined'.z   z8'newline_sequence' must be one of '\n', '\r\n', or '\r'.) issubclass undefinedr)block_start_stringvariable_start_stringcomment_start_stringnewline_sequence)rJr?r?r@_environment_config_check}s$ r^c-@seZdZUdZdZdZdZejde d<dZ e Z ej de d<eZej ee d<ej de d <eeeeeeeeeeeed d edddd d ddfd ededededededejedejedededddedejej eej dfdedej edejej!dej"fd ej eej!ejegeffd!ejd"d#e#d$ed%ejd&d'ef,d(d)Z$d*ej eej dfd+dfd,d-Z%d.ej"d+dfd/d0Z&e'e'e'e'e'e'e'e'e'e'e'e'e'e'e'e'e'e'e'fd ededededededejedejedededejej eej dfdedej edejej!dej"fd ej eej!ejegeffd!ejd"d#e#d$ed%ejd&d+df(d1d2Z(e)d+e*fd3d4Z+d+ej,dfd5d6Z-d7ej"d8ej eej"fd+ej ej"effd9d:Z.d7ej"d;ed+ej"fdej eefd?ej"d@ejejej"dAejej0eej"fdBejedCeje1dDed+ej"fdEdFZ2    dd>ed?ej"d@ejejej"dAejej0eej"fdBejedCeje1d+ej"fdGdHZ3    dd>ed?ej"d@ejejej"dAejej0eej"fdBejedCeje1d+ej"fdIdJZ4e5  ddKed>ejedLejed+e6j7fdMdNZ8dKed>ejedLejed+e6j7fdOdPZ9  ddKed>ejedLejed+ej,ej:e#eeffdQdRZ;  ddKed>ejedLejed+efdSdTZ<  ddKed>ejedLejedUejed+e=f dVdWZ> ddKe6j7d>ejedLejedXed+ef dYdZZ?dKedLed+e@fd[d\ZAeBjC    ddKej ee6j7fd>ejedLejed]d^dXed+e@f d_d`ZDeBjC    ddKej ee6j7fd>ejedLejed]dadXed+ef dbd`ZDe5    ddKej ee6j7fd>ejedLejed]edXed+ej ee@ff dcd`ZD ddKedded+defdfdgZE   h  ddiej eeFjGfdejejHedjejej!egefdkejedlejej!egdfdmed+dfdndoZI  ddejejHedjejej!egefd+ejJefdpdqZKddKejed+drfdsdtZLduedved+efdwdxZMe5d>edyejej0eej"fd+dfdzd{ZNe5  dd>ej edfdvejedyejej0eej"fd+dfd|d}ZOe5  dd~ejPej edfdvejedyejej0eej"fd+dfddZQe5  ddej edejJej edffdvejedyejej0eej"fd+dfddZR  ddKej ee6j7fdyejej0eej"fd ejej dd+dfddZSdejej0eej"fd+ejTeej"ffddZUdS)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_classrCtemplate_classr?TirZblock_end_stringr[variable_end_stringr\comment_end_stringline_statement_prefixline_comment_prefix trim_blocks lstrip_blocksr]te.Literal['\n', '\r\n', '\r']keep_trailing_newlinerKr3 optimizedrYfinalize. autoescapeloaderr4 cache_size auto_reloadbytecode_cacher2 enable_asynccCs||_||_||_||_||_||_||_||_| |_| |_ | |_ | |_ ||_ ||_ ||_||_t|_t|_t|_||_t||_||_||_t|_t|| |_||_ t!|dSN)"rZrcr[rdr\rerfrgrhrir]rkrYrlrmrnrcopyfiltersrtestsrglobalsrorDrErrrqrpoliciesrTrKis_asyncr^)selfrZrcr[rdr\rerfrgrhrir]rkrKrlrYrmrnrorprqrrrsr?r?r@__init__#s6%       zEnvironment.__init__rSr<cCs|jt||gdS)z\Adds an extension after the environment was created. .. versionadded:: 2.5 N)rKupdaterT)r{rSr?r?r@ add_extensionoszEnvironment.add_extension attributescKs,|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.extendcCstt}|d=|d=|d=t|j}|j|jd|_||_| D]\}}|t ur3t |||q%|t ur>t ||_ nt|j |_ i|_|j D] \}}|||j|<qL| t urf|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{rprKT)rGlocalsobject__new__ __class____dict__r} overlayedr_rr1rrDrErIrKbindrTr^)r{rZrcr[rdr\rerfrgrhrirKrlrYrmrnrorprqrrr;rvrrr?r?r@overlays& !    zEnvironment.overlaycCst|S)zThe lexer for this environment.r!r{r?r?r@lexerszEnvironment.lexercCstt|jdddS)z)Iterates over the extensions by priority.cSs|jSrt)priorityxr?r?r@sz-Environment.iter_extensions..)r)itersortedrKvaluesrr?r?r@iter_extensionsszEnvironment.iter_extensionsobjargumentc Csz||WStttfy?t|tr6zt|}Wn ty#Ynwzt||WYSty5Ynw|j||dYSw)z:Get an item or attribute of an object but prefer the item.rname)AttributeError TypeError LookupErrorrLrM ExceptiongetattrrY)r{rrattrr?r?r@getitems      zEnvironment.getitem attributec CsRzt||WStyYnwz||WStttfy(|j||dYSw)zGet an item or attribute of an object but prefer the attribute. Unlike :meth:`getitem` the attribute *must* be a string. r)rrrrrY)r{rrr?r?r@rs   zEnvironment.getattrrrr;kwargscontexteval_ctx is_filterc CsZ|r|j}d} n|j}d} ||} | durOd| d|d} t|trKz |Wt| tyJ} z| d| d} WYd} ~ t| d} ~ wwt| |g|durW|nd}|dur`|ni}t | } | tj ur|durxtd | d | d |n'| tj ur|dur|dur|j }nt|}| d |n | tjur| d || |i|S) NfiltertestzNo z named .z (z-; did you forget to quote the callable name?)r?zAttempted to invoke a context z without context.r)rvrwgetrLr)_fail_with_undefined_errorrrr*from_objrinsert eval_contextrr%rJ)r{rrr;rrrrenv_map type_namefuncmsgepass_argr?r?r@_filter_test_commonsH          zEnvironment._filter_test_commonc C|||||||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 Cr)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_testsourcefilenamecCs2z||||WSty|j|dYdSw)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@parseFs  zEnvironment.parsecCst||||S)z8Internal parsing function used by `parse` and `compile`.)r&rrr?r?r@rZszEnvironment._parsecCs<t|}z |j|||WSty|j|dYdSw)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)rMr 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||Srt) preprocess)srrrr?r@rsz(Environment.preprocess..)rrrMrr?rr@rus  zEnvironment.preprocessstatecCsR||||}|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`. )rrtokenizer filter_streamrLr$)r{rrrrstreamextr?r?r@ _tokenizes     zEnvironment._tokenize defer_initcCst||||||jdS)z|Internal hook that can be overridden to hook a different generate method in. .. versionadded:: 2.5 )rrl)r rl)r{rrrrr?r?r@ _generates zEnvironment._generatecCs 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@_compiles zEnvironment._compilerawzte.Literal[False]cCdSrtr?r{rrrrrr?r?r@r zEnvironment.compilezte.Literal[True]cCrrtr?rr?r?r@rrcCsxd}z)t|tr|}||||}|j||||d}|r|WS|dur%d}|||WSty;|j|dYdSw)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