a `W@sddlZddlZddlZddlZddlmZddlmZddlmZddl m Z ddl m Z ddlmZddlmZdd lmZd d lmZd d lmZd d lmZd dlmZedddddiZeZdjZdedvZddZ ddZ!ddZ"ddZ#dd Z$d!d"Z%d#d$Z&dJd&d'Z'dKd)d*Z(d+d,Z)dLd-d.Z*dMd/d0Z+dNd5d6Z,dOd8d9Z-Gd:d;d;e.Z/ej01e/dPd=d>Z2dQd?d@Z3GdAdBdBe.Z4GdCdDdDe.Z5GdEdFdFe.Z6ze7dGd2Z8Wne9yd%Z8Yn0dHdIZ:dS)RN)deque)choice) randrange) ascii_letters)digits)Lockescape)Markup)abc) string_types) text_type) url_quoteZ MissingType__repr__cCsdS)Nmissingr)xrr0/usr/lib/python3.9/site-packages/jinja2/utils.pyrz\//cCs d|_|S)a+This decorator can be used to mark a function or method context callable. A context callable is passed the active :class:`Context` as first argument when called from the template. This is useful if a function wants to get access to the context or functions provided on the context object. For example a function that returns a sorted list of template variables the current template exports could look like this:: @contextfunction def get_exported_names(context): return sorted(context.exported_vars) T)contextfunctionfrrrr s rcCs d|_|S)aGThis decorator can be used to mark a function or method as an eval context callable. This is similar to the :func:`contextfunction` but instead of passing the context, an evaluation context object is passed. For more information about the eval context, see :ref:`eval-context`. .. versionadded:: 2.4 T)evalcontextfunctionrrrrr0s rcCs d|_|S)zThis decorator can be used to mark a function or method as environment callable. This decorator works exactly like the :func:`contextfunction` decorator just that the first argument is the active :class:`Environment` and not context. T)environmentfunctionrrrrr=srcCst|j|S)z%Marks the function as internally used) internal_codeadd__code__rrrr internalcodeGs r!cCsddlm}t||S)aCheck if the object passed is undefined. This does nothing more than performing an instance check against :class:`Undefined` but looks nicer. This can be used for custom filters or tests that want to react to undefined variables. For example a custom default filter can look like this:: def default(var, default=''): if is_undefined(var): return default return var r ) Undefined)Zruntimer" isinstance)objr"rrr is_undefinedMs r%cCs|D]}qdS)z4Consumes an iterable without doing anything with it.Nr)iterable_rrrconsume^sr(cCs,ddlm}ddlm}||dS)a Jinja keeps internal caches for environments and lexers. These are used so that Jinja doesn't have to recreate environments and lexers all the time. Normally you don't have to care about that but if you are measuring memory consumption you may want to clean the caches. r )_spontaneous_environments) _lexer_cacheN)Z environmentr)Zlexerr*clear)r)r*rrr clear_cachesds  r,Fc CsxzVd|vr|dd\}}n$d|vr6|d\}}}n t|WStt|dd|g|WSttfyr|snYn0dS)aImports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If the `silent` is True the return value will be `None` if the import fails. :return: imported object :r .N)split rpartition __import__getattr ImportErrorAttributeError)Z import_nameZsilentmoduler$r'rrr import_stringqs  r6rbcCstj|sdSt||S)z\Returns a file descriptor for the filename if that file exists, otherwise ``None``. N)ospathisfileopen)filenamemoderrropen_if_existss r>cCsJ|dur dS|turdSt|}|jdvr2|j}n|jd|j}d|S)zReturns the name of the object's type. For some recognized singletons the name of the object is returned instead. (For example for `None` and `Ellipsis`). NNoneEllipsis)Z __builtin__builtinsr.z %s object)r@type __module____name__)r$clsnamerrrobject_type_reprs rGcCsFzddlm}|||dWSty@ddlm}||YS0dS)zYPrettyprint an object. Either use the `pretty` library or the builtin `pprint`. r)pretty)verbose)pformatN)rHr3ZpprintrJ)r$rIrHrJrrrrJs    rJcCs|fdd}tdtt|}|r4dtt|p6d}|rHdt|pJd}t|D]n\}} d| d} } } td| } | r| } | | d} | d rt d | } | r| } | d| } | d s:d | vrN| d sN| dsNt | dkrN| dt tvrN| ds:| ds:| drNd| |||| f} | d sf| drzd| |||| f} d | vr| d sd| vrtd| rd| | f} | | | ||<qTd|S)a Converts any URLs in text into clickable links. Works on http://, https:// and www. links. Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. If trim_url_limit is not None, the URLs in link text will be limited to trim_url_limit characters. If nofollow is True, the URLs in link text will get a rel="nofollow" attribute. If target is not None, a target attribute will be added to the link. cSs,|dur(|d|t||kr"dp$dp*|S)Nz...r)len)rlimitrrrrszurlize..z(\s+)z rel="%s"rz target="%s"z ^([(<]|<)+N))>r., z>z([)>.,\n]|>)+$zwww.@zhttp://zhttps://rz.orgz.netz.comz%sz%sr-z^\S+@\w[\w.-]*\.\w+$z%s)rer/rr enumeratematchgroupendendswithsearchstart startswithrK_letters_digitsjoin)textZtrim_url_limitreltargetZtrim_urlwordsZrel_attrZ target_attriwordheadZmiddletailrTrrrurlizesr          rfTdcCsDddlm}|}g}t|D]}d}d} } d} d} g} ttt||D]\}}t|} | | krV| } qnqV|r~| } d}|tdd| kr|} | d 7} | d 7} |td d | kr|} } | d 7} d}| | qNd | } | d r| ddd } n| d s| d 7} || q |s,d |St d dd|DS)z+Generate some lorem ipsum for the template.r )LOREM_IPSUM_WORDSTrNFrO rhr. z rPcss|]}dt|VqdS)z

%s

Nr.0rrrr 5rz'generate_lorem_ipsum..) Z constantsrjr/rangerSrr capitalizeappendr]rWr )nhtmlminmaxrjraresultr'Znext_capitalizedZ last_commaZ last_fullstoprclastpidxrrrgenerate_lorem_ipsumsF        rutf-8cCsdt|tst|}t|tr&||}|r.dnd}t||}t|tsP|d}|r`|dd}|S)aQuote a string for use in a URL using the given charset. This function is misnamed, it is a wrapper around :func:`urllib.parse.quote`. :param obj: String or bytes to quote. Other types are converted to string then encoded to bytes using the given charset. :param charset: Encode text to bytes using this charset. :param for_qs: Quote "/" and use "+" for spaces. r/rz%20+)r#r rencoderdecodereplace)r$charsetZfor_qssafervrrrunicode_urlencode8s        rc@seZdZdZddZddZddZdd Zd d Zd d Z d3ddZ d4ddZ ddZ ddZ ddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Ze ZdS)5LRUCachez"A simple LRU Cache implementation.cCs ||_i|_t|_|dSN)capacity_mappingr_queue _postinit)selfrrrr__init__\szLRUCache.__init__cCs4|jj|_|jj|_|jj|_t|_|jj |_ dSr) rpopleft_popleftpopZ_popremove_remover_wlockrv_appendrrrrrbs    zLRUCache._postinitcCs|j|j|jdS)Nrrrrrrrr __getstate__jszLRUCache.__getstate__cCs|j||dSr)__dict__updater)rdrrr __setstate__qs zLRUCache.__setstate__cCs|jfSr)rrrrr__getnewargs__uszLRUCache.__getnewargs__cCs,||j}|j|j|j|j|S)z&Return a shallow copy of the instance.) __class__rrrrextendrrrrrcopyxs z LRUCache.copyNcCs&z ||WSty |YS0dS)z/Return an item from the cache dict or `default`NKeyErrorrkeydefaultrrrgets  z LRUCache.getcCs.z ||WSty(|||<|YS0dS)zvSet `default` if the key is not in the cache otherwise leave unchanged. Return the value of this key. Nrrrrr setdefaults   zLRUCache.setdefaultcCs>|jz"|j|jW|jn |j0dS)zClear the cache.N)racquirerr+rreleaserrrrr+s    zLRUCache.clearcCs ||jvS)z$Check if a key exists in this cache.rrrrrr __contains__szLRUCache.__contains__cCs t|jS)z%Return the current size of the cache.)rKrrrrr__len__szLRUCache.__len__cCsd|jj|jfS)Nz<%s %r>)rrDrrrrrrszLRUCache.__repr__cCsp|jzT|j|}|jd|krPz||WntyDYn0|||W|jS|j0dS)zGet an item from the cache. Moves the item up so that it has the highest priority then. Raise a `KeyError` if it does not exist. rpN)rrrrr ValueErrorrr)rrrrrr __getitem__s     zLRUCache.__getitem__cCsp|jzT||jvr"||nt|j|jkr>|j|=||||j|<W|jn |j0dS)zhSets the value for an item. Moves the item up so that it has the highest priority then. N) rrrrrKrrrr)rrvaluerrr __setitem__s      zLRUCache.__setitem__cCsT|jz8|j|=z||Wnty4Yn0W|jn |j0dS)z]Remove an item from the cache dict. Raise a `KeyError` if it does not exist. N)rrrrrrrrrr __delitem__s  zLRUCache.__delitem__cs$fddtjD}||S)zReturn a list of items.csg|]}|j|fqSrr)rrrrrr rz"LRUCache.items..)listrreverse)rr{rrritemsszLRUCache.itemscCstjdtddt|S)zIterate over all items.zP'iteritems()' will be removed in version 3.0. Use 'iter(cache.items())' instead.rm stacklevel)warningswarnDeprecationWarningiterrrrrr iteritemss zLRUCache.iteritemscCsdd|DS)zReturn a list of all values.cSsg|] }|dqS)r rrqrrrrrz#LRUCache.values..)rrrrrvaluesszLRUCache.valuescCstjdtddt|S)Iterate over all values.zQ'itervalue()' will be removed in version 3.0. Use 'iter(cache.values())' instead.rmrrrrrrrrrr itervalues zLRUCache.itervaluecCstjdtddt|S)rzR'itervalues()' will be removed in version 3.0. Use 'iter(cache.values())' instead.rmrrrrrr itervaluess zLRUCache.itervaluescCst|S)z7Return a list of all keys ordered by most recent usage.)rrrrrkeyssz LRUCache.keyscCstjdtddt|S)z[Iterate over all keys in the cache dict, ordered by the most recent usage. zN'iterkeys()' will be removed in version 3.0. Use 'iter(cache.keys())' instead.rmr)rrrrrrrriterkeyss zLRUCache.iterkeyscCstt|jSr)reversedtuplerrrrr__iter__szLRUCache.__iter__cCstt|jS)zTIterate over the keys in the cache dict, oldest items coming first. )rrrrrrr __reversed__szLRUCache.__reversed__)N)N)rDrC __qualname____doc__rrrrrrrrr+rrrrrrrrrrrrrrr__copy__rrrrrUs4       rrxZhtmZxmlcs:tdd|Dtdd|Dfdd}|S)acIntelligently sets the initial value of autoescaping based on the filename of the template. This is the recommended way to configure autoescaping if you do not want to write a custom function yourself. If you want to enable it for all templates created from strings or for all templates with `.html` and `.xml` extensions:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( enabled_extensions=('html', 'xml'), default_for_string=True, )) Example configuration to turn it on at all times except if the template ends with `.txt`:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( disabled_extensions=('txt',), default_for_string=True, default=True, )) The `enabled_extensions` is an iterable of all the extensions that autoescaping should be enabled for. Likewise `disabled_extensions` is a list of all templates it should be disabled for. If a template is loaded from a string then the default from `default_for_string` is used. If nothing matches then the initial value of autoescaping is set to the value of `default`. For security reasons this function operates case insensitive. .. versionadded:: 2.9 css |]}d|dVqdSr.NlstriplowerrqrrrrsFrz$select_autoescape..css |]}d|dVqdSrrrqrrrrsGrcs4|dur S|}|r"dS|r0dSS)NTF)rrW)Z template_namerdefault_for_stringZdisabled_patternsZenabled_patternsrr autoescapeIs  z%select_autoescape..autoescape)r)Zenabled_extensionsZdisabled_extensionsrrrrrrselect_autoescapes( rcKsF|durtj}||fi|dddddddd }t|S) aWorks exactly like :func:`dumps` but is safe for use in ``