MCPcopy Create free account
hub / github.com/psf/cachecontrol / _FileCacheMixin

Class _FileCacheMixin

cachecontrol/caches/file_cache.py:22–104  ·  view source on GitHub ↗

Shared implementation for both FileCache variants.

Source from the content-addressed store, hash-verified

20
21
22class _FileCacheMixin:
23 """Shared implementation for both FileCache variants."""
24
25 def __init__(
26 self,
27 directory: str | Path,
28 forever: bool = False,
29 filemode: int = 0o0600,
30 dirmode: int = 0o0700,
31 lock_class: type[BaseFileLock] | None = None,
32 ) -> None:
33 try:
34 if lock_class is None:
35 from filelock import FileLock
36
37 lock_class = FileLock
38 except ImportError:
39 notice = dedent(
40 """
41 NOTE: In order to use the FileCache you must have
42 filelock installed. You can install it via pip:
43 pip install cachecontrol[filecache]
44 """
45 )
46 raise ImportError(notice)
47
48 self.directory = directory
49 self.forever = forever
50 self.filemode = filemode
51 self.dirmode = dirmode
52 self.lock_class = lock_class
53
54 @staticmethod
55 def encode(x: str) -> str:
56 return hashlib.sha224(x.encode()).hexdigest()
57
58 def _fn(self, name: str) -> str:
59 # NOTE: This method should not change as some may depend on it.
60 # See: https://github.com/ionrock/cachecontrol/issues/63
61 hashed = self.encode(name)
62 parts = list(hashed[:5]) + [hashed]
63 return os.path.join(self.directory, *parts)
64
65 def get(self, key: str) -> bytes | None:
66 name = self._fn(key)
67 try:
68 with open(name, "rb") as fh:
69 return fh.read()
70
71 except FileNotFoundError:
72 return None
73
74 def set(
75 self, key: str, value: bytes, expires: int | datetime | None = None
76 ) -> None:
77 name = self._fn(key)
78 self._write(name, value)
79

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…