3

U'ícâXã@sNdZddlZddlZddlZddlZddlZddlZddl	m
Z
ddlmZddlm
Z
ddlmZddlmZdd	lmZdd
lmZejr¦ddlmZddlmZeejed
œdd„ZGdd„dƒZGdd„deƒZGdd„deƒZGdd„deƒZGdd„deƒZ Gdd„deƒZ!Gdd„deƒZ"Gdd„deƒZ#Gd d!„d!eƒZ$dS)"zKAPI and implementations for loading templates from different data
sources.
éN)Úabc)Úsha1)Ú
import_module)Ú
ModuleTypeé)ÚTemplateNotFound)Úinternalcode)Úopen_if_exists)ÚEnvironment)ÚTemplate)ÚtemplateÚreturncCshg}x^|jdƒD]P}tjj|ks@tjjr4tjj|ks@|tjjkrJt|ƒ‚q|r|dkr|j|ƒqW|S)z‰Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    ú/Ú.)ÚsplitÚosÚpathÚsepÚaltsepÚpardirrÚappend)rÚpiecesZpiece©rú0/tmp/pip-build-gk9425m9/Jinja2/jinja2/loaders.pyÚsplit_template_paths
rc	@sˆeZdZdZdZdeejeejeejej	ge
ffdœdd„Zejedœdd	„Z
eddeejejeejfddœd
d„ƒZd
S)Ú
BaseLoadera½Baseclass 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r
cCs&|jstt|ƒj›dƒ‚t|ƒ‚dS)a¯Get 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ÚRuntimeErrorÚtypeÚ__name__r)ÚselfrrrrrÚ
get_sourceJszBaseLoader.get_source)r
cCstdƒ‚dS)z”Iterates 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)r!rrrÚlist_templatesdszBaseLoader.list_templatesNr)rÚnameÚglobalsr
c
Csd}|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)r"Zbytecode_cacheZ
get_bucketÚcodeÚcompileZ
set_bucketÚtemplate_classZ	from_code)
r!rr%r&r'ÚsourceÚfilenameÚuptodateZbccZbucketrrrÚloadjs

zBaseLoader.load)N)r Ú
__module__Ú__qualname__Ú__doc__rÚstrÚtÚTupleÚOptionalÚCallableÚboolr"ÚListr$rÚMutableMappingÚAnyr-rrrrr)s0rc@s‚eZdZdZdejeejej	ejeejffee
ddœdd„Zdeejeeej
ge
ffd	œd
d„Zejedœd
d„ZdS)Ú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)Ú
searchpathÚencodingÚfollowlinksr
cCs>t|tjƒst|tƒr|g}dd„|Dƒ|_||_||_dS)NcSsg|]}tj|ƒ‘qSr)rÚfspath)Ú.0Úprrrú
<listcomp>»sz-FileSystemLoader.__init__.<locals>.<listcomp>)Ú
isinstancerÚIterabler1r<r=r>)r!r<r=r>rrrÚ__init__²s
zFileSystemLoader.__init__r
)rrr
c
st|ƒ}xz|jD]p}tjj|f|žŽ‰tˆƒ}|dkr8qz|jƒj|jƒ}Wd|j	ƒXtjj
ˆƒ‰tdœ‡‡fdd„}|ˆ|fSWt|ƒ‚dS)N)r
cs*ytjjˆƒˆkStk
r$dSXdS)NF)rrÚgetmtimeÚOSErrorr)r+Úmtimerrr,Ïsz-FileSystemLoader.get_source.<locals>.uptodate)
rr<rrÚjoinr	ÚreadÚdecoder=ÚcloserFr6r)r!rrrr<ÚfÚcontentsr,r)r+rHrr"¿s
zFileSystemLoader.get_source)r
c	Cs®tƒ}xž|jD]”}tj||jd}x~|D]v\}}}xj|D]b}tjj||ƒt|ƒd…jtjj	ƒj
tjj	dƒ}|dd…dkrˆ|dd…}||kr8|j|ƒq8Wq(WqWt|ƒS)N)r>réz./)
Úsetr<rÚwalkr>rrIÚlenÚstriprÚreplaceÚaddÚsorted)	r!Úfoundr<Zwalk_dirÚdirpathÚ_Ú	filenamesr+rrrrr$Øs

zFileSystemLoader.list_templates)r;F)r r.r/r0r2ÚUnionr1rÚPathLikeÚSequencer6rEr3r5r"r7r$rrrrr:—s(	$r:c	@sheZdZdZdededdœdd„Zd	eejeeejej	ge
ffd
œdd„Zejed
œdd„Z
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.
    Ú	templatesúutf-8r1N)Úpackage_nameÚpackage_pathr=r
