3 C\C@sdZddlZddlZddlZddlmZddlmZddlmZddl m Z ddl m Z m Z ddlmZmZd d ZGd d d eZGd ddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZdS)z jinja2.loaders ~~~~~~~~~~~~~~ Jinja loader classes. :copyright: (c) 2017 by the Jinja Team. :license: BSD, see LICENSE for more details. N) ModuleType)path)sha1)TemplateNotFound)open_if_exists internalcode) string_types iteritemscCs`g}xV|jdD]H}tj|ks8tjr.tj|ks8|tjkrBt|q|r|dkr|j|qW|S)zSplit a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. /.)splitrsepaltseppardirrappend)templatepiecesZpiecerf/private/var/folders/pf/wv4htv3x0qs2c2mp0dnn0kchsvlck3/T/pip-install-emcbgzcf/jinja2/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_sourceFs 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) TypeError)rrrrlist_templates]szBaseLoader.list_templatesNc Csd}|dkri}|j||\}}}|j}|dk rF|j||||} | j}|dkr\|j|||}|dk r~| jdkr~|| _|j| |jj||||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)rZbytecode_cacheZ get_bucketcodecompileZ set_buckettemplate_classZ from_code) rrnameglobalsr sourcefilenameuptodateZbccZbucketrrrloadcs  zBaseLoader.load)N) r __module__ __qualname____doc__rrrrr(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|tr|g}t||_||_||_dS)N) isinstancerlist searchpathencoding followlinks)rr0r1r2rrr__init__s   zFileSystemLoader.__init__c st|}xp|jD]f}tj|f|t}|dkr6qz|jj|j}Wd|jXtj fdd}||fSWt |dS)Nc s(ytjkStk r"dSXdS)NF)rgetmtimeOSErrorr)r&mtimerrr'sz-FileSystemLoader.get_source..uptodate) rr0rjoinrreaddecoder1closer4r)rrrrr0fcontentsr'r)r&r6rrs    zFileSystemLoader.get_sourcec Cst}x|jD]}tj||jd}x~|D]v\}}}xj|D]b}tjj||t|djtjj j tjj d}|dddkr|dd}||kr8|j |q8Wq(WqWt |S)N)r2r z./) setr0oswalkr2rr7lenstripr replaceaddsorted) rfoundr0Zwalk_dirdirpathdirnames filenamesr&rrrrrs     zFileSystemLoader.list_templatesN)r-F)rr)r*r+r3rrrrrrr,s r,c@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. templatesutf-8cCsFddlm}m}m}||}||_||_t|||_||_||_ dS)Nr)DefaultProviderResourceManager get_provider) pkg_resourcesrMrNrOr1managerr.filesystem_boundprovider package_path)r package_namerTr1rMrNrOrSrrrr3s zPackageLoader.__init__cst|}dj|jft|}|jj|s2t|d}|jrh|jj|j |t j fdd}|jj |j |}|j |j|fS)Nr c s(ytjkStk r"dSXdS)NF)rr4r5r)r&r6rrr'sz*PackageLoader.get_source..uptodate)rr7rTtuplerS has_resourcerrRget_resource_filenamerQrr4get_resource_stringr9r1)rrrrpr'r%r)r&r6rrs  zPackageLoader.get_sourcecsbj}|dddkr$|dd}n |dkr0d}t|gfdd|jS)Nr=z./r csTxNjj|D]>}|d|}jj|r4|qj|djdqWdS)Nr )rSresource_listdirresource_isdirrlstrip)rr&fullname)_walkoffsetresultsrrrr`s    z+PackageLoader.list_templates.._walk)rTrAsort)rrr)r`rarbrrrszPackageLoader.list_templatesN)rKrL)rr)r*r+r3rrrrrrrJs   rJc@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 ||_dS)N)mapping)rrerrrr3szDictLoader.__init__cs6jkr*jdfddfStdS)NcsjjkS)N)regetr)rr%rrrsz'DictLoader.get_source..)rer)rrrr)rr%rrrs  zDictLoader.get_sourcecCs t|jS)N)rEre)rrrrr szDictLoader.list_templatesN)rr)r*r+r3rrrrrrrdsrdc@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 ||_dS)N) load_func)rrirrrr36szFunctionLoader.__init__cCs4|j|}|dkrt|nt|tr0|ddfS|S)N)rirr.r)rrrrvrrrr9s     zFunctionLoader.get_sourceN)rr)r*r+r3rrrrrrh$srhc@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. r cCs||_||_dS)N)re delimiter)rrerlrrrr3QszPrefixLoader.__init__c CsJy |j|jd\}}|j|}Wn ttfk r@t|YnX||fS)N)r rlre ValueErrorKeyErrorr)rrprefixr#loaderrrr get_loaderUs zPrefixLoader.get_loaderc Cs<|j|\}}y |j||Stk r6t|YnXdS)N)rrrr)rrrrqr#rrrr]s  zPrefixLoader.get_sourceNc Cs>|j|\}}y|j|||Stk r8t|YnXdS)N)rrr(r)rrr#r$rqZ local_namerrrr(fs zPrefixLoader.loadcCsFg}x>> 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 ||_dS)N)loaders)rrurrrr3szChoiceLoader.__init__c Cs>x0|jD]&}y |j||Stk r,YqXqWt|dS)N)rurr)rrrrqrrrrs    zChoiceLoader.get_sourceNc Cs@x2|jD](}y|j|||Stk r.YqXqWt|dS)N)rur(r)rrr#r$rqrrrr(s   zChoiceLoader.loadcCs,t}x|jD]}|j|jqWt|S)N)r>ruupdaterrE)rrFrqrrrrs zChoiceLoader.list_templates)N) rr)r*r+r3rrr(rrrrrrtxs   rtc@seZdZdZdS)_TemplateModulez9Like a normal module but with support for weak referencesN)rr)r*r+rrrrrwsrwc@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`. Fcs^dt|t}t|tr&|g}nt|}||_tj|fddtj <||_ |_ dS)Nz_jinja2_module_templates_%xcstjjdS)N)sysmodulespop)x)rUrrrgsz'ModuleLoader.__init__..) idrwr.rr/__path__weakrefproxyryrzmodulerU)rrmodr)rUrr3s  zModuleLoader.__init__cCsdt|jdjS)NZtmpl_zutf-8)rencode hexdigest)r#rrrget_template_keyszModuleLoader.get_template_keycCstj|dS)Nz.py)rxr)r#rrrget_module_filenamesz ModuleLoader.get_module_filenameNc Cs|j|}d|j|f}t|j|d}|dkrnyt|dddg}Wntk r^t|YnXtjj |d|j j ||j |S)Nz%s.%sroot) rrUgetattrr __import__ ImportErrorrryrzr{r"Zfrom_module_dict__dict__)rrr#r$keyrrrrrr(s zModuleLoader.load)N) rr)r*r+rr3 staticmethodrrrr(rrrrrxs   rx)r+r?ryrtypesrrhashlibrZjinja2.exceptionsrZ jinja2.utilsrrZjinja2._compatrr robjectrr,rJrdrhrkrtrwrxrrrr s&    eCA6)