dbfdg 3 Gg*Q@sdZddlZddlZddlZddlmZddlmZddlm Z ddl m Z ddl mZmZmZmZedfd d d iZeZd jZd ejdkZddZddZddZddZddZddZddZ dDddZ!dEd!d"Z"d#d$Z#dFd%d&Z$dGd'd(Z%dHd-d.Z&dId0d1Z'Gd2d3d3e(Z)ydd4lm*Z*e*j+e)Wne,k rPYnXdJfd*dfd8d9Z-dKd:d;Z.eGdd?d?e(Z0Gd@dAdAe(Z1ye2dBd*Z3Wne4k rdZ3YnXddCl5m6Z6m7Z7m8Z8dS)Lz jinja2.utils ~~~~~~~~~~~~ Utility functions. :copyright: (c) 2017 by the Jinja Team. :license: BSD, see LICENSE for more details. N)deque) ascii_letters)digits)Lock) text_type string_typesimplements_iterator url_quoteZ MissingType__repr__cCsdS)Nmissing)xr r /usr/lib/python3.6/utils.pysrz\//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)contextfunction)fr r rr 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)evalcontextfunction)rr r rr0s 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)environmentfunction)rr r rr=srcCstj|j|S)z%Marks the function as internally used) internal_codeadd__code__)rr r r internalcodeGs rcCsddlm}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)Zjinja2.runtimer isinstance)objrr r r is_undefinedMs rcCsx |D]}qWdS)z4Consumes an iterable without doing anything with it.Nr )iterableZeventr r rconsume]s rcCs,ddlm}ddlm}|j|jdS)a"Jinja2 keeps internal caches for environments and lexers. These are used so that Jinja2 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)Zjinja2.environmentr Z jinja2.lexerr!clear)r r!r r r clear_cachescs  r#Fc Csyfd|kr|jdd\}}n6d|krJ|jd}dj|dd}|d}nt|Stt|dd|g|Sttfk r|sYnXdS)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 :.Nr')splitjoin __import__getattr ImportErrorAttributeError)Z import_nameZsilentmoduleritemsr r r import_stringos   r0rbcCsJy t||Stk rD}z|jtjtjtjfkr4WYdd}~XnXdS)zZReturns a file descriptor for the filename if that file exists, otherwise `None`. N)openIOErrorerrnoENOENTZEISDIRZEINVAL)filenamemodeer r ropen_if_existss  r9cCsJ|dkr dS|tkrdS|jjdkr.|jj}n|jjd|jj}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 __builtin__builtinsr&z %s object)r<r=)r; __class__ __module____name__)rnamer r robject_type_reprs  rBc CsByddlm}|||dStk r<ddlm}||SXdS)zYPrettyprint an object. Either use the `pretty` library or the builtin `pprint`. r)pretty)verbose)pformatN)rCr,pprintrE)rrDrCrEr r rrEs    rEcCs|fdd}tjdtt|}|r4dtt|p6d}|rHdt|pJd}xt|D]t\}} d| d} } } tjd| } | r| j} | | jd} | jdrtj d| } | r| j} | d| j } | j dsBd| krV| j d rV| j d rVt | dkrV| dt tkrV| jdsB| jdsB| jdrVd| |||| f} | j dsn| j drd| |||| f} d| kr| j d rd| krtjd| rd| | f} | | | ||<qXWdj|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,|dk r(|d|t||kr"dp$dp*|S)Nz...r)len)r limitr r rrszurlize..z(\s+)z rel="%s"rz target="%s"z ^([(<]|<)+N)>r&, >z([)>.,\n]|>)+$zwww.@zhttp://zhttps://rz.orgz.netz.comz%sz%sr$z^\S@\w[\w.-]*\.\w$z%s)rIrJr&rKrLrM)rer(rescape enumeratematchgroupendendswithsearchstart startswithrG_letters_digitsr))textZtrim_url_limitZreltargetZtrim_urlwordsZrel_attrZ target_attriwordheadZmiddletailrRr r rurlizesT              rbTdcCsfddlm}ddlm}m}|j}g}xt|D]} d} d} } d} d}g}xtt|||D]\}} x||} | |krp| }PqpW| r| j} d} ||dd| kr|} | d 7} | d 7} ||d d | kr|} } | d 7} d} |j | qfWdj |}|j d r|ddd }n|j d s0|d 7}|j |q4W|sNdj |St dj dd|DS)z+Generate some lorem ipsum for the template.r)LOREM_IPSUM_WORDS)choice randrangeTNFrK rdr& r%z rLcss|]}dt|VqdS)z

%s