c
Csltjj|ƒjtjjƒ}|tjjkr(d}n(|dd…tjjtjjkrP|dd…}||_||_||_t	|ƒt
jj|ƒ}|dk	s†t
dƒ‚|j}|dk	sœt
dƒ‚||_d|_d}t|tjƒrÞ|j|_tt|jƒƒ}tjj||ƒ}njg}|jrö|j|jƒn |jdk	r|jtjj|jƒƒx0|D](}	tjj|	|ƒ}	tjj|	ƒr|	}PqW|dkrbtd|›dƒ‚||_dS)NÚrOz-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.) rrÚnormpathÚrstriprÚcurdirrbrar=rÚ	importlibÚutilÚ	find_specÚAssertionErrorÚloaderÚ_loaderÚ_archiverCÚ	zipimportÚzipimporterÚarchiveÚnextÚiterÚsubmodule_search_locationsrIÚextendÚoriginrÚdirnameÚisdirÚ
ValueErrorÚ_template_root)
r!rarbr=ÚspecrkZ
template_rootZpkgdirÚrootsÚrootrrrrEsD

zPackageLoader.__init__r
)rrr
csÊtjj|jft|ƒžŽ‰|jdkrvtjjˆƒs6t|ƒ‚tˆdƒ}|j	ƒ}WdQRXtjj
ˆƒ‰tdœ‡‡fdd„}nBy|jj
ˆƒ}Wn,tk
r²}zt|ƒ|‚WYdd}~XnXd}|j|jƒˆ|fS)NÚrb)r
cstjjˆƒotjjˆƒˆkS)N)rrÚisfilerFr)rHrArrÚ
up_to_dateVsz,PackageLoader.get_source.<locals>.up_to_date)rrrIryrrmr~rÚopenrJrFr6rlÚget_datarGrKr=)r!rrrMr*rÚer)rHrArr"Fs
zPackageLoader.get_source)r
csg}|jdkrdt|jƒ}xÚtj|jƒD]8\‰}}ˆ|d…jtjjƒ‰|j‡fdd„|Dƒƒq&Wnt	|j
dƒsxtdƒ‚|jt|jƒd…jtjjƒtjj}t|ƒ}xL|j
jj
ƒD]<}|j|ƒr´|dtjjkr´|j||d…jtjjdƒƒq´W|jƒ|S)Nc3s(|] }tjjˆ|ƒjtjjdƒVqdS)rN)rrrIrTr)r@r%)rXrrú	<genexpr>qsz/PackageLoader.list_templates.<locals>.<genexpr>Ú_fileszFThis zip import does not have the required metadata to list templates.rréÿÿÿÿ)rmrRryrrQÚlstriprrrtÚhasattrrlr#r„ÚkeysÚ
startswithrrTÚsort)r!ÚresultsÚoffsetrYrZÚprefixr%r)rXrr$gs&



"zPackageLoader.list_templates)r_r`)r r.r/r0r1rEr2r3r4r5r6r"r7r$rrrrr^ês7*r^c@sfeZdZdZejeefddœdd„Zdeejedej	ge
ffdœdd	„Zejed
œdd„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)Úmappingr
cCs
||_dS)N)r)r!rrrrrE”szDictLoader.__init__r
)rrr
cs6ˆˆjkr*ˆjˆ‰ˆd‡‡‡fdd„fStˆƒ‚dS)NcsˆˆjjˆƒkS)N)rÚgetr)r!r*rrrÚ<lambda>œsz'DictLoader.get_source.<locals>.<lambda>)rr)r!rrr)r!r*rrr"—s

zDictLoader.get_source)r
cCs
t|jƒS)N)rVr)r!rrrr$ŸszDictLoader.list_templates)r r.r/r0r2ÚMappingr1rEr3r5r6r"r7r$rrrrrŽ‹s
$rŽc@s’eZdZdZejegejejeej	eejeejejge
ffffddœdd„Zdeej	eejeejejge
ffdœdd	„ZdS)
ÚFunctionLoadera­A 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_funcr
cCs
||_dS)N)r”)r!r”rrrrEµszFunctionLoader.__init__r
)rrr
cCs2|j|ƒ}|dkrt|ƒ‚t|tƒr.|ddfS|S)N)r”rrCr1)r!rrÚrvrrrr"Âs


