a `E@s0dZddlZddlZddlZddlmZddlmZddlmZddl m Z ddl m Z dd l m Z dd l m Z dd lmZdd lmZdd lmZddZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGd d!d!eZdS)"zKAPI and implementations for loading templates from different data sources. N)sha1)path) ModuleType)abcfspath) iteritems) string_types)TemplateNotFound) internalcode)open_if_existscCs\g}|dD]H}tj|vs6tjr,tj|vs6|tjkr@t|q|r|dkr||q|S)zSplit a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. /.)splitrsepaltseppardirr append)templatepiecesZpiecer2/usr/lib/python3.9/site-packages/jinja2/loaders.pysplit_template_paths   rc@s2eZdZdZdZddZddZed dd ZdS) BaseLoaderaBaseclass for all loaders. Subclass this and override `get_source` to implement a custom loading mechanism. The environment provides a `get_template` method that calls the loader's `load` method to get the :class:`Template` object. A very basic example for a loader that looks up templates on the file system could look like this:: from jinja2 import BaseLoader, TemplateNotFound from os.path import join, exists, getmtime class MyLoader(BaseLoader): def __init__(self, path): self.path = path def get_source(self, environment, template): path = join(self.path, template) if not exists(path): raise TemplateNotFound(template) mtime = getmtime(path) with file(path) as f: source = f.read().decode('utf-8') return source, path, lambda: mtime == getmtime(path) TcCs"|jstd|jjt|dS)aGet the template source, filename and reload helper for a template. It's passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can't locate the template. The source part of the returned tuple must be the source of the template as unicode string or a ASCII bytestring. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise `None`. The filename is used by python for the tracebacks if no loader extension is used. The last item in the tuple is the `uptodate` function. If auto reloading is enabled it's always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns `False` the template will be reloaded. z&%s cannot provide access to the sourceN)has_source_access RuntimeError __class____name__r self environmentrrrr get_sourceGs  zBaseLoader.get_sourcecCs tddS)zIterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior. z-this loader cannot iterate over all templatesN) TypeErrorr rrrlist_templates_szBaseLoader.list_templatesNc Csd}|duri}|||\}}}|j}|durF|||||} | j}|dur\||||}|dur~| jdur~|| _|| |j||||S)acLoads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly. N)r"Zbytecode_cacheZ get_bucketcodecompileZ set_buckettemplate_classZ from_code) r r!nameglobalsr&sourcefilenameuptodateZbccZbucketrrrloades  zBaseLoader.load)N) r __module__ __qualname____doc__rr"r%r r.rrrrr&s rc@s*eZdZdZd ddZddZdd Zd S) FileSystemLoadera#Loads templates from the file system. This loader can find templates in folders on the file system and is the preferred way to load them. The loader takes the path to the templates as string, or if multiple locations are wanted a list of them which is then looked up in the given order:: >>> loader = FileSystemLoader('/path/to/templates') >>> loader = FileSystemLoader(['/path/to/templates', '/other/path']) Per default the template encoding is ``'utf-8'`` which can be changed by setting the `encoding` parameter to something else. To follow symbolic links, set the *followlinks* parameter to ``True``:: >>> loader = FileSystemLoader('/path/to/templates', followlinks=True) .. versionchanged:: 2.8 The ``followlinks`` parameter was added. utf-8FcCs<t|tjrt|tr|g}dd|D|_||_||_dS)NcSsg|] }t|qSrr.0prrr z-FileSystemLoader.__init__..) isinstancerIterabler searchpathencoding followlinks)r r;r<r=rrr__init__szFileSystemLoader.__init__c st|}|jD]t}tj|g|Rt}|dur6qz||j}W|n |0t fdd}||fSt |dS)Ncs*ztkWSty$YdS0dSNFrgetmtimeOSErrorrr,mtimerrr-s z-FileSystemLoader.get_source..uptodate) rr;rjoinr readdecoder<closerAr )r r!rrr;fcontentsr-rrCrr"s  zFileSystemLoader.get_sourcec Cst}|jD]}tj||jd}|D]r\}}}|D]b}tj||t|dtjj  tjj d}|dddkr|dd}||vr2| |q2q$q t |S)N)r=r./) setr;oswalkr=rrElenstriprreplaceaddsorted) r foundr;Zwalk_dirdirpath_ filenamesr,rrrrr%s   zFileSystemLoader.list_templatesN)r3Frr/r0r1r>r"r%rrrrr2s r2c@s*eZdZdZd ddZddZdd Zd S) PackageLoadera,Load templates from python eggs or packages. It is constructed with the name of the python package and the path to the templates in that package:: loader = PackageLoader('mypackage', 'views') If the package path is not given, ``'templates'`` is assumed. Per default the template encoding is ``'utf-8'`` which can be changed by setting the `encoding` parameter to something else. Due to the nature of eggs it's only possible to reload templates if the package was loaded from the file system and not a zip file. templatesr3cCsVddlm}ddlm}ddlm}||}||_||_t|||_||_||_ dS)Nr)DefaultProvider) get_provider)ResourceManager) Z pkg_resourcesr\r]r^r<managerr9filesystem_boundprovider package_path)r package_namerbr<r\r]r^rarrrr>s    zPackageLoader.__init__cst|}d|jft|}|j|s2t|d}|jrh|j|j |t fdd}|j |j |}| |j|fS)Nrcs*ztkWSty$YdS0dSr?r@rrCrrr-s z*PackageLoader.get_source..uptodate)rrErbtupleraZ has_resourcer r`Zget_resource_filenamer_rrAZget_resource_stringrGr<)r r!rrr6r-r+rrCrr"s  zPackageLoader.get_sourcecsbj}|dddkr$|dd}n |dkr0d}t|gfdd|S)NrKrLrcsPj|D]>}|d|}j|r2|q |ddq dS)Nr)raZresource_listdirZresource_isdirrlstrip)rr,fullname_walkoffsetresultsr rrris    z+PackageLoader.list_templates.._walk)rbrPsort)r rrrhrr% s zPackageLoader.list_templatesN)r[r3rYrrrrrZs rZc@s(eZdZdZddZddZddZdS) DictLoaderaLoads a template from a python dict. It's passed a dict of unicode strings bound to template names. This loader is useful for unittesting: >>> loader = DictLoader({'index.html': 'source here'}) Because auto reloading is rarely useful this is disabled per default. cCs ||_dSN)mapping)r rorrrr>,szDictLoader.__init__cs6jvr*jdfddfStdS)NcsjkSrn)rogetrr r+rrr2r8z'DictLoader.get_source..)ror rrrqrr"/s  zDictLoader.get_sourcecCs t|jSrn)rTror$rrrr%5szDictLoader.list_templatesNrYrrrrrm#srmc@s eZdZdZddZddZdS)FunctionLoaderaA loader that is passed a function which does the loading. The function receives the name of the template and has to return either an unicode string with the template source, a tuple in the form ``(source, filename, uptodatefunc)`` or `None` if the template does not exist. >>> def load_template(name): ... if name == 'index.html': ... return '...' ... >>> loader = FunctionLoader(load_template) The `uptodatefunc` is a function that is called if autoreload is enabled and has to return `True` if the template is still up to date. For more details have a look at :meth:`BaseLoader.get_source` which has the same return value. cCs ||_dSrn) load_func)r rtrrrr>KszFunctionLoader.__init__cCs4||}|durt|nt|tr0|ddfS|Srn)rtr r9r )r r!rrvrrrr"Ns     zFunctionLoader.get_sourceN)rr/r0r1r>r"rrrrrs9srsc@s@eZdZdZdddZddZddZedd d Zd d Z d S) PrefixLoaderaA loader that is passed a dict of loaders where each loader is bound to a prefix. The prefix is delimited from the template by a slash per default, which can be changed by setting the `delimiter` argument to something else:: loader = PrefixLoader({ 'app1': PackageLoader('mypackage.app1'), 'app2': PackageLoader('mypackage.app2') }) By loading ``'app1/index.html'`` the file from the app1 package is loaded, by loading ``'app2/index.html'`` the file from the second. rcCs||_||_dSrn)ro delimiter)r rorwrrrr>fszPrefixLoader.__init__c CsHz ||jd\}}|j|}Wnttfy>t|Yn0||fS)Nr)rrwro ValueErrorKeyErrorr )r rprefixr)loaderrrr get_loaderjs zPrefixLoader.get_loadercCs<||\}}z|||WSty6t|Yn0dSrn)r|r"r )r r!rr{r)rrrr"rs  zPrefixLoader.get_sourceNcCs>||\}}z||||WSty8t|Yn0dSrn)r|r.r )r r!r)r*r{Z local_namerrrr.{s  zPrefixLoader.loadcCs>g}t|jD]*\}}|D]}|||j|qq|Srn)r ror%rrw)r resultrzr{rrrrr%s  zPrefixLoader.list_templates)r)N) rr/r0r1r>r|r"r r.r%rrrrrvWs   rvc@s6eZdZdZddZddZed ddZd d ZdS) ChoiceLoaderaThis loader works like the `PrefixLoader` just that no prefix is specified. If a template could not be found by one loader the next one is tried. >>> loader = ChoiceLoader([ ... FileSystemLoader('/path/to/user/templates'), ... FileSystemLoader('/path/to/system/templates') ... ]) This is useful if you want to allow users to override builtin templates from a different location. cCs ||_dSrn)loaders)r rrrrr>szChoiceLoader.__init__c Cs>|jD]*}z|||WSty.Yq0qt|dSrn)rr"r )r r!rr{rrrr"s   zChoiceLoader.get_sourceNc Cs@|jD],}z||||WSty0Yq0qt|dSrn)rr.r )r r!r)r*r{rrrr.s   zChoiceLoader.loadcCs(t}|jD]}||q t|Srn)rMrupdater%rT)r rUr{rrrr%s zChoiceLoader.list_templates)N) rr/r0r1r>r"r r.r%rrrrr~s   r~c@seZdZdZdS)_TemplateModulez9Like a normal module but with support for weak referencesN)rr/r0r1rrrrrsrc@sBeZdZdZdZddZeddZeddZe d d d Z d S) ModuleLoadera6This loader loads templates from precompiled templates. Example usage: >>> loader = ChoiceLoader([ ... ModuleLoader('/path/to/compiled/templates'), ... FileSystemLoader('/path/to/templates') ... ]) Templates can be precompiled with :meth:`Environment.compile_templates`. Fcsjdt|t}t|tjr*t|tr0|g}dd|D|_t|fddt j <||_ |_ dS)Nz_jinja2_module_templates_%xcSsg|] }t|qSrrr4rrrr7r8z)ModuleLoader.__init__..cstjdSrn)sysmodulespop)xrcrrrrr8z'ModuleLoader.__init__..) idrr9rr:r __path__weakrefproxyrrmodulerc)r rmodrrrr>s  zModuleLoader.__init__cCsdt|dS)NZtmpl_r3)rencodeZ hexdigestr)rrrget_template_keyszModuleLoader.get_template_keycCst|dS)Nz.py)rrrrrrget_module_filenamesz ModuleLoader.get_module_filenameNcCs~||}d|j|f}t|j|d}|durlzt|dddg}Wnty\t|Yn0tj |d|j ||j |S)Nz%s.%sroot) rrcgetattrr __import__ ImportErrorr rrrr(Zfrom_module_dict__dict__)r r!r)r*keyrrrrrr.s  zModuleLoader.load)N) rr/r0r1rr> staticmethodrrr r.rrrrrs   r)r1rNrrZhashlibrrtypesrZ_compatrrr r exceptionsr Zutilsr r robjectrr2rZrmrsrvr~rrrrrrs.          gLJ6)