3

U'íc~1ã@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z
ddlmZddl
mZddlmZe
jrœddlZddlmZGdd	„d	ejƒZd
Zdejedƒejejdd
>ejdBdƒZGdd„dƒZGdd„dƒZGdd„deƒZGdd„deƒZdS)a The optional bytecode cache system. This is useful if you have very
complex template situations and the compilation of all those templates
slows down your application too much.

Situations where this is useful are often forking web applications that
are initialized on the first request.
éN)Úsha1)ÚBytesIO)ÚCodeTypeé)ÚEnvironmentc@s8eZdZeedœdd„Zdeeejeddœdd„Z	dS)	Ú_MemcachedClient)ÚkeyÚreturncCsdS)N©)Úselfrr
r
ú0/tmp/pip-build-gk9425m9/Jinja2/jinja2/bccache.pyÚgetsz_MemcachedClient.getN)rÚvalueÚtimeoutr	cCsdS)Nr
)rrrrr
r
rÚsetsz_MemcachedClient.set)N)
Ú__name__Ú
__module__Ú__qualname__ÚstrÚbytesr
ÚtÚOptionalÚintrr
r
r
rrsrésj2ééc@steZdZdZdeeddœdd„Zddœdd	„Zejdd
œdd„Z	ejdd
œd
d„Z
eddœdd„Zedœdd„Z
dS)ÚBucketauBuckets are used to store the bytecode for one template.  It's created
    and initialized by the bytecode cache and passed to the loading functions.

    The buckets get an internal checksum from the cache assigned and use this
    to automatically reject outdated cache material.  Individual bytecode
    cache subclasses don't have to care about cache invalidation.
    rN)ÚenvironmentrÚchecksumr	cCs||_||_||_|jƒdS)N)rrrÚreset)rrrrr
r
rÚ__init__5szBucket.__init__)r	cCs
d|_dS)z)Resets the bucket (unloads the bytecode).N)Úcode)rr
r
rr;szBucket.reset)Úfr	c
Csz|jttƒƒ}|tkr"|jƒdStj|ƒ}|j|krB|jƒdSytj|ƒ|_Wn"t	t
tfk
rt|jƒdSXdS)z/Loads bytecode from a file or file like object.N)ÚreadÚlenÚbc_magicrÚpickleÚloadrÚmarshalr!ÚEOFErrorÚ
ValueErrorÚ	TypeError)rr"Úmagicrr
r
rÚ
load_bytecode?s

zBucket.load_bytecodecCs>|jdkrtdƒ‚|jtƒtj|j|dƒtj|j|ƒdS)z;Dump the bytecode into the file or file like object passed.Nzcan't write empty bucketr)r!r+Úwriter%r&Údumprr()rr"r
r
rÚwrite_bytecodeRs


zBucket.write_bytecode)Ústringr	cCs|jt|ƒƒdS)zLoad bytecode from bytes.N)r-r)rr1r
r
rÚbytecode_from_stringZszBucket.bytecode_from_stringcCstƒ}|j|ƒ|jƒS)zReturn the bytecode as bytes.)rr0Úgetvalue)rÚoutr
r
rÚbytecode_to_string^s
zBucket.bytecode_to_string)rrrÚ__doc__rr rrZBinaryIOr-r0rr2r5r
r
r
rr,src@sšeZdZdZeddœdd„Zeddœdd„Zddœd	d
„Zdee	j
e	jeedœdd
„Zeedœdd„Z
dee	j
eeedœdd„Zeddœdd„ZdS)Ú
BytecodeCacheaÞTo implement your own bytecode cache you have to subclass this class
    and override :meth:`load_bytecode` and :meth:`dump_bytecode`.  Both of
    these methods are passed a :class:`~jinja2.bccache.Bucket`.

    A very basic bytecode cache that saves the bytecode on the file system::

        from os import path

        class MyCache(BytecodeCache):

            def __init__(self, directory):
                self.directory = directory

            def load_bytecode(self, bucket):
                filename = path.join(self.directory, bucket.key)
                if path.exists(filename):
                    with open(filename, 'rb') as f:
                        bucket.load_bytecode(f)

            def dump_bytecode(self, bucket):
                filename = path.join(self.directory, bucket.key)
                with open(filename, 'wb') as f:
                    bucket.write_bytecode(f)

    A more advanced version of a filesystem based bytecode cache is part of
    Jinja.
    N)Úbucketr	cCs
