3 C\kl@sdZddlZddlmZddlmZddlmZmZddl 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.ydd&l/m0Z0e0j1e.Wne2k rfYnXGd'd(d(e#Z3Gd)d*d*e#Z4Gd+d d e4Z5eGd,d-d-e#Z6Gd.d d e#Z7eGd/d0d0e#Z8d8d1d2Z9eGd3d4d4e8Z:eGd5d6d6e8Z;e8`%sr$cCsLg}tt|}x4|D],}|j|t|drtdjt||SqWt|S)z@Concatenation that escapes if necessary and converts to unicode.Z__html__)rrappendhasattrrjoinrr )seqbufiteratorargr!r!r#r+s    cCsttt|S)z4Simple args to unicode conversion and concatenation.)r rr)r)r!r!r#r6sc Csl|dkr i}|r|}nt|pff|}|r\|r6t|}x$t|D]\}} | tk r@| ||<q@W|j||||S)z(Internal helper to for context creation.N)dictrr Z context_class) environmentZ template_nameblocksvarsZsharedglobalslocalsparentkeyvaluer!r!r# new_context;s  r6c@s(eZdZdZddZddZddZdS) rzThe `self` in templates.cCs ||_dS)N)_TemplateReference__context)selfcontextr!r!r#__init__SszTemplateReference.__init__cCs|jj|}t||j|dS)Nr)r7r/BlockReference)r8namer/r!r!r# __getitem__Vs zTemplateReference.__getitem__cCsd|jj|jjfS)Nz<%s %r>) __class____name__r7r<)r8r!r!r#__repr__ZszTemplateReference.__repr__N)r? __module__ __qualname____doc__r:r=r@r!r!r!r#rPscCs t|d|S)N__func__)getattr)r"r!r!r# _get_funcasrFc@seZdZddZdS) ContextMetac Csvtj||||}|fkr|St|j}ttj}t|j}ttj}||k r\||kr\d|_n||krr||krrd|_|S)NT)type__new__rFresolveContextresolve_or_missing_legacy_resolve_mode_fast_resolve_mode) clsr<basesdrvrJZdefault_resolverLZdefault_resolve_or_missingr!r!r#rIgs    zContextMeta.__new__N)r?rArBrIr!r!r!r#rGesrGcCs,||jkr|j|S||jkr(|j|S|S)N)r0r3)r9r4r r!r!r#rL}s     rLc@seZdZdZdZdZddZddZd$dd Zd d Z d d Z ddZ ddZ e ddZd%ddZddZedZedZedZeredZedZedZ[ddZd d!Zd"d#ZdS)&rKaThe 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|]\}}||gfVqdS)Nr!).0kvr!r!r# sz#Context.__init__..)r3r0r.reval_ctxset exported_varsr<r-rr/rNrrL)r8r.r3r<r/r!r!r#r:szContext.__init__c CsXy$|j|}|j|d}||Wn$tk rH|jjd|ddSXt||||S)zRender a parent block.z#there is no parent block called %r.super)r<)r/index LookupErrorr. undefinedr;)r8r<currentr/r\r!r!r#r[s   z Context.superNc Cs"y||Stk r|SXdS)zfReturns an item from the template context, if it doesn't exist `default` is returned. N)KeyError)r8r4defaultr!r!r#getsz Context.getcCs6|jrt||}n |j|}|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. )r<)rMrLr r.r^)r8r4rRr!r!r#rJs   zContext.resolvecCs,|jr"|j|}t|trt}|St||S)zxResolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found. )rMrJ isinstance Undefinedr rL)r8r4rRr!r!r#rLs   zContext.resolve_or_missingcstfddjDS)z+Get a new dict with the exported variables.c3s|]}|j|fVqdS)N)r0)rSrT)r8r!r#rVsz'Context.get_exported..)r-rY)r8r!)r8r# 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. )r0r3r-)r8r!r!r#get_alls zContext.get_allc Osd}t|dr2|j}xd D]}t||r|}PqWt|trt|ddrT|f|}n2t|ddrn|jf|}nt|ddr|jf|}y |||Stk r|jjdSXdS) 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 environmentfunctionrzGvalue was undefined because a callable raised a StopIteration exceptionN)rhr ri) r'rgrcrrErWr. StopIterationr^)Z_Context__selfZ _Context__objargskwargsZ__traceback_hide__fnZfn_typer!r!r#calls(         z Context.callcCsDt|j|ji|jdd|}|j|_|jjddt|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|fVqdS)N)list)rSrTrUr!r!r#rVsz"Context.derived..)r6r.r<rfrWr/updater)r8r2r9r!r!r#derived s  zContext.derivedcs$fdd}ttj|_|_|S)Ncst|jS)N)rErf)r8)methr!r#r$szContext._all..)rEr-rCr?)rrproxyr!)rrr#_alls z Context._allkeysvaluesitemsiterkeys itervaluesrcCs||jkp||jkS)N)r0r3)r8r<r!r!r# __contains__(szContext.__contains__cCs|j|}|tkrt||S)zTLookup a variable or raise `KeyError` if the variable is undefined. )rLr r`)r8r4itemr!r!r#r=+s zContext.__getitem__cCsd|jjt|j|jfS)Nz <%s %s of %r>)r>r?reprrfr<)r8r!r!r#r@4s zContext.__repr__)N)N)r?rArBrCrMrNr:r[rbrJrLrerfr rnrqrtrurvrwrrxryrrzr=r@r!r!r!r#rKs0    "  rK)Mappingc@s0eZdZdZddZeddZeddZdS) r;z"One block on a template reference.cCs||_||_||_||_dS)N)r<_context_stack_depth)r8r<r9stackdepthr!r!r#r:GszBlockReference.__init__cCsF|jdt|jkr,|jjjd|jddSt|j|j|j|jdS)zSuper the block.rZz#there is no parent block called %r.r[)r<)rlenrr~r.r^r<r;)r8r!r!r#r[Ms zBlockReference.supercCs,t|j|j|j}|jjjr(t|}|S)N)r rrr~rW autoescaper)r8rRr!r!r#rgWs zBlockReference.__call__N) r?rArBrCr:propertyr[r rgr!r!r!r#r;Ds 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)NrZ) _undefined_recurseindex0depth0r _last_checked_value)r8r^recurserr!r!r#r:gs zLoopContextBase.__init__cGs|s td||jt|S)z7Cycles among the arguments with the current loop index.zno items for cycling given) TypeErrorrr)r8rkr!r!r#cyclenszLoopContextBase.cyclecGs|j|kr||_dSdS)z9Checks whether the value has changed since the last call.TF)r)r8r5r!r!r#changedts zLoopContextBase.changedcCs |jdkS)Nr)r)r"r!r!r#r${szLoopContextBase.cCs |jtkS)N)_after_last_iteration)r"r!r!r#r$|scCs |jdS)NrZ)r)r"r!r!r#r$}scCs |j|jS)N)lengthr)r"r!r!r#r$~scCs |j|jS)N)rr\)r"r!r!r#r$scCs |jdS)NrZ)r)r"r!r!r#r$scCs|jtkr|jdS|jS)Nzthere is no previous item)_before_first_iterationr)r8r!r!r#previtems  zLoopContextBase.previtemcCs|jtkr|jdS|jS)Nzthere is no next item)rrr)r8r!r!r#nextitems  zLoopContextBase.nextitemcCs|jS)N)r)r8r!r!r#__len__szLoopContextBase.__len__cCs(|jdkrtd|j||j|jdS)NzMTried to call non recursive loop. Maybe you forgot the 'recursive' modifier.rZ)rrr)r8iterabler!r!r#loops zLoopContextBase.loopcCsd|jj|j|jfS)Nz <%s %r/%r>)r>r?r\r)r8r!r!r#r@szLoopContextBase.__repr__)Nr)r?rArBrCrr_currentrr_lengthr:rrrfirstlastr\ZrevindexZ revindex0rrrrr rrgr@r!r!r!r#r_s*          rc@s2eZdZd ddZeddZddZd d ZdS) rNrc CsVtj||||t||_yt||_Wnttfk rFd|_YnX|j|_ dS)N) rr:iter _iteratorrrrAttributeError _safe_nextr)r8rr^rrr!r!r#r:s  zLoopContext.__init__cCs<|jdkr6t|j}t||_|jd}t|||_|jS)N)rtuplerrrr)r8rZiterations_doner!r!r#rs     zLoopContext.lengthcCst|S)N)LoopContextIterator)r8r!r!r#__iter__szLoopContext.__iter__c Cs$y t|jStk rtSXdS)N)nextrrjr)r8r!r!r#rs zLoopContext._safe_next)Nr)r?rArBr:rrrrr!r!r!r#rs  c@s,eZdZdZd ZddZddZddZd S) rz The iterator for a loop context.r9cCs ||_dS)N)r9)r8r9r!r!r#r:szLoopContextIterator.__init__cCs|S)Nr!)r8r!r!r#rszLoopContextIterator.__iter__cCsH|j}|jd7_|jtkr$t|j|_|j|_|j|_|j|fS)NrZ)r9rrrrjrrr)r8ctxr!r!r#__next__s  zLoopContextIterator.__next__N)r9)r?rArBrC __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) r8r.funcr<rrrrZdefault_autoescaper!r!r#r:s  zMacro.__init__c Os|r*t|dtr*|dj}|dd}n|j}t|d|j}t|}d}||jkrxht|jt|dD]F\}}y|j |} Wnt k rt } YnX|dkrd}|j | qpWn|j }|jr| r|j dd} | dkr|jjddd} |j | |jr|j |n8|rHd|kr.td|jtd |jtt|f|jrf|j ||jdn(t||jkrtd |jt|jf|j||S) NrrZFrTzNo caller defined)r<zamacro %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))rcrrrrorr enumeraterpopr`r r&rrrr^rrr<rrr_invoke) r8rkrlrroffZ found_calleridxr<r5rr!r!r#rgsJ          zMacro.__call__cCs|j|}|rt|}|S)z=This method is being swapped out by the async implementation.)rr)r8rrrRr!r!r#rAs z Macro._invokecCs$d|jj|jdkrdpt|jfS)Nz<%s %s>Z anonymous)r>r?r<r|)r8r!r!r#r@HszMacro.__repr__)N) r?rArBrCr:r r rgrr@r!r!r!r#rs  Kc@seZdZdZdZdedefddZed d Z ed d Z e Z Z Z ZZZZZZZZZZZZZZZZZZZ Z!Z"Z#Z$Z%d dZ&ddZ'ddZ(ddZ)ddZ*ddZ+ddZ,e,Z-ddZ.dS)rdazThe 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||_||_||_||_dS)N)rrrr)r8hintobjr<excr!r!r#r:aszUndefined.__init__cOsl|jdkrX|jtkr d|j}q^t|jtsBdt|j|jf}q^dt|j|jf}n|j}|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 rrcrr r)r8rkrlrr!r!r#_fail_with_undefined_errorgs      z$Undefined._fail_with_undefined_errorcCs |dddkrt||jS)Nr__)rr)r8r<r!r!r# __getattr__}szUndefined.__getattr__cCst|t|kS)N)rH)r8otherr!r!r#__eq__szUndefined.__eq__cCs |j| S)N)r)r8rr!r!r#__ne__szUndefined.__ne__cCs tt|S)N)idrH)r8r!r!r#__hash__szUndefined.__hash__cCsdS)Nr%r!)r8r!r!r#__str__szUndefined.__str__cCsdS)Nrr!)r8r!r!r#rszUndefined.__len__ccsdS)Nr!)r8r!r!r#rszUndefined.__iter__cCsdS)NFr!)r8r!r!r# __nonzero__szUndefined.__nonzero__cCsdS)Nrdr!)r8r!r!r#r@szUndefined.__repr__)rrrr)/r?rArBrCrr rr:r rr__add____radd____mul____rmul__Z__div__Z__rdiv__ __truediv__ __rtruediv__ __floordiv__ __rfloordiv____mod____rmod____pos____neg__rgr=__lt____le____gt____ge____int__ __float__ __complex____pow____rpow____sub____rsub__rrrrrrr__bool__r@r!r!r!r#rdOs   lrdcs`dkr,ddl}|jtj|jtjdkr8tfddGfddd}|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}jd|dS)Nz%s is undefinedz%s has no element %sz%s has no attribute %szTemplate variable warning: %s)rrr rrcrr warning)Zundefr)loggerr!r# _log_messages      z,make_logging_undefined.._log_messagecsfeZdZfddZfddZfddZerTfddZfd d Znfd d Z d S)z0make_logging_undefined..LoggingUndefinedcsPyj|f||S|jk rJ}zjdt||WYdd}~XnXdS)NzTemplate variable error: %s)rrerrorstr)r8rkrle)baserr!r#rs zKmake_logging_undefined..LoggingUndefined._fail_with_undefined_errorcsj|}||S)N)r)r8rR)rrr!r#rs z8make_logging_undefined..LoggingUndefined.__str__csj|}||S)N)r)r8rR)rrr!r#rs z9make_logging_undefined..LoggingUndefined.__iter__csj|}||S)N)r)r8rR)rrr!r#rs z.LoggingUndefined.__nonzero__csj|}||S)N) __unicode__)r8rR)rrr!r#rs z.LoggingUndefined.__unicode__csj|}||S)N)r)r8rR)rrr!r#rs z9make_logging_undefined..LoggingUndefined.__bool__N) r?rArBrrrrrrrr!)rrrr!r#LoggingUndefinedsr)logging getLoggerr? addHandler StreamHandlersysstderrrd)rrrrr!)rrrr#make_logging_undefineds  #rc@seZdZdZfZddZdS)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 cCs<|jdkr2|jtkrd|jSdt|j|jfSd|jS)Nz{{ %s }}z{{ no such element: %s[%r] }}z!{{ undefined value printed: %s }})rrr rr )r8r!r!r#rs    zDebugUndefined.__str__N)r?rArBrCrrr!r!r!r#rs rc@s6eZdZdZfZejZZZ 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 N)r?rArBrCrrdrrrrrrrrrr!r!r!r#rsr)NNNN)NN)=rCr itertoolsrtypesrZ jinja2.nodesrrZ jinja2.utilsrrrr r r r r rZjinja2.exceptionsrrrZjinja2._compatrrrrrrrr__all__rr objectrrrrr6rrFrHrGrLrK collectionsr}register ImportErrorr;rrrrrdrrrrr!r!r!r# sX  ,(   9 F' m U Q