zFunctionLoader.get_source)
r r.r/r0r2r5r1r4r[r3r6rEr"rrrrr“£s0r“c	@s¼eZdZdZdejeefeddœdd„Zeej	eefdœdd	„Z
d
eej	eejeejejge
ffdœdd
„Zedd
eejejeejfddœdd„ƒZejedœdd„ZdS)Ú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Ú	delimiterr
cCs||_||_dS)N)rr—)r!rr—rrrrEßszPrefixLoader.__init__)rr
cCsZy |j|jdƒ\}}|j|}Wn0ttfk
rP}zt|ƒ|‚WYdd}~XnX||fS)Nr)rr—rrxÚKeyErrorr)r!rrr%rkr‚rrrÚ
get_loaderåszPrefixLoader.get_loaderr
)rrr
cCsL|j|ƒ\}}y|j||ƒStk
rF}zt|ƒ|‚WYdd}~XnXdS)N)r™r"r)r!rrrkr%r‚rrrr"ís
zPrefixLoader.get_sourcer)rr%r&r
cCsN|j|ƒ\}}y|j|||ƒStk
rH}zt|ƒ|‚WYdd}~XnXdS)N)r™r-r)r!rr%r&rkZ
local_namer‚rrrr-øs
zPrefixLoader.load)r
cCsFg}x<|jjƒD].\}}x$|jƒD]}|j||j|ƒq"WqW|S)N)rÚitemsr$rr—)r!Úresultrrkrrrrr$s
zPrefixLoader.list_templates)r)N)r r.r/r0r2r’r1rrEr3r™r4r5r6r"rr8r9r-r7r$rrrrr–Ðs
	0		r–c	@sšeZdZdZejeddœdd„Zdeej	eej
eej
ejgeffdœdd	„Z
eddeej
ejeejfd
dœdd
„ƒZejedœdd„ZdS)ÚChoiceLoaderaªThis 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)Úloadersr
cCs
||_dS)N)r)r!rrrrrEszChoiceLoader.__init__r
)rrr
cCs>x0|jD]&}y|j||ƒStk
r,YqXqWt|ƒ‚dS)N)rr"r)r!rrrkrrrr" s
zChoiceLoader.get_sourcer)rr%r&r
cCs@x2|jD](}y|j|||ƒStk
r.YqXqWt|ƒ‚dS)N)rr-r)r!rr%r&rkrrrr-*s
zChoiceLoader.load)r
cCs,tƒ}x|jD]}|j|jƒƒqWt|ƒS)N)rPrÚupdater$rV)r!rWrkrrrr$8szChoiceLoader.list_templates)N)r r.r/r0r2r]rrEr1r3r4r5r6r"rr8r9r-r7r$rrrrrœs0rœc@seZdZdZdS)Ú_TemplateModulez9Like a normal module but with support for weak referencesN)r r.r/r0rrrrrŸ?srŸc@s˜eZdZdZdZejeej	ej
ejeej	ffddœdd„Zeeedœdd	„ƒZ
eeedœd
d„ƒZeddeejejeejfd
dœdd„ƒZdS)Ú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)rr
cspdt|ƒd›‰tˆƒ}t|tjƒs0t|tƒr6|g}dd„|Dƒ|_tj|‡fdd„ƒt	j
ˆ<||_ˆ|_dS)NZ_jinja2_module_templates_ÚxcSsg|]}tj|ƒ‘qSr)rr?)r@rArrrrB^sz)ModuleLoader.__init__.<locals>.<listcomp>cstjjˆdƒS)N)ÚsysÚmodulesÚpop)r¡)rarrr‘asz'ModuleLoader.__init__.<locals>.<lambda>)
ÚidrŸrCrrDr1Ú__path__ÚweakrefÚproxyr¢r£Úmodulera)r!rÚmodr)rarrERszModuleLoader.__init__)r%r
cCsdt|jdƒƒjƒS)NZtmpl_zutf-8)rÚencodeÚ	hexdigest)r%rrrÚget_template_keyjszModuleLoader.get_template_keycCstj|ƒdS)Nz.py)r r­)r%rrrÚget_module_filenamensz ModuleLoader.get_module_filenamer
r)rr%r&r
cCsž|j|ƒ}|j›d|›}t|j|dƒ}|dkr€yt|dddgƒ}Wn,tk
rp}zt|ƒ|‚WYdd}~XnXtjj	|dƒ|dkrŒi}|j
j||j|ƒS)Nrr|)
r­raÚgetattrr©Ú
__import__ÚImportErrorrr¢r£r¤r)Zfrom_module_dictÚ__dict__)r!rr%r&Úkeyr©rªr‚rrrr-rs
zModuleLoader.load)N)r r.r/r0rr2r[r1rr\r]rEÚstaticmethodr­r®rr4r8r9r-rrrrr Cs"r )%r0Úimportlib.utilrgrr¢Útypingr2r§rnÚcollectionsrÚhashlibrrÚtypesrÚ
exceptionsrÚutilsrr	Z
TYPE_CHECKINGrr
rr1r7rrr:r^rŽr“r–rœrŸr rrrrÚ<module>s6nS"-?0