a `w@sJdZddlZddlmZddlmZddlmZddlmZddlm Z dd l m Z dd l m Z dd l m Z dd l mZdd l mZddl mZddl mZddl mZddl mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z gdZ!eZ"ddZ#dd Z$d!d"Z%d?d#d$Z&Gd%d&d&e'Z(d'd(Z)Gd)d*d*e*Z+efd+d,Z,Gd-d.d.ee+Z-e j./e-Gd/d0d0e'Z0e Gd1d2d2Z1Gd3d4d4e'Z2eGd5d6d6e'Z3d@d7d8Z4Gd9d:d:e3Z5eGd;d<dd>e3Z7e3`8e5`8e6`8e7`8dS)Az;The runtime functions and state used by compiled templates.N)chain) MethodType)escape)Markup) soft_unicode)abc)imap)implements_iterator)implements_to_string) iteritems)PY2) string_types) text_type)with_metaclass)TemplateNotFound)TemplateRuntimeError)UndefinedError) EvalContext)concat)evalcontextfunction) internalcode)missing) Namespace)object_type_repr) LoopContextTemplateReferenceMacrorrrrr markup_join unicode_join to_stringidentityrr UndefinedcCs|S)zLReturns its argument. Useful for certain things in the environment. xr#r#2/usr/lib/python3.9/site-packages/jinja2/runtime.pyr!7sr!cCsLg}tt|}|D]0}||t|drtdt||Sqt|S)z@Concatenation that escapes if necessary and converts to unicode.__html__)r rappendhasattrrjoinrr)seqbufiteratorargr#r#r&r>s   rcCsttt|S)z4Simple args to unicode conversion and concatenation.)rr r)r,r#r#r&rIsrc Csl|dur i}|r|}nt|pdfi|}|r\|r:t|}t|D]\}} | turB| ||<qB|||||S)z%Internal helper for context creation.Nr#)dictr rZ context_class) environmentZ template_nameblocksvarsZsharedglobalslocalsparentkeyvaluer#r#r& new_contextNs  r9c@s(eZdZdZddZddZddZdS) rzThe `self` in templates.cCs ||_dSN)_TemplateReference__context)selfcontextr#r#r&__init__lszTemplateReference.__init__cCs|jj|}t||j|dSNr)r;r2BlockReference)r<namer2r#r#r& __getitem__os zTemplateReference.__getitem__cCsd|jj|jjfS)Nz<%s %r>) __class____name__r;rAr<r#r#r&__repr__sszTemplateReference.__repr__N)rD __module__ __qualname____doc__r>rBrFr#r#r#r&risrcCs t|d|S)N__func__)getattrr$r#r#r& _get_funcwsrLc@seZdZddZdS) ContextMetac Csvt||||}|dkr|St|j}ttj}t|j}ttj}||ur\||ur\d|_n||urr||urrd|_|S)Nr#T)type__new__rLresolveContextresolve_or_missing_legacy_resolve_mode_fast_resolve_mode) ZmcsrAbasesdrvrPZdefault_resolverRZdefault_resolve_or_missingr#r#r&rO|s$    zContextMeta.__new__N)rDrGrHrOr#r#r#r&rM{srMcCs,||jvr|j|S||jvr(|j|S|Sr:r3r6)r=r7rr#r#r&rRs     rRc@seZdZdZdZdZddZddZd$dd Zd d Z d d Z ddZ ddZ e ddZd%ddZddZedZedZedZeredZedZedZ[ddZd d!Zd"d#ZdS)&rQaThe template context holds the variables of a template. It stores the values passed to the template and also the names the template exports. Creating instances is neither supported nor useful as it's created automatically at various stages of the template evaluation and should not be created by hand. The context is immutable. Modifications on :attr:`parent` **must not** happen and modifications on :attr:`vars` are allowed from generated template code only. Template filters and global functions marked as :func:`contextfunction`\s get the active context passed as first argument and are allowed to access the context read-only. The template context supports read only dict operations (`get`, `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`, `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve` method that doesn't fail with a `KeyError` but returns an :class:`Undefined` object for missing variables. FcCs\||_i|_||_t|j||_t|_||_tddt |D|_ |j rXt t ||_ dS)Ncss|]\}}||gfVqdSr:r#.0kvr#r#r& z#Context.__init__..)r6r3r1reval_ctxset exported_varsrAr0r r2rTrrR)r<r1r6rAr2r#r#r&r>szContext.__init__cCsZz$|j|}||d}||Wn&tyJ|jjd|ddYS0t||||S)zRender a parent block.r#there is no parent block called %r.superrA)r2index LookupErrorr1 undefinedr@)r<rAcurrentr2rer#r#r&rcs    z Context.superNcCs&z ||WSty |YS0dS)zfReturns an item from the template context, if it doesn't exist `default` is returned. N)KeyError)r<r7defaultr#r#r&gets  z Context.getcCs6|jrt||}n ||}|tur2|jj|dS|S)zLooks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up. rd)rSrRrr1rgr<r7rWr#r#r&rPs   zContext.resolvecCs,|jr"||}t|trt}|St||S)zxResolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found. )rSrP isinstancer"rrRrlr#r#r&rRs   zContext.resolve_or_missingcstfddjDS)z+Get a new dict with the exported variables.c3s|]}|j|fVqdSr:)r3)rZr[rEr#r&r]r^z'Context.get_exported..)r0rarEr#rEr& get_exportedszContext.get_exportedcCs,|js |jS|js|jSt|jfi|jS)zReturn the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it. )r3r6r0rEr#r#r&get_alls zContext.get_allcOst|dr,|j}dD]}t||r|}q,qt|rt|dddurP|f|}n:t|dddurn|jf|}nt|dddur|jf|}z||i|WSty|jdYS0d S) zCall the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a :func:`contextfunction` or :func:`environmentfunction`. __call__)contextfunctionrenvironmentfunctionrqFTrrrzGvalue was undefined because a callable raised a StopIteration exceptionN)r*rpcallablerKr_r1 StopIterationrg)Z_Context__selfZ _Context__objargskwargsfnZfn_typer#r#r&calls&     z Context.callcCsDt|j|ji|dd|}|j|_|jddt|jD|S)zInternal helper function to create a derived context. This is used in situations where the system needs a new context in the same template that is independent. TNcss|]\}}|t|fVqdSr:)listrYr#r#r&r]3r^z"Context.derived..)r9r1rAror_r2updater )r<r5r=r#r#r&derived*s zContext.derivedcs$fdd}ttj|_|_|S)Ncst|Sr:)rKrorEmethr#r&proxy7szContext._all..proxy)rKr0rIrD)r}r~r#r|r&_all6s z Context._allkeysvaluesitemsiterkeys itervaluesr cCs||jvp||jvSr:rXr<rAr#r#r& __contains__IszContext.__contains__cCs||}|turt||S)zTLookup a variable or raise `KeyError` if the variable is undefined. )rRrri)r<r7itemr#r#r&rBLs zContext.__getitem__cCsd|jjt||jfS)Nz <%s %s of %r>)rCrDreprrorArEr#r#r&rFUs  zContext.__repr__)N)N)rDrGrHrIrSrTr>rcrkrPrRrnrorrxr{rrrrr rrr rrBrFr#r#r#r&rQs2     %  rQc@s0eZdZdZddZeddZeddZdS) r@z"One block on a template reference.cCs||_||_||_||_dSr:)rA_context_stack_depth)r<rAr=stackdepthr#r#r&r>cszBlockReference.__init__cCsF|jdt|jkr,|jjjd|jddSt|j|j|j|jdS)zSuper the block.rrbrcrd)rlenrrr1rgrAr@rEr#r#r&rcis  zBlockReference.supercCs,t|j|j|j}|jjjr(t|}|Sr:)rrrrr_ autoescaperr<rWr#r#r&rprs zBlockReference.__call__N) rDrGrHrIr>propertyrcrrpr#r#r#r&r@`s  r@c@seZdZdZdZdZeZeZeZ eZ d+ddZ e ddZ ed d Zd d Zed dZeddZeddZeddZeddZddZeddZeddZeddZdd Zd!d"Zd#d$Zd%d&Zed'd(Zd)d*Z dS),rzeA wrapper iterable for dynamic ``for`` loops, with information about the loop and iteration. NrcCs(||_|||_||_||_||_dS)a@ :param iterable: Iterable to wrap. :param undefined: :class:`Undefined` class to use for next and previous items. :param recurse: The function to render the loop body when the loop is marked recursive. :param depth0: Incremented when looping recursively. N) _iterable _to_iterator _iterator _undefined_recursedepth0)r<iterablergZrecurserr#r#r&r>s  zLoopContext.__init__cCst|Sr:)iter)rr#r#r&rszLoopContext._to_iteratorcCsj|jdur|jSzt|j|_WnBtybt|j}|||_t||j|jt u|_Yn0|jS)zLength of the iterable. If the iterable is a generator or otherwise does not have a size, it is eagerly evaluated to get a size. N) _lengthrr TypeErrorryrrre_afterrr<rr#r#r&lengths     zLoopContext.lengthcCs|jSr:)rrEr#r#r&__len__szLoopContext.__len__cCs |jdS)zBHow many levels deep a recursive loop currently is, starting at 1.r)rrEr#r#r&rszLoopContext.depthcCs |jdS)z-Current iteration of the loop, starting at 1.rindex0rEr#r#r&reszLoopContext.indexcCs |j|jS)zrNumber of iterations from the end of the loop, ending at 0. Requires calculating :attr:`length`. )rrerEr#r#r& revindex0szLoopContext.revindex0cCs |j|jS)zrNumber of iterations from the end of the loop, ending at 1. Requires calculating :attr:`length`. )rrrEr#r#r&revindexszLoopContext.revindexcCs |jdkS)z0Whether this is the first iteration of the loop.rrrEr#r#r&firstszLoopContext.firstcCs$|jtur|jSt|jt|_|jS)a Return the next element in the iterable, or :data:`missing` if the iterable is exhausted. Only peeks one item ahead, caching the result in :attr:`_last` for use in subsequent checks. The cache is reset when :meth:`__next__` is called. )rrnextrrEr#r#r& _peek_nexts zLoopContext._peek_nextcCs |tuS)zWhether this is the last iteration of the loop. Causes the iterable to advance early. See :func:`itertools.groupby` for issues this can cause. The :func:`groupby` filter avoids that issue. )rrrEr#r#r&lastszLoopContext.lastcCs|jr|dS|jS)zZThe item in the previous iteration. Undefined during the first iteration. zthere is no previous item)rr_beforerEr#r#r&previtems zLoopContext.previtemcCs|}|tur|dS|S)zThe item in the next iteration. Undefined during the last iteration. Causes the iterable to advance early. See :func:`itertools.groupby` for issues this can cause. The :func:`groupby` filter avoids that issue. zthere is no next item)rrrrr#r#r&nextitems  zLoopContext.nextitemcGs|s td||jt|S)zReturn a value from the given args, cycling through based on the current :attr:`index0`. :param args: One or more values to cycle through. zno items for cycling given)rrr)r<rur#r#r&cycleszLoopContext.cyclecGs|j|kr||_dSdS)zReturn ``True`` if previously called with a different value (including when called for the first time). :param value: One or more values to compare to the last call. TF)_last_changed_value)r<r8r#r#r&changed s zLoopContext.changedcCs|Sr:r#rEr#r#r&__iter__szLoopContext.__iter__cCsF|jtur|j}t|_n t|j}|jd7_|j|_||_||fS)Nr)rrrrr_currentrrr#r#r&__next__s  zLoopContext.__next__cCs&|jdurtd|j||j|jdS)zWhen iterating over nested data, render the body of the loop recursively with the given inner iterable data. The loop must have the ``recursive`` marker for this to work. NzCThe loop must have the 'recursive' marker to be called recursively.)r)rrrrr#r#r&rp(s  zLoopContext.__call__cCsd|jj|j|jfS)Nz <%s %d/%d>)rCrDrerrEr#r#r&rF6szLoopContext.__repr__)Nr)!rDrGrHrIrrrrrrrr> staticmethodrrrrrrerrrrrrrrrrrrrprFr#r#r#r&rzsJ                rc@s:eZdZdZd ddZeeddZddZd d Z dS) rzWraps a macro function.Nc CsV||_||_t||_||_||_||_||_||_d|v|_ |durL|j }||_ dS)Ncaller) _environment_funcr_argument_countrA arguments catch_kwargs catch_varargsrexplicit_callerr_default_autoescape) r<r1funcrArrrrZdefault_autoescaper#r#r&r>=s   zMacro.__init__c Os|r*t|dtr*|dj}|dd}n|j}t|d|j}t|}d}||jkr|jt|dD]@}z||}Wnt yt }Yn0|dkrd}| |qjn|j }|j r|s|dd} | dur|jjddd} | | |jr| |n8|r6d|vrtd|jtd |jtt|f|jrT| ||jdn(t||jkr|td |jt|jf|||S) NrrFrTzNo caller definedrdzamacro %r was invoked with two values for the special caller argument. This is most likely a bug.z%macro %r takes no keyword argument %rz+macro %r takes not more than %d argument(s))rmrrrryrrrpoprirr)rrrrgrrrArrr_invoke) r<rurvrrZoffZ found_callerrAr8rr#r#r&rpUsZ         zMacro.__call__cCs|j|}|rt|}|S)z=This method is being swapped out by the async implementation.)rr)r<rrrWr#r#r&rs z Macro._invokecCs$d|jj|jdurdpt|jfS)Nz<%s %s>Z anonymous)rCrDrArrEr#r#r&rFszMacro.__repr__)N) rDrGrHrIr>rrrprrFr#r#r#r&r:s  Nrc@seZdZdZdZdedefddZeddZ e dd Z e d d Z e Z ZZZZZZZZZZZZZZZZZZZ Z!Z"Z#Z$Z%Z&Z'd d Z(ddZ)ddZ*ddZ+ddZ,ddZ-ddZ.e.Z/ddZ0dS)r"ahThe default undefined type. This undefined type can be printed and iterated over, but every other access will raise an :exc:`UndefinedError`: >>> foo = Undefined(name='foo') >>> str(foo) '' >>> not foo True >>> foo + 42 Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined _undefined_hint_undefined_obj_undefined_name_undefined_exceptionNcCs||_||_||_||_dSr:r)r<hintobjrAexcr#r#r&r>szUndefined.__init__cCsT|jr |jS|jtur d|jSt|jts@dt|j|jfSdt|j|jfS)zXBuild a message about the undefined value based on how it was accessed. z%r is undefinedz%s has no element %rz%r has no attribute %r)rrrrrmrrrEr#r#r&_undefined_messages   zUndefined._undefined_messagecOs||jdS)zeRaise an :exc:`UndefinedError` when operations are performed on the undefined value. N)rr)r<rurvr#r#r&_fail_with_undefined_errorsz$Undefined._fail_with_undefined_errorcCs |dddkrt||S)N__)AttributeErrorrrr#r#r& __getattr__szUndefined.__getattr__cCst|t|uSr:)rNr<otherr#r#r&__eq__!szUndefined.__eq__cCs || Sr:)rrr#r#r&__ne__$szUndefined.__ne__cCs tt|Sr:)idrNrEr#r#r&__hash__'szUndefined.__hash__cCsdS)Nr(r#rEr#r#r&__str__*szUndefined.__str__cCsdSr?r#rEr#r#r&r-szUndefined.__len__ccsdSr:r#rEr#r#r&r0szUndefined.__iter__cCsdS)NFr#rEr#r#r& __nonzero__4szUndefined.__nonzero__cCsdS)Nr"r#rEr#r#r&rF9szUndefined.__repr__)1rDrGrHrI __slots__rrr>rrrrr__add____radd____mul____rmul__Z__div__Z__rdiv__ __truediv__ __rtruediv__ __floordiv__ __rfloordiv____mod____rmod____pos____neg__rprB__lt____le____gt____ge____int__ __float__ __complex____pow____rpow____sub____rsub__rrrrrrr__bool__rFr#r#r#r&r"s   1   !#%')+,,,r"cs`dur,ddl}|t|tjdur8tfddGfddd}|S)akGiven a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`. Nrcsn|jdurX|jtur d|j}q^t|jtsBdt|j|jf}q^dt|j|jf}n|j}d|dS)Nz%s is undefinedz%s has no element %sz%s has no attribute %szTemplate variable warning: %s)rrrrrmrrZwarning)Zundefr)loggerr#r& _log_messageYs    z,make_logging_undefined.._log_messagecsfeZdZfddZfddZfddZerTfddZfd d Znfd d Z d S)z0make_logging_undefined..LoggingUndefinedc sZzj|g|Ri|WS|jyT}z dt||WYd}~n d}~00dS)NzTemplate variable error: %s)rrerrorstr)r<rurve)baserr#r&rls zKmake_logging_undefined..LoggingUndefined._fail_with_undefined_errorcs|}||Sr:rrrrr#r&rss z8make_logging_undefined..LoggingUndefined.__str__cs|}||Sr:)rrrr#r&rxs z9make_logging_undefined..LoggingUndefined.__iter__cs|}||Sr:)rrrr#r&rs z.LoggingUndefined.__nonzero__cs|}||Sr:) __unicode__rrr#r&rs z.LoggingUndefined.__unicode__cs|}||Sr:)rrrr#r&rs z9make_logging_undefined..LoggingUndefined.__bool__N) rDrGrHrrrr rrrr#rrrr#r&LoggingUndefinedksr)loggingZ getLoggerrDZ addHandlerZ StreamHandlersysstderrr")rrrrr#rr&make_logging_undefined=s  %rc@s(eZdZdZdZddZddZeZdS)ChainableUndefinedaAn undefined that is chainable, where both ``__getattr__`` and ``__getitem__`` return itself rather than raising an :exc:`UndefinedError`. >>> foo = ChainableUndefined(name='foo') >>> str(foo.bar['baz']) '' >>> foo.bar['baz'] + 42 Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined .. versionadded:: 2.11.0 r#cCs|Sr:rrEr#r#r&r'szChainableUndefined.__html__cCs|Sr:r#)r<_r#r#r&rszChainableUndefined.__getattr__N)rDrGrHrIrr'rrBr#r#r#r&rs rc@seZdZdZdZddZdS)DebugUndefinedaAn undefined that returns the debug info when printed. >>> foo = DebugUndefined(name='foo') >>> str(foo) '{{ foo }}' >>> not foo True >>> foo + 42 Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined r#cCs<|jdur2|jturd|jSdt|j|jfSd|jS)Nz{{ %s }}z{{ no such element: %s[%r] }}z!{{ undefined value printed: %s }})rrrrrrEr#r#r&rs   zDebugUndefined.__str__N)rDrGrHrIrrr#r#r#r&rs rc@s6eZdZdZdZejZZZ Z Z Z Z ZdS)StrictUndefinedasAn undefined that barks on print and iteration as well as boolean tests and all kinds of comparisons. In other words: you can do nothing with it except checking if it's defined using the `defined` test. >>> foo = StrictUndefined(name='foo') >>> str(foo) Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined >>> not foo Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined >>> foo + 42 Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined r#N)rDrGrHrIrr"rrrrrrrrrr#r#r#r&rs r)NNNN)NN)9rIr itertoolsrtypesrZ markupsaferrrZ_compatrr r r r r rrr exceptionsrrrZnodesrZutilsrrrrrrZexportedr r!rrr9objectrrLrNrMrRrQMappingregisterr@rrr"rrrrrr#r#r#r&sz                            @ @y Y!