Shared implementation for both FileCache variants.
| 20 | |
| 21 | |
| 22 | class _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 |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…