cache.py 2.3 KB

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