cache.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """HTTP cache implementation.
  2. """
  3. import os
  4. from contextlib import contextmanager
  5. from typing import Iterator, Optional
  6. from pip._vendor.cachecontrol.cache import BaseCache
  7. from pip._vendor.cachecontrol.caches import FileCache
  8. from pip._vendor.requests.models import Response
  9. from pip._internal.utils.filesystem import adjacent_tmp_file, replace
  10. from pip._internal.utils.misc import ensure_dir
  11. def is_from_cache(response):
  12. # type: (Response) -> bool
  13. return getattr(response, "from_cache", False)
  14. @contextmanager
  15. def suppressed_cache_errors():
  16. # type: () -> Iterator[None]
  17. """If we can't access the cache then we can just skip caching and process
  18. requests as if caching wasn't enabled.
  19. """
  20. try:
  21. yield
  22. except OSError:
  23. pass
  24. class SafeFileCache(BaseCache):
  25. """
  26. A file based cache which is safe to use even when the target directory may
  27. not be accessible or writable.
  28. """
  29. def __init__(self, directory):
  30. # type: (str) -> None
  31. assert directory is not None, "Cache directory must not be None."
  32. super().__init__()
  33. self.directory = directory
  34. def _get_cache_path(self, name):
  35. # type: (str) -> str
  36. # From cachecontrol.caches.file_cache.FileCache._fn, brought into our
  37. # class for backwards-compatibility and to avoid using a non-public
  38. # method.
  39. hashed = FileCache.encode(name)
  40. parts = list(hashed[:5]) + [hashed]
  41. return os.path.join(self.directory, *parts)
  42. def get(self, key):
  43. # type: (str) -> Optional[bytes]
  44. path = self._get_cache_path(key)
  45. with suppressed_cache_errors():
  46. with open(path, 'rb') as f:
  47. return f.read()
  48. def set(self, key, value):
  49. # type: (str, bytes) -> None
  50. path = self._get_cache_path(key)
  51. with suppressed_cache_errors():
  52. ensure_dir(os.path.dirname(path))
  53. with adjacent_tmp_file(path) as f:
  54. f.write(value)
  55. replace(f.name, path)
  56. def delete(self, key):
  57. # type: (str) -> None
  58. path = self._get_cache_path(key)
  59. with suppressed_cache_errors():
  60. os.remove(path)