tƒ‚dS)z¹Subclasses have to override this method to load bytecode into a
        bucket.  If they are not able to find code in the cache for the
        bucket, it must not do anything.
        N)ÚNotImplementedError)rr8r
r
rr-‚szBytecodeCache.load_bytecodecCs
tƒ‚dS)zÀSubclasses have to override this method to write the bytecode
        from a bucket back to the cache.  If it unable to do so it must not
        fail silently but raise an exception.
        N)r9)rr8r
r
rÚ
dump_bytecode‰szBytecodeCache.dump_bytecode)r	cCsdS)zºClears the cache.  This method is not used by Jinja but should be
        implemented to allow applications to clear the bytecode cache used
        by a particular environment.
        Nr
)rr
r
rÚclearszBytecodeCache.clear)ÚnameÚfilenamer	cCs2t|jdƒƒ}|dk	r*|jd|›jƒƒ|jƒS)z3Returns the unique hash key for this template name.zutf-8Nú|)rÚencodeÚupdateÚ	hexdigest)rr<r=Úhashr
r
rÚ
get_cache_key–szBytecodeCache.get_cache_key)Úsourcer	cCst|jdƒƒjƒS)z"Returns a checksum for the source.zutf-8)rr?rA)rrDr
r
rÚget_source_checksum¡sz!BytecodeCache.get_source_checksumr)rr<r=rDr	cCs0|j||ƒ}|j|ƒ}t|||ƒ}|j|ƒ|S)zwReturn a cache bucket for the given template.  All arguments are
        mandatory but filename may be `None`.
        )rCrErr-)rrr<r=rDrrr8r
r
rÚ
get_bucket¥s



zBytecodeCache.get_bucketcCs|j|ƒdS)zPut the bucket into the cache.N)r:)rr8r
r
rÚ
set_bucketµszBytecodeCache.set_bucket)N)rrrr6rr-r:r;rrrÚUnionrCrErFrGr
r
r
rr7es	
r7c@sveZdZdZdejeeddœdd„Zedœdd	„Ze	ed
œdd„Z
e	dd
œd
d„Ze	dd
œdd„Zddœdd„Z
dS)ÚFileSystemBytecodeCacheaïA bytecode cache that stores bytecode on the filesystem.  It accepts
    two arguments: The directory where the cache items are stored and a
    pattern string that is used to build the filename.

    If no directory is specified a default cache directory is selected.  On
    Windows the user's temp directory is used, on UNIX systems a directory
    is created for the user in the system temp directory.

    The pattern can be used to have multiple separate caches operate on the
    same directory.  The default pattern is ``'__jinja2_%s.cache'``.  ``%s``
    is replaced with the cache key.

    >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')

    This bytecode cache supports clearing of the cache using the clear method.
    Nú__jinja2_%s.cache)Ú	directoryÚpatternr	cCs |dkr|jƒ}||_||_dS)N)Ú_get_default_cache_dirrKrL)rrKrLr
r
rr Ìsz FileSystemBytecodeCache.__init__)r	cCsbddœdd„}tjƒ}tjdkr$|Sttdƒs4|ƒdtjƒ›}tjj||ƒ}ytj|t	j
ƒWn0tk
r’}z|jtj
kr‚‚WYdd}~XnXyPtj|t	j
ƒtj|ƒ}|jtjƒksÜt	j|jƒsÜt	j|jƒt	j
krâ|ƒWn4tk
r}z|jtj
kr‚WYdd}~XnXtj|ƒ}|jtjƒksXt	j|jƒsXt	j|jƒt	j
kr^|ƒ|S)Nzte.NoReturn)r	cSstdƒ‚dS)NzJCannot determine safe temp directory.  You need to explicitly provide one.)ÚRuntimeErrorr
r
r
rÚ_unsafe_dirÕszCFileSystemBytecodeCache._get_default_cache_dir.<locals>._unsafe_dirÚntÚgetuidz_jinja2-cache-)ÚtempfileÚ
gettempdirÚosr<ÚhasattrrQÚpathÚjoinÚmkdirÚstatÚS_IRWXUÚOSErrorÚerrnoÚEEXISTÚchmodÚlstatÚst_uidÚS_ISDIRÚst_modeÚS_IMODE)rrOZtmpdirÚdirnameZ
actual_dirÚeZactual_dir_statr
r
rrMÔs:




