U Wn{gl@sDdZddlZddlmZddlmZddlmZmZddl m Z m Z m Z m Z mZmZmZmZmZddlmZmZmZddlmZmZmZmZmZmZmZmZd d d d d dddddddddgZ eZ!ddZ"e#Z$e#Z%ddZ&ddZ'd7ddZ(Gdd d e#Z)ddZ*Gd d!d!e+Z,e fd"d#Z-Gd$d%d%ee,Z.zdd&l/m0Z0e01e.WnHe2k rzdd&l3m0Z0e01e.Wne2k rYnXYnXGd'd(d(e#Z4Gd)d*d*e#Z5Gd+d d e5Z6eGd,d-d-e#Z7Gd.d d e#Z8eGd/d0d0e#Z9d8d1d2Z:eGd3d4d4e9Z;eGd5d6d6e9Z%r&cCsLg}tt|}|D]0}||t|drtdt||Sqt|S)z@Concatenation that escapes if necessary and converts to unicode.Z__html__)rrappendhasattrrjoinrr )seqZbufiteratorargr"r"r%r+s   cCsttt|S)z4Simple args to unicode conversion and concatenation.)r rr)r,r"r"r%r6sc Csh|dkr i}|r|}nt|pdf|}|rX|r6t|}t|D]\}} | tk r>| ||<q>|||||S)z(Internal helper to for context creation.Nr")dictrr Z context_class) environmentZ template_nameblocksvarsZsharedglobalslocalsparentkeyvaluer"r"r% new_context;s  r8c@s(eZdZdZddZddZddZdS) rzThe `self` in templates.cCs ||_dSr!)_TemplateReference__contextselfcontextr"r"r%__init__SszTemplateReference.__init__cCs|jj|}t||j|dSNr)r9r1BlockReference)r;namer1r"r"r% __getitem__Vs zTemplateReference.__getitem__cCsd|jj|jjfS)Nz<%s %r>) __class____name__r9r@r;r"r"r%__repr__ZszTemplateReference.__repr__N)rC __module__ __qualname____doc__r=rArEr"r"r"r%rPscCs t|d|S)N__func__)getattrr#r"r"r% _get_funcasrKc@seZdZddZdS) ContextMetac Csvt||||}|dkr|St|j}ttj}t|j}ttj}||k r\||kr\d|_n||krr||krrd|_|S)Nr"T)type__new__rKresolveContextresolve_or_missing_legacy_resolve_mode_fast_resolve_mode) clsr@basesdrvrOZdefault_resolverQZdefault_resolve_or_missingr"r"r%rNgs     zContextMeta.__new__N)rCrFrGrNr"r"r"r%rLesrLcCs,||jkr|j|S||jkr(|j|S|Sr!r2r5)r<r6r r"r"r%rQ}s     rQc@seZdZdZdZdZddZddZd$dd Zd d Z d d Z ddZ ddZ e ddZd%ddZddZedZedZedZeredZedZedZ[ddZd d!Zd"d#ZdS)&rPaThe 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% sz#Context.__init__..)r5r2r0reval_ctxset exported_varsr@r/rr1rSrrQ)r;r0r5r@r1r"r"r%r=szContext.__init__cCs\z$|j|}||d}||Wn(tk rL|jjd|ddYSXt||||S)zRender a parent block.#there is no parent block called %r.superr@)r1index LookupErrorr0 undefinedr?)r;r@Zcurrentr1rer"r"r%rcs   z Context.superNcCs(z ||WStk r"|YSXdS)zfReturns an item from the template context, if it doesn't exist `default` is returned. N)KeyError)r;r6defaultr"r"r%gets z Context.getcCs6|jrt||}n ||}|tkr2|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)rRrQr r0rgr;r6rWr"r"r%rOs   zContext.resolvecCs,|jr"||}t|trt}|St||S)zxResolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found. )rRrO isinstance Undefinedr rQrkr"r"r%rQs   zContext.resolve_or_missingcstfddjDS)z+Get a new dict with the exported variables.c3s|]}|j|fVqdSr!)r2)rZr[rDr"r%r]sz'Context.get_exported..)r/r`rDr"rDr% get_exportedszContext.get_exportedcCs(|js |jS|js|jSt|jf|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. )r2r5r/rDr"r"r%get_alls zContext.get_allcOsd}t|dr0|j}dD]}t||r|}q0qt|trt|ddrR|f|}n2t|ddrl|jf|}nt|ddr|jf|}z |||WStk r|jdYSXd 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`. T__call__)contextfunctionr environmentfunctionrqrr rrzGvalue was undefined because a callable raised a StopIteration exceptionN) r*rprlrrJr^r0 StopIterationrg)Z_Context__selfZ _Context__objargskwargsZ__traceback_hide__fnZfn_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]sz"Context.derived..)r8r0r@ror^r1updater)r;r4r<r"r"r%derived s zContext.derivedcs$fdd}ttj|_|_|S)Ncst|Sr!)rJrorDmethr"r%r&r'zContext._all..)rJr/rHrC)r|proxyr"r{r%_alls z Context._allkeysvaluesitemsiterkeys itervaluesrcCs||jkp||jkSr!rXr;r@r"r"r% __contains__(szContext.__contains__cCs||}|tkrt||S)zTLookup a variable or raise `KeyError` if the variable is undefined. )rQr rh)r;r6itemr"r"r%rA+s zContext.__getitem__cCsd|jjt||jfS)Nz <%s %s of %r>)rBrCreprror@rDr"r"r%rE4s  zContext.__repr__)N)N)rCrFrGrHrRrSr=rcrjrOrQrnror rwrzr~rrrrrrrrrArEr"r"r"r%rPs2     !  rP)Mappingc@s0eZdZdZddZeddZeddZdS) r?z"One block on a template reference.cCs||_||_||_||_dSr!)r@_context_stack_depth)r;r@r<stackdepthr"r"r%r=KszBlockReference.__init__cCsF|jdt|jkr,|jjjd|jddSt|j|j|j|jdS)zSuper the block.rarbrcrd)rlenrrr0rgr@r?rDr"r"r%rcQszBlockReference.supercCs,t|j|j|j}|jjjr(t|}|Sr!)r rrrr^ autoescaperr;rWr"r"r%rp[s zBlockReference.__call__N) rCrFrGrHr=propertyrcr rpr"r"r"r%r?Hs  r?c@seZdZdZeZeZeZdZ dddZ ddZ dd Z e d d Ze d d Ze d d Ze dd Ze dd Ze dd Ze ddZe ddZddZeddZeZ[ddZdS)LoopContextBasez%A loop context for dynamic iteration.NrcCs"||_||_d|_||_t|_dS)N) _undefined_recurseindex0depth0r _last_checked_value)r;rgrecurserr"r"r%r=ks zLoopContextBase.__init__cGs|s td||jt|S)z7Cycles among the arguments with the current loop index.zno items for cycling given) TypeErrorrr)r;rtr"r"r%cyclerszLoopContextBase.cyclecGs|j|kr||_dSdS)z9Checks whether the value has changed since the last call.TF)r)r;r7r"r"r%changedxs zLoopContextBase.changedcCs |jdkSr>rr#r"r"r%r&r'zLoopContextBase.cCs |jtkSr!)_after_last_iterationr#r"r"r%r&r'cCs |jdSNrarr#r"r"r%r&r'cCs |j|jSr!)lengthrr#r"r"r%r&r'cCs |j|jSr!)rrer#r"r"r%r&r'cCs |jdSr)rr#r"r"r%r&r'cCs|jtkr|dS|jS)Nzthere is no previous item)_before_first_iterationrrDr"r"r%previtems  zLoopContextBase.previtemcCs|jtkr|dS|jS)Nzthere is no next item)rrrrDr"r"r%nextitems  zLoopContextBase.nextitemcCs|jSr!)rrDr"r"r%__len__szLoopContextBase.__len__cCs(|jdkrtd|||j|jdS)NzMTried to call non recursive loop. Maybe you forgot the 'recursive' modifier.ra)rrr)r;iterabler"r"r%loops zLoopContextBase.loopcCsd|jj|j|jfS)Nz <%s %r/%r>)rBrCrerrDr"r"r%rEs zLoopContextBase.__repr__)Nr)rCrFrGrHrr_currentrr_lengthr=rrrfirstZlastreZrevindexZ revindex0rrrrr rrprEr"r"r"r%rcs0          rc@s2eZdZd ddZeddZddZd d ZdS) rNrc CsVt||||t||_zt||_Wnttfk rFd|_YnX||_ dSr!) rr=iter _iteratorrrrAttributeError _safe_nextr)r;rrgrrr"r"r%r=s  zLoopContext.__init__cCs<|jdkr6t|j}t||_|jd}t|||_|jS)N)rtuplerrrr)r;rZiterations_doner"r"r%rs     zLoopContext.lengthcCst|Sr!)LoopContextIteratorrDr"r"r%__iter__szLoopContext.__iter__cCs*z t|jWStk r$tYSXdSr!)nextrrsrrDr"r"r%rs zLoopContext._safe_next)Nr)rCrFrGr=rrrrr"r"r"r%rs   c@s,eZdZdZdZddZddZddZd S) rz The iterator for a loop context.r<cCs ||_dSr!rr:r"r"r%r=szLoopContextIterator.__init__cCs|Sr!r"rDr"r"r%rszLoopContextIterator.__iter__cCsH|j}|jd7_|jtkr$t|j|_|j|_||_|j|fSr)r<rrrrsrrr)r;Zctxr"r"r%__next__s  zLoopContextIterator.__next__N)rCrFrGrH __slots__r=rrr"r"r"r%rs rc@s:eZdZdZd ddZeeddZddZd d Z dS) rzWraps a macro function.Nc CsV||_||_t||_||_||_||_||_||_d|k|_ |dkrL|j }||_ dS)Ncaller) _environment_funcr_argument_countr@ arguments catch_kwargs catch_varargsrexplicit_callerr_default_autoescape) r;r0funcr@rrrrZdefault_autoescaper"r"r%r=s  zMacro.__init__c Os|r*t|dtr*|dj}|dd}n|j}t|d|j}t|}d}||jkrt|jt|dD]F\}}z| |} Wnt k rt } YnX|dkrd}| | qnn|j }|jr|s| dd} | dkr|jjddd} | | |jr | |n8|rBd|kr(td|jtd |jtt|f|jr`| ||jdn(t||jkrtd |jt|jf|||S) NrraFrTzNo 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))rlrrrrxrr enumeraterpoprhr r)rrrrgrrr@rrr_invoke) r;rtrurrZoffZ found_calleridxr@r7rr"r"r%rpsR        zMacro.__call__cCs|j|}|rt|}|S)z=This method is being swapped out by the async implementation.)rr)r;rrrWr"r"r%rEs z Macro._invokecCs$d|jj|jdkrdpt|jfS)Nz<%s %s>Z anonymous)rBrCr@rrDr"r"r%rELszMacro.__repr__)N) rCrFrGrHr=r r rprrEr"r"r"r%rs  Jc@seZdZdZdZdedefddZeddZ edd Z e Z Z Z ZZZZZZZZZZZZZZZZZZZ Z!Z"Z#Z$Z%d d Z&d d Z'ddZ(ddZ)ddZ*ddZ+ddZ,e,Z-ddZ.dS)rmazThe default undefined type. This undefined type can be printed and iterated over, but every other access will raise an :exc:`jinja2.exceptions.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;hintobjr@excr"r"r%r=eszUndefined.__init__cOsl|jdkrX|jtkr d|j}q^t|jtsBdt|j|jf}q^dt|j|jf}n|j}||dS)z{Regular callback function for undefined objects that raises an `jinja2.exceptions.UndefinedError` on call. Nz%r is undefinedz%s has no element %rz%r has no attribute %r)rrr rrlrr r)r;rtrurr"r"r%_fail_with_undefined_errorks    z$Undefined._fail_with_undefined_errorcCs |dddkrt||S)Nr__)rrrr"r"r% __getattr__szUndefined.__getattr__cCst|t|kSr!)rMr;otherr"r"r%__eq__szUndefined.__eq__cCs || Sr!)rrr"r"r%__ne__szUndefined.__ne__cCs tt|Sr!)idrMrDr"r"r%__hash__szUndefined.__hash__cCsdS)Nr(r"rDr"r"r%__str__szUndefined.__str__cCsdSr>r"rDr"r"r%rszUndefined.__len__ccsdSr!r"rDr"r"r%rszUndefined.__iter__cCsdS)NFr"rDr"r"r% __nonzero__szUndefined.__nonzero__cCsdS)Nrmr"rDr"r"r%rEszUndefined.__repr__)/rCrFrGrHrr rr=r rr__add____radd____mul____rmul__Z__div__Z__rdiv__ __truediv__ __rtruediv__ __floordiv__ __rfloordiv____mod____rmod____pos____neg__rprA__lt____le____gt____ge____int__ __float__ __complex____pow____rpow____sub____rsub__rrrrrrr__bool__rEr"r"r"r%rmSst   rmcs`dkr,ddl}|t|tjdkr8tfddGfddd}|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|jdkrX|jtkr 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)rrr rrlrr Zwarning)Zundefr)loggerr"r% _log_messages    z,make_logging_undefined.._log_messagecsfeZdZfddZfddZfddZerTfddZfd d Znfd d Z d S)z0make_logging_undefined..LoggingUndefinedc sRzj|f||WS|jk rL}zdt||W5d}~XYnXdS)NzTemplate variable error: %s)rrerrorstr)r;rtrue)baserr"r%rs zKmake_logging_undefined..LoggingUndefined._fail_with_undefined_errorcs|}||Sr!)rrrrr"r%rs z8make_logging_undefined..LoggingUndefined.__str__cs|}||Sr!)rrrr"r%rs 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) rCrFrGrrrrrrrr"rrrr"r%LoggingUndefinedsr)loggingZ getLoggerrCZ addHandlerZ StreamHandlersysstderrrm)rrrrr"rr%make_logging_undefineds  #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<|jdkr2|jtkrd|jSdt|j|jfSd|jS)Nz{{ %s }}z{{ no such element: %s[%r] }}z!{{ undefined value printed: %s }})rrr rr rDr"r"r%r s   zDebugUndefined.__str__N)rCrFrGrHrrr"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)rCrFrGrHrrmrrrrrrrrrr"r"r"r%rsr)NNNN)NN)>rHr itertoolsrtypesrZ jinja2.nodesrrZ jinja2.utilsrrrr r r r r rZjinja2.exceptionsrrrZjinja2._compatrrrrrrrr__all__rr objectrrrrr8rrKrMrLrQrPZcollections.abcrregister ImportError collectionsr?rrrrrmrrrrr"r"r"r%sv   ,(   9   F'mU Q