N)rP).0r r r r .sz'generate_lorem_ipsum..r') Zjinja2.constantsrfZrandomrgrhr(rangerQ capitalizeappendr)rUMarkup)nhtmlminmaxrfrgrhr]result_Znext_capitalizedZ last_commaZ last_fullstopr_Zlastpidxr r rgenerate_lorem_ipsumsJ     r|utf-8cCsVt|tst|}t|tr&|j|}| r0dp2d}tt||}|rR|jdd}|S)a&URL escapes a single bytestring or unicode string with the given charset if applicable to URL safe quoting under all rules that need to be considered under all supported Python versions. If non strings are provided they are converted to their unicode representation first. /z%20+)rrrencoder replace)rcharsetZfor_qsZsafervr r runicode_urlencode1s    rc@seZdZdZddZddZddZdd Zd d Zd d Z d/ddZ d0ddZ ddZ ddZ ddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,ZeZd-d.Ze ZdS)1LRUCachez"A simple LRU Cache implementation.cCs ||_i|_t|_|jdS)N)capacity_mappingr_queue _postinit)selfrr r r__init__KszLRUCache.__init__cCs4|jj|_|jj|_|jj|_t|_|jj |_ dS)N) rpopleft_popleftpopZ_popremove_remover_wlockrr_append)rr r rrQs    zLRUCache._postinitcCs|j|j|jdS)N)rrr)rrr)rr r r __getstate__YszLRUCache.__getstate__cCs|jj||jdS)N)__dict__updater)rdr r r __setstate__`s zLRUCache.__setstate__cCs|jfS)N)r)rr r r__getnewargs__dszLRUCache.__getnewargs__cCs*|j|j}|jj|jt|j|_|S)z&Return a shallow copy of the instance.)r>rrrrr)rrr r rcopygs  z LRUCache.copyNc Cs"y||Stk r|SXdS)z/Return an item from the cache dict or `default`N)KeyError)rkeydefaultr r rgetnsz LRUCache.getcCsF|jjz*y||Stk r0|||<|SXWd|jjXdS)zvSet `default` if the key is not in the cache otherwise leave unchanged. Return the value of this key. N)racquirerrelease)rrrr r r setdefaultus  zLRUCache.setdefaultc Cs4|jjz|jj|jjWd|jjXdS)zClear the cache.N)rrrr"rr)rr r rr"s   zLRUCache.clearcCs ||jkS)z$Check if a key exists in this cache.)r)rrr r r __contains__szLRUCache.__contains__cCs t|jS)z%Return the current size of the cache.)rGr)rr r r__len__szLRUCache.__len__cCsd|jj|jfS)Nz<%s %r>)r>r@r)rr r rr szLRUCache.__repr__cCsf|jjzJ|j|}|jd|krRy|j|Wntk rFYnX|j||S|jjXdS)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. r%Nr')rrrrr ValueErrorrr)rrrr r r __getitem__s   zLRUCache.__getitem__c Csf|jjzJ||jkr"|j|nt|j|jkr>|j|j=|j|||j|<Wd|jjXdS)zhSets the value for an item. Moves the item up so that it has the highest priority then. N) rrrrrGrrrr)rrvaluer r r __setitem__s     zLRUCache.__setitem__cCsL|jjz0|j|=y|j|Wntk r6YnXWd|jjXdS)z]Remove an item from the cache dict. Raise a `KeyError` if it does not exist. N)rrrrrr)rrr r r __delitem__s  zLRUCache.__delitem__cs$fddtjD}|j|S)zReturn a list of items.csg|]}|j|fqSr )r)rnr)rr r sz"LRUCache.items..)listrreverse)rrxr )rrr/szLRUCache.itemscCs t|jS)zIterate over all items.)iterr/)rr r r iteritemsszLRUCache.iteritemscCsdd|jDS)zReturn a list of all values.cSsg|] }|dqS)r%r )rnr r r rrsz#LRUCache.values..)r/)rr r rvaluesszLRUCache.valuescCs t|jS)zIterate over all values.)rr)rr r r itervalueszLRUCache.itervaluecCst|S)z7Return a list of all keys ordered by most recent usage.)r)rr r rkeyssz LRUCache.keyscCstt|jS)z[Iterate over all keys in the cache dict, ordered by the most recent usage. )reversedtupler)rr r riterkeysszLRUCache.iterkeyscCstt|jS)zVIterate over the values in the cache dict, oldest items coming first. )rrr)rr r r __reversed__szLRUCache.__reversed__)N)N)r@r? __qualname____doc__rrrrrrrrr"rrr rrrr/rrrrr__iter__r__copy__r r r rrDs2   r)MutableMappingruhtmxmlcs: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|jdjVqdS)r&N)lstriplower)rnr r r rro#sz$select_autoescape..css |]}d|jdjVqdS)r&N)rr)rnr r r rro%scs4|dkr S|j}|jr"dS|jr0dSS)NTF)rrU)Z template_name)rdefault_for_stringdisabled_patternsenabled_patternsr r autoescape's  z%select_autoescape..autoescape)r)Zenabled_extensionsZdisabled_extensionsrrrr )rrrrrselect_autoescapes &   rcKsB|dkrtj}||f|jddjddjddjdd }t|S) aWorks exactly like :func:`dumps` but is safe for use in ``