U aNW@sNdZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddlm Z ddlmZddlmZdd lmZdd lmZejrdd lmZdd lmZeejed ddZGdddZGdddeZGdddeZGdddeZGdddeZ GdddeZ!GdddeZ"GdddeZ#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)TemplatetemplatereturncCsdg}|dD]P}tjj|ks>tjjr2tjj|ks>|tjjkrHt|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. /.)splitospathsepaltseppardirrappend)r piecesZpiecerOC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-8gbwd15f\jinja2\loaders.pysplit_template_paths      rc @seZdZdZdZdeejeejeejej ge ffdddZ ej eddd Z eddeejejeejfd d d dZd 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) Tr  environmentr rcCs&|jstt|jdt|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 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 sourceN)has_source_access RuntimeErrortype__name__rselfrr rrr get_sourceJs zBaseLoader.get_sourcercCs 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_templatesdszBaseLoader.list_templatesNr rnameglobalsrc Csd}|dkri}|||\}}}|j}|dk rF|||||} | j}|dkr\||||}|dk r~| jdkr~|| _|| |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$rr+r,r-sourcefilenameuptodateZbccZbucketrrrloadjs&  zBaseLoader.load)N)r" __module__ __qualname____doc__rstrtTupleOptionalCallableboolr%Listr)rMutableMappingAnyr3rrrrr)s$ rc@seZdZdZdejeejej ejeejffee ddddZ deej eeej ge ffd d d Zejed d dZdS)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-8FN) searchpathencoding followlinksrcCs<t|tjrt|tr|g}dd|D|_||_||_dS)NcSsg|]}t|qSrrfspath.0prrr sz-FileSystemLoader.__init__..) isinstancerIterabler7rBrCrD)r$rBrCrDrrr__init__s zFileSystemLoader.__init__r rc st|}|jD]t}tjj|f|t}|dkr6qz||j }W5|Xtj t dfdd }||fSt |dS)Nr&cs.ztjkWStk r(YdSXdS)NF)rrgetmtimeOSErrorrr1mtimerrr2sz-FileSystemLoader.get_source..uptodate) rrBrrjoinr closereaddecoderCrNr<r)r$rr rrBfcontentsr2rrPrr%s   zFileSystemLoader.get_sourcer&c Cst}|jD]}tj||jd}|D]r\}}}|D]b}tj||t|dtjj  tjj d}|dddkr|dd}||kr2| |q2q$q t |S)N)rDrz./) setrBrwalkrDrrRlenstriprreplaceaddsorted) r$foundrBZwalk_dirdirpath_ filenamesr1r rrrr)s"  zFileSystemLoader.list_templates)rAF)r"r4r5r6r8Unionr7rPathLikeSequencer<rMr9r;r%r=r)rrrrr@s"  r@c @sheZdZdZdededdddZd eejeeejej ge ffd d d Z ej ed ddZ dS) 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. templatesrAr7N) package_name package_pathrCrc Cs:|tjjkrd}n(|ddtjjtjjkr:|dd}tj|tjj}||_||_||_t |t j |}|dk st d|j}|dk st d||_d|_d}t|tjr|j|_tt|j}tj||}n8|jr|jD](}tj||}tj|r|}qq|dkr0td|d||_dS)NrXz-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.)rrcurdirrnormpathrstriprjrirCr importlibutil find_specAssertionErrorloader_loader_archiverK zipimport zipimporterarchivenextitersubmodule_search_locationsrRisdir ValueError_template_root) r$rirjrCspecrsZ template_rootZpkgdirrootrrrrM s>        zPackageLoader.__init__r rc stjj|jft||jdkrvtjs6t|td}| }W5QRXtj t dfdd }n2z|j }Wntk rt|YnXd}||j|fS)Nrbr&cstjotjkSN)rrisfilerNrrQrIrr up_to_dateLsz,PackageLoader.get_source..up_to_date)rrrRr~rrurropenrTrNr<rtget_datarOrUrC)r$rr rVr0rrrrr%<s    zPackageLoader.get_sourcer&csg}|jdkr`t|j}t|jD]8\}}|dtjj|fdd|Dq$nt |j dstt d|jt|jdtjjtjj}t|}|j j D]<}||r|dtjjkr|||dtjjdq||S)Nc3s(|] }tj|tjjdVqdS)rN)rrrRr]r)rHr+rarr fsz/PackageLoader.list_templates.._fileszFThis zip import does not have the required metadata to list templates.r)rur[r~rrZlstriprrextendhasattrrtr'rkeys startswithrr]sort)r$resultsoffsetrbrcprefixr+rrrr)]s,     zPackageLoader.list_templates)rhrA)r"r4r5r6r7rMr8r9r:r;r<r%r=r)rrrrrgs# 2 !rgc@sfeZdZdZejeefddddZdeejedej ge ffddd Z ej ed d 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. N)mappingrcCs ||_dSr)r)r$rrrrrMszDictLoader.__init__r rcs6jkr*jdfddfStdS)NcsjkSr)rgetrr$r0r rrz'DictLoader.get_source..)rrr#rrrr%s  zDictLoader.get_sourcer&cCs t|jSr)r_rr(rrrr)szDictLoader.list_templates)r"r4r5r6r8Mappingr7rMr9r;r<r%r=r)rrrrrs rc @seZdZdZejegejejeej eejeejejge ffffddddZ deej eejeejejge ffddd 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. N) load_funcrcCs ||_dSr)r)r$rrrrrMs zFunctionLoader.__init__r rcCs2||}|dkrt|t|tr.|ddfS|Sr)rrrKr7)r$rr rvrrrr%s    zFunctionLoader.get_source) r"r4r5r6r8r;r7r:rdr9r<rMr%rrrrrs ( $rc @seZdZdZdejeefeddddZeej eefddd Z d eej eej eej ej ge ffd d d Zedd eej ejeejfddddZejedddZdS) 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. rN)r delimiterrcCs||_||_dSr)rr)r$rrrrrrMszPrefixLoader.__init__r c CsJz ||jd\}}|j|}Wn ttfk r@t|YnX||fS)Nr)rrrr}KeyErrorr)r$r rr+rsrrr get_loaders zPrefixLoader.get_loaderr rcCs>||\}}z|||WStk r8t|YnXdSr)rr%r)r$rr rsr+rrrr%s zPrefixLoader.get_sourcer r*cCs@||\}}z||||WStk r:t|YnXdSr)rr3r)r$rr+r,rsZ local_namerrrr3s zPrefixLoader.loadr&cCs>g}|jD]*\}}|D]}|||j|qq|Sr)ritemsr)rr)r$resultrrsr rrrr)s  zPrefixLoader.list_templates)r)N)r"r4r5r6r8rr7rrMr9rr:r;r<r%rr>r?r3r=r)rrrrrs*   $ rc @seZdZdZejeddddZdeej eej eej ej ge ffddd Z eddeej ejeejfd d d d ZejedddZdS) 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. N)loadersrcCs ||_dSr)r)r$rrrrrMszChoiceLoader.__init__r rc Cs@|jD],}z|||WStk r0YqXqt|dSr)rr%r)r$rr rsrrrr%s  zChoiceLoader.get_sourcer r*c CsB|jD].}z||||WStk r2YqXqt|dSr)rr3r)r$rr+r,rsrrrr3 s  zChoiceLoader.loadr&cCs(t}|jD]}||q t|Sr)rYrupdater)r_)r$r`rsrrrr).s zChoiceLoader.list_templates)N)r"r4r5r6r8rfrrMr7r9r:r;r<r%rr>r?r3r=r)rrrrrs $  rc@seZdZdZdS)_TemplateModulez9Like a normal module but with support for weak referencesN)r"r4r5r6rrrrr5src@seZdZdZdZejeej ej ejeej ffddddZ e eeddd Z e eedd d Zedd eejejeejfd dddZdS) 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`. FN)rrcsndt|dt}t|tjr.t|tr4|g}dd|D|_t|fddt j <||_ |_ dS)NZ_jinja2_module_templates_xcSsg|]}t|qSrrErGrrrrJTsz)ModuleLoader.__init__..cstjdSr)sysmodulespop)rrirrrWrz'ModuleLoader.__init__..) idrrKrrLr7__path__weakrefproxyrrmoduleri)r$rmodrrrrMHs zModuleLoader.__init__)r+rcCsdt|dS)NZtmpl_rA)rencode hexdigestr+rrrget_template_key`szModuleLoader.get_template_keycCst|dS)Nz.py)rrrrrrget_module_filenamedsz ModuleLoader.get_module_filenamer r r*cCs||}|jd|}t|j|d}|dkrpzt|dddg}Wntk r`t|YnXtj |d|dkr|i}|j ||j |S)Nrr) rrigetattrr __import__ ImportErrorrrrrr/Zfrom_module_dict__dict__)r$rr+r,keyrrrrrr3hs  zModuleLoader.load)N)r"r4r5r6rr8rdr7rrerfrM staticmethodrrrr:r>r?r3rrrrr9s" " r)%r6importlib.utilrorrtypingr8rrv collectionsrhashlibrrtypesr exceptionsrutilsrr TYPE_CHECKINGrr r r7r=rrr@rgrrrrrrrrrrs6         nS-?0