bccache.py
This file
Path
src/jinja2/bccache.py
404 lines · 13.7 KiB · Python
Last changed by
drop end of life python versions (#2096)David Lordbefore adoption49c48a0
History of this fileTake it
1"""The optional bytecode cache system. This is useful if you have very2complex template situations and the compilation of all those templates3slows down your application too much.45Situations where this is useful are often forking web applications that6are initialized on the first request.7"""89import errno10import fnmatch11import marshal12import os13import pickle14import stat15import sys16import tempfile17import typing as t18from hashlib import sha119from io import BytesIO20from types import CodeType2122if t.TYPE_CHECKING:23 import typing_extensions as te2425 from .environment import Environment2627 class _MemcachedClient(te.Protocol):28 def get(self, key: str) -> bytes: ...2930 def set(self, key: str, value: bytes, timeout: int | None = None) -> None: ...313233bc_version = 534# Magic bytes to identify Jinja bytecode cache files. Contains the35# Python major and minor version to avoid loading incompatible bytecode36# if a project upgrades its Python version.37bc_magic = (38 b"j2"39 + pickle.dumps(bc_version, 2)40 + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2)41)424344class Bucket:45 """Buckets are used to store the bytecode for one template. It's created46 and initialized by the bytecode cache and passed to the loading functions.4748 The buckets get an internal checksum from the cache assigned and use this49 to automatically reject outdated cache material. Individual bytecode50 cache subclasses don't have to care about cache invalidation.51 """5253 def __init__(self, environment: "Environment", key: str, checksum: str) -> None:54 self.environment = environment55 self.key = key56 self.checksum = checksum57 self.reset()5859 def reset(self) -> None:60 """Resets the bucket (unloads the bytecode)."""61 self.code: CodeType | None = None6263 def load_bytecode(self, f: t.BinaryIO) -> None:64 """Loads bytecode from a file or file like object."""65 # make sure the magic header is correct66 magic = f.read(len(bc_magic))67 if magic != bc_magic:68 self.reset()69 return70 # the source code of the file changed, we need to reload71 checksum = pickle.load(f)72 if self.checksum != checksum:73 self.reset()74 return75 # if marshal_load fails then we need to reload76 try:77 self.code = marshal.load(f)78 except (EOFError, ValueError, TypeError):79 self.reset()80 return8182 def write_bytecode(self, f: t.IO[bytes]) -> None:83 """Dump the bytecode into the file or file like object passed."""84 if self.code is None:85 raise TypeError("can't write empty bucket")86 f.write(bc_magic)87 pickle.dump(self.checksum, f, 2)88 marshal.dump(self.code, f)8990 def bytecode_from_string(self, string: bytes) -> None:91 """Load bytecode from bytes."""92 self.load_bytecode(BytesIO(string))9394 def bytecode_to_string(self) -> bytes:95 """Return the bytecode as bytes."""96 out = BytesIO()97 self.write_bytecode(out)98 return out.getvalue()99100101class BytecodeCache:102 """To implement your own bytecode cache you have to subclass this class103 and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of104 these methods are passed a :class:`~jinja2.bccache.Bucket`.105106 A very basic bytecode cache that saves the bytecode on the file system::107108 from os import path109110 class MyCache(BytecodeCache):111112 def __init__(self, directory):113 self.directory = directory114115 def load_bytecode(self, bucket):116 filename = path.join(self.directory, bucket.key)117 if path.exists(filename):118 with open(filename, 'rb') as f:119 bucket.load_bytecode(f)120121 def dump_bytecode(self, bucket):122 filename = path.join(self.directory, bucket.key)123 with open(filename, 'wb') as f:124 bucket.write_bytecode(f)125126 A more advanced version of a filesystem based bytecode cache is part of127 Jinja.128 """129130 def load_bytecode(self, bucket: Bucket) -> None:131 """Subclasses have to override this method to load bytecode into a132 bucket. If they are not able to find code in the cache for the133 bucket, it must not do anything.134 """135 raise NotImplementedError()136137 def dump_bytecode(self, bucket: Bucket) -> None:138 """Subclasses have to override this method to write the bytecode139 from a bucket back to the cache. If it unable to do so it must not140 fail silently but raise an exception.141 """142 raise NotImplementedError()143144 def clear(self) -> None:145 """Clears the cache. This method is not used by Jinja but should be146 implemented to allow applications to clear the bytecode cache used147 by a particular environment.148 """149150 def get_cache_key(self, name: str, filename: str | None = None) -> str:151 """Returns the unique hash key for this template name."""152 hash = sha1(name.encode("utf-8"))153154 if filename is not None:155 hash.update(f"|{filename}".encode())156157 return hash.hexdigest()158159 def get_source_checksum(self, source: str) -> str:160 """Returns a checksum for the source."""161 return sha1(source.encode("utf-8")).hexdigest()162163 def get_bucket(164 self,165 environment: "Environment",166 name: str,167 filename: str | None,168 source: str,169 ) -> Bucket:170 """Return a cache bucket for the given template. All arguments are171 mandatory but filename may be `None`.172 """173 key = self.get_cache_key(name, filename)174 checksum = self.get_source_checksum(source)175 bucket = Bucket(environment, key, checksum)176 self.load_bytecode(bucket)177 return bucket178179 def set_bucket(self, bucket: Bucket) -> None:180 """Put the bucket into the cache."""181 self.dump_bytecode(bucket)182183184class FileSystemBytecodeCache(BytecodeCache):185 """A bytecode cache that stores bytecode on the filesystem. It accepts186 two arguments: The directory where the cache items are stored and a187 pattern string that is used to build the filename.188189 If no directory is specified a default cache directory is selected. On190 Windows the user's temp directory is used, on UNIX systems a directory191 is created for the user in the system temp directory.192193 The pattern can be used to have multiple separate caches operate on the194 same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``195 is replaced with the cache key.196197 >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')198199 This bytecode cache supports clearing of the cache using the clear method.200 """201202 def __init__(203 self, directory: str | None = None, pattern: str = "__jinja2_%s.cache"204 ) -> None:205 if directory is None:206 directory = self._get_default_cache_dir()207 self.directory = directory208 self.pattern = pattern209210 def _get_default_cache_dir(self) -> str:211 def _unsafe_dir() -> "te.NoReturn":212 raise RuntimeError(213 "Cannot determine safe temp directory. You "214 "need to explicitly provide one."215 )216217 tmpdir = tempfile.gettempdir()218219 # On windows the temporary directory is used specific unless220 # explicitly forced otherwise. We can just use that.221 if os.name == "nt":222 return tmpdir223 if not hasattr(os, "getuid"):224 _unsafe_dir()225226 dirname = f"_jinja2-cache-{os.getuid()}"227 actual_dir = os.path.join(tmpdir, dirname)228229 try:230 os.mkdir(actual_dir, stat.S_IRWXU)231 except OSError as e:232 if e.errno != errno.EEXIST:233 raise234 try:235 os.chmod(actual_dir, stat.S_IRWXU)236 actual_dir_stat = os.lstat(actual_dir)237 if (238 actual_dir_stat.st_uid != os.getuid()239 or not stat.S_ISDIR(actual_dir_stat.st_mode)240 or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU241 ):242 _unsafe_dir()243 except OSError as e:244 if e.errno != errno.EEXIST:245 raise246247 actual_dir_stat = os.lstat(actual_dir)248 if (249 actual_dir_stat.st_uid != os.getuid()250 or not stat.S_ISDIR(actual_dir_stat.st_mode)251 or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU252 ):253 _unsafe_dir()254255 return actual_dir256257 def _get_cache_filename(self, bucket: Bucket) -> str:258 return os.path.join(self.directory, self.pattern % (bucket.key,))259260 def load_bytecode(self, bucket: Bucket) -> None:261 filename = self._get_cache_filename(bucket)262263 # Don't test for existence before opening the file, since the264 # file could disappear after the test before the open.265 try:266 f = open(filename, "rb")267 except (FileNotFoundError, IsADirectoryError, PermissionError):268 # PermissionError can occur on Windows when an operation is269 # in progress, such as calling clear().270 return271272 with f:273 bucket.load_bytecode(f)274275 def dump_bytecode(self, bucket: Bucket) -> None:276 # Write to a temporary file, then rename to the real name after277 # writing. This avoids another process reading the file before278 # it is fully written.279 name = self._get_cache_filename(bucket)280 f = tempfile.NamedTemporaryFile(281 mode="wb",282 dir=os.path.dirname(name),283 prefix=os.path.basename(name),284 suffix=".tmp",285 delete=False,286 )287288 def remove_silent() -> None:289 try:290 os.remove(f.name)291 except OSError:292 # Another process may have called clear(). On Windows,293 # another program may be holding the file open.294 pass295296 try:297 with f:298 bucket.write_bytecode(f)299 except BaseException:300 remove_silent()301 raise302303 try:304 os.replace(f.name, name)305 except OSError:306 # Another process may have called clear(). On Windows,307 # another program may be holding the file open.308 remove_silent()309 except BaseException:310 remove_silent()311 raise312313 def clear(self) -> None:314 # imported lazily here because google app-engine doesn't support315 # write access on the file system and the function does not exist316 # normally.317 from os import remove318319 files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",))320 for filename in files:321 try:322 remove(os.path.join(self.directory, filename))323 except OSError:324 pass325326327class MemcachedBytecodeCache(BytecodeCache):328 """This class implements a bytecode cache that uses a memcache cache for329 storing the information. It does not enforce a specific memcache library330 (tummy's memcache or cmemcache) but will accept any class that provides331 the minimal interface required.332333 Libraries compatible with this class:334335 - `cachelib <https://github.com/pallets/cachelib>`_336 - `python-memcached <https://pypi.org/project/python-memcached/>`_337338 (Unfortunately the django cache interface is not compatible because it339 does not support storing binary data, only text. You can however pass340 the underlying cache client to the bytecode cache which is available341 as `django.core.cache.cache._client`.)342343 The minimal interface for the client passed to the constructor is this:344345 .. class:: MinimalClientInterface346347 .. method:: set(key, value[, timeout])348349 Stores the bytecode in the cache. `value` is a string and350 `timeout` the timeout of the key. If timeout is not provided351 a default timeout or no timeout should be assumed, if it's352 provided it's an integer with the number of seconds the cache353 item should exist.354355 .. method:: get(key)356357 Returns the value for the cache key. If the item does not358 exist in the cache the return value must be `None`.359360 The other arguments to the constructor are the prefix for all keys that361 is added before the actual cache key and the timeout for the bytecode in362 the cache system. We recommend a high (or no) timeout.363364 This bytecode cache does not support clearing of used items in the cache.365 The clear method is a no-operation function.366367 .. versionadded:: 2.7368 Added support for ignoring memcache errors through the369 `ignore_memcache_errors` parameter.370 """371372 def __init__(373 self,374 client: "_MemcachedClient",375 prefix: str = "jinja2/bytecode/",376 timeout: int | None = None,377 ignore_memcache_errors: bool = True,378 ):379 self.client = client380 self.prefix = prefix381 self.timeout = timeout382 self.ignore_memcache_errors = ignore_memcache_errors383384 def load_bytecode(self, bucket: Bucket) -> None:385 try:386 code = self.client.get(self.prefix + bucket.key)387 except Exception:388 if not self.ignore_memcache_errors:389 raise390 else:391 bucket.bytecode_from_string(code)392393 def dump_bytecode(self, bucket: Bucket) -> None:394 key = self.prefix + bucket.key395 value = bucket.bytecode_to_string()396397 try:398 if self.timeout is not None:399 self.client.set(key, value, self.timeout)400 else:401 self.client.set(key, value)402 except Exception:403 if not self.ignore_memcache_errors:404 raise