filesystemcache.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """
  2. flask_caching.backends.filesystem
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. The filesystem caching backend.
  5. :copyright: (c) 2018 by Peter Justin.
  6. :copyright: (c) 2010 by Thadeus Burgess.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import hashlib
  10. import logging
  11. from cachelib import FileSystemCache as CachelibFileSystemCache
  12. from flask_caching.backends.base import BaseCache
  13. logger = logging.getLogger(__name__)
  14. class FileSystemCache(BaseCache, CachelibFileSystemCache):
  15. """A cache that stores the items on the file system. This cache depends
  16. on being the only user of the `cache_dir`. Make absolutely sure that
  17. nobody but this cache stores files there or otherwise the cache will
  18. randomly delete files therein.
  19. :param cache_dir: the directory where cache files are stored.
  20. :param threshold: the maximum number of items the cache stores before
  21. it starts deleting some. A threshold value of 0
  22. indicates no threshold.
  23. :param default_timeout: the default timeout that is used if no timeout is
  24. specified on :meth:`~BaseCache.set`. A timeout of
  25. 0 indicates that the cache never expires.
  26. :param mode: the file mode wanted for the cache files, default 0600
  27. :param hash_method: Default hashlib.md5. The hash method used to
  28. generate the filename for cached results.
  29. :param ignore_errors: If set to ``True`` the :meth:`~BaseCache.delete_many`
  30. method will ignore any errors that occurred during the
  31. deletion process. However, if it is set to ``False``
  32. it will stop on the first error. Defaults to
  33. ``False``.
  34. """
  35. def __init__(
  36. self,
  37. cache_dir,
  38. threshold=500,
  39. default_timeout=300,
  40. mode=0o600,
  41. hash_method=hashlib.md5,
  42. ignore_errors=False,
  43. ):
  44. BaseCache.__init__(self, default_timeout=default_timeout)
  45. CachelibFileSystemCache.__init__(
  46. self,
  47. cache_dir=cache_dir,
  48. threshold=threshold,
  49. default_timeout=default_timeout,
  50. mode=mode,
  51. hash_method=hash_method,
  52. )
  53. self.ignore_errors = ignore_errors
  54. @classmethod
  55. def factory(cls, app, config, args, kwargs):
  56. args.insert(0, config["CACHE_DIR"])
  57. kwargs.update(
  58. dict(
  59. threshold=config["CACHE_THRESHOLD"],
  60. ignore_errors=config["CACHE_IGNORE_ERRORS"],
  61. )
  62. )
  63. return cls(*args, **kwargs)