Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than c580dd0 point at it.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1–7why, one step back
1"""The optional bytecode cache system. This is useful if you have very
2complex 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"""

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 8why, one step back
8

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 9–16why, one step back
9import errno
10import fnmatch11import marshal12import os13import pickle14import stat15import sys16import tempfile

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 17why, one step back
17import typing as t

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 18–19why, one step back
18from hashlib import sha1
19from io import BytesIO

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 20why, one step back
20from types import CodeType

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 21why, one step back
21

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 22–23why, one step back
22if t.TYPE_CHECKING:
23 import typing_extensions as te

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 24why, one step back
24

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 25why, one step back
25 from .environment import Environment

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 26why, one step back
26

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 27why, one step back
27 class _MemcachedClient(te.Protocol):

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 28why, one step back
28 def get(self, key: str) -> bytes: ...

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 29why, one step back
29

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 30why, one step back
30 def set(self, key: str, value: bytes, timeout: int | None = None) -> None: ...

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 31–32why, one step back
31
32

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 33–52why, one step back
33bc_version = 5
34# 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 """52

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 53why, one step back
53 def __init__(self, environment: "Environment", key: str, checksum: str) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 54–58why, one step back
54 self.environment = environment
55 self.key = key56 self.checksum = checksum57 self.reset()58

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 59why, one step back
59 def reset(self) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 60why, one step back
60 """Resets the bucket (unloads the bytecode)."""

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 61why, one step back
61 self.code: CodeType | None = None

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 62why, one step back
62

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 63why, one step back
63 def load_bytecode(self, f: t.BinaryIO) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 64–81why, one step back
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 return81

Merge branch '3.1.x'David Lordbefore adoption52843b5

line 82why, one step back
82 def write_bytecode(self, f: t.IO[bytes]) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 83–89why, one step back
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)89

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 90–91why, one step back
90 def bytecode_from_string(self, string: bytes) -> None:
91 """Load bytecode from bytes."""

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 92–93why, one step back
92 self.load_bytecode(BytesIO(string))
93

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 94–95why, one step back
94 def bytecode_to_string(self) -> bytes:
95 """Return the bytecode as bytes."""

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 96–129why, one step back
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 """129

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 130why, one step back
130 def load_bytecode(self, bucket: Bucket) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 131–136why, one step back
131 """Subclasses have to override this method to load bytecode into a
132 bucket. If they are not able to find code in the cache for the133 bucket, it must not do anything.134 """135 raise NotImplementedError()136

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 137why, one step back
137 def dump_bytecode(self, bucket: Bucket) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 138–143why, one step back
138 """Subclasses have to override this method to write the bytecode
139 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()143

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 144why, one step back
144 def clear(self) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 145–149why, one step back
145 """Clears the cache. This method is not used by Jinja but should be
146 implemented to allow applications to clear the bytecode cache used147 by a particular environment.148 """149

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 150why, one step back
150 def get_cache_key(self, name: str, filename: str | None = None) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 151–152why, one step back
151 """Returns the unique hash key for this template name."""
152 hash = sha1(name.encode("utf-8"))

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 153why, one step back
153

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 154why, one step back
154 if filename is not None:

Merge pull request #1480 from pallets/pre-commit-ci-update-configDavid Lordbefore adoption44f3d21

line 155why, one step back
155 hash.update(f"|{filename}".encode())

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 156why, one step back
156

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 157–158why, one step back
157 return hash.hexdigest()
158

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 159why, one step back
159 def get_source_checksum(self, source: str) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 160–162why, one step back
160 """Returns a checksum for the source."""
161 return sha1(source.encode("utf-8")).hexdigest()162

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 163–166why, one step back
163 def get_bucket(
164 self,165 environment: "Environment",166 name: str,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 167why, one step back
167 filename: str | None,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 168–169why, one step back
168 source: str,
169 ) -> Bucket:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 170–178why, one step back
170 """Return a cache bucket for the given template. All arguments are
171 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 bucket178

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 179why, one step back
179 def set_bucket(self, bucket: Bucket) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 180–201why, one step back
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 """201

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 202why, one step back
202 def __init__(

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 203why, one step back
203 self, directory: str | None = None, pattern: str = "__jinja2_%s.cache"

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 204why, one step back
204 ) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 205–209why, one step back
205 if directory is None:
206 directory = self._get_default_cache_dir()207 self.directory = directory208 self.pattern = pattern209

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 210why, one step back
210 def _get_default_cache_dir(self) -> str:

Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0

line 211why, one step back
211 def _unsafe_dir() -> "te.NoReturn":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 212–256why, one step back
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_dir256

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 257why, one step back
257 def _get_cache_filename(self, bucket: Bucket) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 258–259why, one step back
258 return os.path.join(self.directory, self.pattern % (bucket.key,))
259

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 260–262why, one step back
260 def load_bytecode(self, bucket: Bucket) -> None:
261 filename = self._get_cache_filename(bucket)262

Merge branch '3.1.x'David Lordbefore adoption52843b5

lines 263–270why, one step back
263 # Don't test for existence before opening the file, since the
264 # 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 return

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 271why, one step back
271

Merge branch '3.1.x'David Lordbefore adoption52843b5

lines 272–274why, one step back
272 with f:
273 bucket.load_bytecode(f)274

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 275why, one step back
275 def dump_bytecode(self, bucket: Bucket) -> None:

Merge branch '3.1.x'David Lordbefore adoption52843b5

lines 276–311why, one step back
276 # Write to a temporary file, then rename to the real name after
277 # 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 raise

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 312why, one step back
312

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 313why, one step back
313 def clear(self) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 314–373why, one step back
314 # imported lazily here because google app-engine doesn't support
315 # 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,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 374–375why, one step back
374 client: "_MemcachedClient",
375 prefix: str = "jinja2/bytecode/",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 376why, one step back
376 timeout: int | None = None,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 377why, one step back
377 ignore_memcache_errors: bool = True,

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 378–383why, one step back
378 ):
379 self.client = client380 self.prefix = prefix381 self.timeout = timeout382 self.ignore_memcache_errors = ignore_memcache_errors383

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 384why, one step back
384 def load_bytecode(self, bucket: Bucket) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 385–389why, one step back
385 try:
386 code = self.client.get(self.prefix + bucket.key)387 except Exception:388 if not self.ignore_memcache_errors:389 raise

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 390why, one step back
390 else:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 391–392why, one step back
391 bucket.bytecode_from_string(code)
392

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 393–396why, one step back
393 def dump_bytecode(self, bucket: Bucket) -> None:
394 key = self.prefix + bucket.key395 value = bucket.bytecode_to_string()396

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 397why, one step back
397 try:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 398–401why, one step back
398 if self.timeout is not None:
399 self.client.set(key, value, self.timeout)400 else:401 self.client.set(key, value)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 402–404why, one step back
402 except Exception:
403 if not self.ignore_memcache_errors:404 raise