z.FileSystemBytecodeCache._get_default_cache_dir)r8r	cCstjj|j|j|jfƒS)N)rTrVrWrKrLr)rr8r
r
rÚ_get_cache_filenamesz+FileSystemBytecodeCache._get_cache_filenamec	Cs:|j|ƒ}tjj|ƒr6t|dƒ}|j|ƒWdQRXdS)NÚrb)rfrTrVÚexistsÚopenr-)rr8r=r"r
r
rr-s
z%FileSystemBytecodeCache.load_bytecodec	Cs*t|j|ƒdƒ}|j|ƒWdQRXdS)NÚwb)rirfr0)rr8r"r
r
rr:
sz%FileSystemBytecodeCache.dump_bytecodecCsfddlm}tjtj|jƒ|jdƒ}x:|D]2}y|tjj|j|ƒƒWq,t	k
r\Yq,Xq,WdS)Nr)ÚremoveÚ*)rl)
rTrkÚfnmatchÚfilterÚlistdirrKrLrVrWr[)rrkÚfilesr=r
r
rr;s
zFileSystemBytecodeCache.clear)NrJ)rrrr6rrrr rMrrfr-r:r;r
r
r
rrIºs/rIc@sLeZdZdZddeejeedœdd„Z	e
dd	œd
d„Ze
dd	œdd
„ZdS)ÚMemcachedBytecodeCachea'This class implements a bytecode cache that uses a memcache cache for
    storing the information.  It does not enforce a specific memcache library
    (tummy's memcache or cmemcache) but will accept any class that provides
    the minimal interface required.

    Libraries compatible with this class:

    -   `cachelib <https://github.com/pallets/cachelib>`_
    -   `python-memcached <https://pypi.org/project/python-memcached/>`_

    (Unfortunately the django cache interface is not compatible because it
    does not support storing binary data, only text. You can however pass
    the underlying cache client to the bytecode cache which is available
    as `django.core.cache.cache._client`.)

    The minimal interface for the client passed to the constructor is this:

    .. class:: MinimalClientInterface

        .. method:: set(key, value[, timeout])

            Stores the bytecode in the cache.  `value` is a string and
            `timeout` the timeout of the key.  If timeout is not provided
            a default timeout or no timeout should be assumed, if it's
            provided it's an integer with the number of seconds the cache
            item should exist.

        .. method:: get(key)

            Returns the value for the cache key.  If the item does not
            exist in the cache the return value must be `None`.

    The other arguments to the constructor are the prefix for all keys that
    is added before the actual cache key and the timeout for the bytecode in
    the cache system.  We recommend a high (or no) timeout.

    This bytecode cache does not support clearing of used items in the cache.
    The clear method is a no-operation function.

    .. versionadded:: 2.7
       Added support for ignoring memcache errors through the
       `ignore_memcache_errors` parameter.
    újinja2/bytecode/NTr)ÚclientÚprefixrÚignore_memcache_errorscCs||_||_||_||_dS)N)rsrtrru)rrsrtrrur
r
rr LszMemcachedBytecodeCache.__init__)r8r	cCsDy|jj|j|jƒ}Wntk
r4|js0‚YnX|j|ƒdS)N)rsr
rtrÚ	Exceptionrur2)rr8r!r
r
rr-Xsz$MemcachedBytecodeCache.load_bytecodecCsf|j|j}|jƒ}y0|jdk	r4|jj|||jƒn|jj||ƒWntk
r`|js\‚YnXdS)N)rtrr5rrsrrvru)rr8rrr
r
rr:as
z$MemcachedBytecodeCache.dump_bytecode)rrNT)
rrrr6rrrrÚboolr rr-r:r
r
r
rrqs+	rq) r6r\rmr(rTr&rYÚsysrRÚtypingrÚhashlibrÚiorÚtypesrZ
TYPE_CHECKINGZtyping_extensionsÚterrZProtocolrZ
bc_versionÚdumpsÚversion_infor%rr7rIrqr
r
r
rÚ<module>s,09Ue