o G؊aX@sPdZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddlm Z ddlmZddlmZdd lmZdd lmZejrSdd lmZdd lmZd edejefddZGdddZGdddeZGdddeZGdddeZGdddeZ GdddeZ!GdddeZ"Gdd d eZ#Gd!d"d"eZ$dS)#zKAPI and implementations for loading templates from different data sources. N)abc)sha1) import_module) ModuleType)TemplateNotFound) internalcode)open_if_exists) Environment)TemplatetemplatereturncCsbg}|dD]'}tjj|vstjjrtjj|vs|tjjkr#t||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. /.)splitospathsepaltseppardirrappend)r piecespiecer0/usr/lib/python3/dist-packages/jinja2/loaders.pysplit_template_paths     rc @seZdZdZdZdddedejeejeejej ge fffddZ dej efd d Z e dddd ed ejejeejfddfddZd S) 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 open(path) as f: source = f.read() return source, path, lambda: mtime == getmtime(path) T environmentr r r cCs"|js tt|jdt|)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 a string. 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$ cannot provide access to the source)has_source_access RuntimeErrortype__name__rselfrr rrr get_sourceJs zBaseLoader.get_sourcecCstd)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 templates) TypeErrorr#rrrlist_templatesdszBaseLoader.list_templatesNnameglobalsr c Csd}|duri}|||\}}}|j}|dur#|||||} | 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$bytecode_cache get_bucketcodecompile set_buckettemplate_class from_code) r#rr(r)r,sourcefilenameuptodatebccbucketrrrloadjs   zBaseLoader.loadN)r! __module__ __qualname____doc__rstrtTupleOptionalCallableboolr$Listr'rMutableMappingAnyr6rrrrr)s,$ rc @seZdZdZ  ddejeejej ejeejffdede ddfd d Z d d d edej eeej ge fffddZdejefddZdS)FileSystemLoaderaLoad templates from a directory in the file system. The path can be relative or absolute. Relative paths are relative to the current working directory. .. code-block:: python loader = FileSystemLoader("templates") A list of paths can be given. The directories will be searched in order, stopping at the first matching template. .. code-block:: python loader = FileSystemLoader(["/override/templates", "/default/templates"]) :param searchpath: A path, or list of paths, to the directory that contains the templates. :param encoding: Use this encoding to read the text from template files. :param followlinks: Follow symbolic links in the path. .. versionchanged:: 2.8 Added the ``followlinks`` parameter. utf-8F searchpathencoding followlinksr NcCs<t|tjr t|tr|g}dd|D|_||_||_dS)NcSg|]}t|qSrrfspath.0prrr z-FileSystemLoader.__init__..) isinstancerIterabler;rFrGrH)r#rFrGrHrrr__init__s  zFileSystemLoader.__init__rr r c st|}|jD]?}tjj|g|Rt}|durqz||j}W| n| wtj dt ffdd }||fSt |)Nr cs(z tjkWStyYdSw)NF)rrgetmtimeOSErrorrr2mtimerrr3s  z-FileSystemLoader.get_source..uptodate) rrFrrjoinr readdecoderGcloserTr@r)r#rr rrFfcontentsr3rrVrr$s  zFileSystemLoader.get_sourcec Cst}|jD]F}tj||jd}|D]9\}}}|D]1}tj||t|dtjj  tjj d}|dddkrA|dd}||vrJ| |qqqt |S)N)rHrz./) setrFrwalkrHrrXlenstriprreplaceaddsorted) r#foundrFwalk_dirdirpath_ filenamesr2r rrrr's"      zFileSystemLoader.list_templates)rEF)r!r8r9r:r<Unionr;rPathLikeSequencer@rSr=r?r$rAr'rrrrrDs*"   rDc @sveZdZdZ  ddedddedd fd d Zd d dedejeeejej ge fffddZ dej efddZ d S) PackageLoaderalLoad templates from a directory in a Python package. :param package_name: Import name of the package that contains the template directory. :param package_path: Directory within the imported package that contains the templates. :param encoding: Encoding of template files. The following example looks up templates in the ``pages`` directory within the ``project.ui`` package. .. code-block:: python loader = PackageLoader("project.ui", "pages") Only packages installed as directories (standard pip behavior) or zip/egg files (less common) are supported. The Python API for introspecting data in packages is too limited to support other installation methods the way this loader requires. There is limited support for :pep:`420` namespace packages. The template directory is assumed to only be in one namespace contributor. Zip files contributing to a namespace are not supported. .. versionchanged:: 3.0 No longer uses ``setuptools`` as a dependency. .. versionchanged:: 3.0 Limited PEP 420 namespace package support. templatesrE package_name package_pathr;rGr Nc Csbtj|tjj}|tjjkrd}n|ddtjjtjjkr(|dd}||_||_||_t |t j |}|dusCJd|j }|dusNJd||_d|_d}t|tjro|j|_tt|j}tj||}n1g}|jr{||jn|jdur|tj|j|D]} tj| |} tj| r| }nq|durtd|d||_dS)Nr^z-An import spec was not found for the package.z'A loader was not found for the package.zThe zC package was not installed in a way that PackageLoader understands.)rrnormpathrstriprcurdirrqrprGr importlibutil find_specloader_loader_archiverQ zipimport zipimporterarchivenextitersubmodule_search_locationsrXextendoriginrdirnameisdir ValueError_template_root) r#rprqrGspecry template_rootpkgdirrootsrootrrrrS sH        zPackageLoader.__init__rr r c stjj|jgt|R|jdurFtjst|td }| }Wdn1s0wYtj dt ffdd }nz|j }Wnty_}zt||d}~wwd}||j|fS)Nrbr cstjo tjkSr7)rrisfilerTrrWrNrr up_to_dateVsz,PackageLoader.get_source..up_to_date)rrrXrrr{rropenrYrTr@rzget_datarUrZrG)r#rr r\r1rerrrr$Fs"      zPackageLoader.get_sourcecsg}|jdur0t|j}t|jD]\}}|dtjj|fdd|DqnFt |j ds:t d|jt|jdtjjtjj}t|}|j j D]}||ru|dtjjkru|||dtjjdqW||S)Nc3s*|]}tj|tjjdVqdS)rN)rrrXrcr)rMr(rhrr ps  z/PackageLoader.list_templates.._fileszFThis zip import does not have the required metadata to list templates.r)r{rarrr`lstriprrrhasattrrzr%rkeys startswithrrcsort)r#resultsoffsetrirjprefixr(rrrr'gs0    zPackageLoader.list_templates)rorE)r!r8r9r:r;rSr<r=r>r?r@r$rAr'rrrrrns*# ; !rnc @sleZdZdZdejeefddfddZddd edejedej ge fffd d Z dej efd d Z dS) DictLoaderaLoads a template from a Python dict mapping template names to template source. This loader is useful for unittesting: >>> loader = DictLoader({'index.html': 'source here'}) Because auto reloading is rarely useful this is disabled per default. mappingr NcC ||_dSr7)r)r#rrrrrS zDictLoader.__init__rr r cs2jvrjdfddfSt)NcsjkSr7)rgetrr#r1r rrsz'DictLoader.get_source..)rrr"rrrr$s  zDictLoader.get_sourcecCs t|jSr7)rerr&rrrr'rzDictLoader.list_templates)r!r8r9r:r<Mappingr;rSr=r?r@r$rAr'rrrrrs rc @seZdZdZdejegejejeej eejeejejge ffffddfddZ ddd edej eejeejejge fffd d Z dS) FunctionLoaderaA loader that is passed a function which does the loading. The function receives the name of the template and has to return either a 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. load_funcr NcCrr7)r)r#rrrrrSs zFunctionLoader.__init__rr r cCs2||}|dur t|t|tr|ddfS|Sr7)rrrQr;)r#rr rvrrrr$s   zFunctionLoader.get_source) r!r8r9r:r<r?r;r>rkr=r@rSr$rrrrrs,(  $rc @seZdZdZ ddejeefdeddfddZd edej eeffd d Z d d d edej eej eej ej ge fffddZe dd d dedej ejeejfddfddZdejefddZdS) 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. rr delimiterr NcCs||_||_dSr7)rr)r#rrrrrrSs zPrefixLoader.__init__r c CsNz||jd\}}|j|}W||fSttfy&}zt||d}~ww)Nr)rrrrKeyErrorr)r#r rr(ryrrrr get_loaders  zPrefixLoader.get_loaderrr c Cs@||\}}z|||WSty}zt||d}~wwr7)rr$r)r#rr ryr(rrrrr$s zPrefixLoader.get_sourcer(r)r c CsB||\}}z||||WSty }zt||d}~wwr7)rr6r)r#rr(r)ry local_namerrrrr6s zPrefixLoader.loadcCs>g}|jD]\}}|D] }|||j|qq|Sr7)ritemsr'rr)r#resultrryr rrrr's  zPrefixLoader.list_templates)rr7)r!r8r9r:r<rr;rrSr=rr>r?r@r$rrBrCr6rAr'rrrrrs<  $   rc @seZdZdZdejeddfddZddd edej eej eej ej ge fffd d Z e dddd ed ej ejeejfddfddZdejefddZdS) 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. loadersr NcCrr7)r)r#rrrrrSrzChoiceLoader.__init__rr r c Cs8|jD]}z |||WStyYqwt|r7)rr$r)r#rr ryrrrr$ s  zChoiceLoader.get_sourcer(r)r c Cs:|jD]}z ||||WStyYqwt|r7)rr6r)r#rr(r)ryrrrr6*s  zChoiceLoader.loadcCs(t}|jD] }||qt|Sr7)r_rupdater're)r#rfryrrrr'8s zChoiceLoader.list_templatesr7)r!r8r9r:r<rmrrSr;r=r>r?r@r$rrBrCr6rAr'rrrrrs, $    rc@seZdZdZdS)_TemplateModulez9Like a normal module but with support for weak referencesN)r!r8r9r:rrrrr?src @seZdZdZdZdejeej ej ejeej ffddfddZ e dedefd d Z e dedefd d Ze dd ddedejejeejfddfddZdS) 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`. Frr Ncsndt|dt}t|tjrt|tr|g}dd|D|_t|fddt j <||_ |_ dS)N_jinja2_module_templates_xcSrIrrJrLrrrrO^rPz)ModuleLoader.__init__..cstjdSr7)sysmodulespop)rrprrrasz'ModuleLoader.__init__..) idrrQrrRr;__path__weakrefproxyrrmodulerp)r#rmodrrrrSRs   zModuleLoader.__init__r(cCsdt|dS)Ntmpl_rE)rencode hexdigestr(rrrget_template_keyjszModuleLoader.get_template_keycCst|dS)Nz.py)rrrrrrget_module_filenamensz ModuleLoader.get_module_filenamerr r)r c Cs||}|jd|}t|j|d}|dur;z t|dddg}Wnty3}zt||d}~wwtj |d|durAi}|j ||j |S)Nrr) rrpgetattrr __import__ ImportErrorrrrrr/from_module_dict__dict__)r#rr(r)keyrrrrrrr6rs  zModuleLoader.loadr7)r!r8r9r:rr<rkr;rrlrmrS staticmethodrrrr>rBrCr6rrrrrCs. " r)%r:importlib.utilrvrrtypingr<rr| collectionsrhashlibrrtypesr exceptionsrutilsrr TYPE_CHECKINGrr r r;rArrrDrnrrrrrrrrrrs8         nS"-?0