fZdZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddlmZddlmZddlmZdd lmZej*r dd lmZdd lmZd ed ej4efdZGddZGddeZGddeZGddeZGddeZ GddeZ!GddeZ"GddeZ#Gdd eZ$y)!zKAPI and implementations for loading templates from different data sources. N)abc)sha1) import_module) ModuleType)TemplateNotFound) internalcode) Environment)Templatetemplatereturnc^g}|jdD]}tjj|vsStjjrtjj|vs|tjj k(r t ||s|dk7s|j||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 piecespieces W/var/lib/jenkins/workspace/mettalog/venv/lib/python3.12/site-packages/jinja2/loaders.pysplit_template_pathrs}F$ GGKK5 277>>U#:&"8, , u| MM% % Mc 2eZdZdZdZdddedejeejeejejge fffdZ dejefdZ e dddd ed ejejeej fdd fd Zy ) 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 cr|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__r)selfrr s r get_sourcezBaseLoader.get_sourceKs=(%%:&&''KL x((rctd)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%s rlist_templateszBaseLoader.list_templatesesGHHrNnameglobalsr cHd}|i}|j||\}}}|j}| |j||||} | j}||j |||}|$ j|| _|j | |j 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,r0sourcefilenameuptodatebccbuckets rloadzBaseLoader.loadks ?G&*__[$%G"((( ?^^KxHF;;D <&&vtX>D ?v{{2FK NN6 "))33 w  rN)r$ __module__ __qualname____doc__r!strtTupleOptionalCallableboolr&Listr*r MutableMappingAnyr:rrrr*s<)()47) ajjoqzz!**RX2F'GG H)4Is I  =A ) ") ) A,,S!%%Z89 )  ) ) rrc eZdZdZ ddej edejej edffdededdfdZ d d d edejeeejgefffd Z dejefd Zy)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. searchpathos.PathLike[str]encoding followlinksr Nct|tjrt|tr|g}|Dcgc]}t j |c}|_||_||_ycc}wr;) isinstancerIterabler?rfspathrKrMrN)r%rKrMrNps r__init__zFileSystemLoader.__init__sP*cll3z*c7R$J1;.uptodates4 ww''1U::  s !% 11)rrK posixpathjoinrrisfileropenrMreadrWrDnormpath) r%rr rrKfcontentsr7r6rYs @@rr&zFileSystemLoader.get_sources%X.//J!~~j:6:Hww~~h' *#8, , (T]] 3 qvvxH   * $ ))(3X==  s 8CC(ct}|jD]}tj||j}|D]\}}}|D]}tj j ||t|djtj jjtj jd}|dddk(r|dd}||vs|j|t|S)N)rNrz./) setrKrwalkrNrr[lenstriprreplaceaddsorted) r%foundrKwalk_dirdirpath_ filenamesr6r s rr*zFileSystemLoader.list_templatess//Jwwzt7G7GHH)1%I )H Wh7J8IJrww{{+ c2  |t+#+AB<u, (+!**2*e}r)utf-8F)r$r<r=r>r@Unionr?SequencerDrTrArCr&rEr*rHrrrJrJs> ! 'GG #QZZ=O8O0P%Q Q  '  '  '  '>(>47> c1::b$h// 0>:s rrJc eZdZdZ ddedddeddfdZd d d edejeeejejge fffd Z dejefd Z y) 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. package_name package_pathr?rMr Nctjj|jtjj}|tjj k(rd}n@|ddtjj tjjzk(r|dd}||_||_||_t|tjj|}|Jd|j}|Jd||_d|_d}t!|t"j$rw|j&|_t)t+|j,}tjj/||jtjj}ng}|j,r|j1|j,nD|j28|j5tjj7|j2|D]E} tjj/| |} tjj9| sC| }n|t;d|d||_y)Nrcz-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.)rrr_rstriprcurdirrvrurMr importlibutil find_specloader_loader_archiverP zipimport zipimporterarchivenextitersubmodule_search_locationsr[extendoriginrdirnameisdir ValueError_template_root) r%rurvrMspecr~ template_rootpkgdirrootsroots rrTzPackageLoader.__init__s ww'' 5<> )L "1 "''++!= ='+L((   l#~~'' 5P!PP!L#LL!   fi33 4"NNDM$t>>?@FGGLL>EEbggkkRM!#E.. T<<=( RWW__T[[9:ww||D,777==&$(M   |&'77  ,rrr r cltjjtj|j gt ||j|tjjs t|td5}|j}dddtjjdtffd }n |jj}d}j#|j$|fS#1swYrxYw#t $r}t||d}~wwxYw)Nrbr ctjjxr"tjjk(Sr;)rrr\rW)rYrSsr up_to_datez,PackageLoader.get_source..up_to_datebs/ww~~a(IRWW-=-=a-@E-IIr)rrr_rZr[rrrr\rr]r^rWrDrget_datarXdecoderM) r%rr r`r5rerYrSs @@rr&zPackageLoader.get_sourceMs GG   NN4.. O1DX1N O  == 77>>!$&x00a "! "GG$$Q'E J J  8..q1J}}T]]+Q ::) " " 8&x0a7 8s$ D D D D3" D..D3cg}|jt|j}tj|jD]L\}}|dj tj j|jfd|DNn(t|jds td|jt|jdj tj jtj jz}t|}|jjjD]q}|j|s|dtj jk7s6|j||dj!tj jds|j#|S)Nc3K|]L}tjj|jtjjdNyw)rN)rrr[rhr).0r+rms r z/PackageLoader.list_templates..|s=GGLL$/77 SIsAA_fileszFThis zip import does not have the required metadata to list templates.r)rrfrrrelstriprrrhasattrrr(rkeys startswithrrhsort)r%resultsoffsetrnroprefixr+rms @rr*zPackageLoader.list_templatesss_! == ,,-F)+1D1D)E%I!&'*11"''++> )*F4<<23##C $6$89@@M''++ [F ++002??6*tBx277;;/FNN4=#8#8c#JK3  r) templatesrp)r$r<r=r>r?rTr@rArBrCrDr&rEr*rHrrrtrtsF* 9,9,9, 9,  9,v$;($;47$; c1::ajjT&:;; <$;L!s !rrtc eZdZdZdej eefddfdZdddedejedejge fffd Z dejefd Z y) 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 Nc||_yr;)r)r%rs rrTzDictLoader.__init__  rrr r cljvrjdfdfSt)Nc@jjk(Sr;)rget)r%r5r srz'DictLoader.get_source..s4<<3C3CH3M)Mr)rr)r%rr r5s` `@rr&zDictLoader.get_sources8 t|| #\\(+F4!MM Mx((rc,t|jSr;)rjrr)s rr*zDictLoader.list_templatessdll##r)r$r<r=r>r@Mappingr?rTrArCrDr&rEr*rHrrrrsu #s( 3)()47) dAJJr4x00 1)$s $rrc peZdZdZdej egejejeejeejeejej ge ffffddfdZ dddedejeejeejej ge fffd Z y) 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 Nc||_yr;)r)r%rs rrTzFunctionLoader.__init__s #rrr r cl|j|}| t|t|tr|ddfS|Sr;)rrrPr?)r%rr rvs rr&zFunctionLoader.get_sources=^^H % :"8, , b# tT> ! r) r$r<r=r>r@rCr?rBrqrArDrTr&rHrrrrs" #:: E JJajjoqzz!**RQUXBV7W!WXX    #  # ( 47  ajjoqzz!**RX2F'GG H rrc eZdZdZ ddej eefdeddfdZdedejeeffdZ d d dedejeejeejejge fffd Ze dd d d ed ejej eej"fddfdZdej&efdZy) 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 delimiterr Nc ||_||_yr;)rr)r%rrs rrTzPrefixLoader.__init__s "rr c |j|jd\}}|j|}||fS#ttf$r}t ||d}~wwxYw)Nr)rrrrKeyErrorr)r%r rr+r~rs r get_loaderzPrefixLoader.get_loaders] 4#>>$..!Acg}|jjD];\}}|jD]#}|j||jz|z%=|Sr;)ritemsr*rr)r%resultrr~r s rr*zPrefixLoader.list_templatessV"ll002NFF"113 ft~~5@A43 r)rr;)r$r<r=r>r@rr?rrTrArrBrCrDr&r rFrGr:rEr*rHrrrrs EH#yyj1#>A# # 3177:s?+C 4( 447 4 ajjoqzz!**RX2F'GG H 4 =A 0" 0 0A,,S!%%Z89 0  0 0s rrc XeZdZdZdej eddfdZdddedejeejeejejge fffd Z e dddd ed ejejeej fdd fd Zdej$efdZy) 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 Nc||_yr;)r)r%rs rrTzChoiceLoader.__init__)rrrr r c|jD]} |j||cSt|#t$rY/wxYwr;)rr&r)r%rr r~s rr&zChoiceLoader.get_source,sKllF ((h??# x(($  s 1 ==r+r,r c|jD]} |j|||cSt|#t$rY0wxYwr;)rr:r)r%rr+r,r~s rr:zChoiceLoader.load6sKllF {{;g>># t$$$  s 2 >>ct}|jD]!}|j|j#t |Sr;)rdrupdater*rj)r%rkr~s rr*zChoiceLoader.list_templatesDs6llF LL..0 1#e}rr;)r$r<r=r>r@rrrrTr?rArBrCrDr&r rFrGr:rEr*rHrrrrs  : 64)()47) ajjoqzz!**RX2F'GG H) =A %" % %A,,S!%%Z89 %  % %s rrceZdZdZy)_TemplateModulez9Like a normal module but with support for weak referencesN)r$r<r=r>rHrrrrKsCrrc "eZdZdZdZdej edejej edffddfdZ e dedefd Z e dedefd Z e dd d ded ejejeej fddfdZy) 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`. FrrLr Nc^dt|dt}t|tjrt|t r|g}|Dcgc]}t j|c}|_tj|fdtj<||_ |_ycc}w)N_jinja2_module_templates_xcDtjjdSr;)sysmodulespop)rrus rrz'ModuleLoader.__init__..ps3;;??<>r)idrrPrrQr?rrR__path__weakrefproxyrrmoduleru)r%rmodrSrus @rrTzModuleLoader.__init__^s 32d8A,? l+$ -D#1F6D.23 ! 3 $+MM >%  L! (4s B*r+cXdt|jdjzS)Ntmpl_rp)rencode hexdigestr+s rget_template_keyzModuleLoader.get_template_keyys$dkk'23==???rc2tj|dzS)Nz.py)rrrs rget_module_filenamez ModuleLoader.get_module_filename}s,,T2U::rrr r,r ch|j|}|jd|}t|j|d}|0 t |dddg}tjj|d|i}|jj||j|S#t $r}t ||d}~wwxYw)Nrr) rrugetattrr __import__ ImportErrorrrrrr3from_module_dict__dict__)r%rr+r,keyrrrs rr:zModuleLoader.loads##D)%%&au-dkk640 ; 4 tfX> KKOOFD ) ?G)):: w   4&t,!3 4sB B1 B,,B1r;)r$r<r=r>r!r@rqr?rrrT staticmethodrrr rBrFrGr:rHrrrrOs )gg #QZZ=O8O0P%Q Q )  )6@s@s@@;#;#;; =A  "  A,,S!%%Z89     rr)%r>importlib.utilr{rrZrtypingr@rr collectionsrhashlibrrtypesr exceptionsrutilsr TYPE_CHECKINGrr r r?rErrrJrtrrrrrrrHrrrs  #(??(%#!&&+"k k \VzVrcJcL$$0*Z*Z<:<~-:-`DjDL :L r