simplecache.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """
  2. flask_caching.backends.simple
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. The simple cache 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 logging
  10. from cachelib import SimpleCache as CachelibSimpleCache
  11. from flask_caching.backends.base import BaseCache
  12. logger = logging.getLogger(__name__)
  13. class SimpleCache(BaseCache, CachelibSimpleCache):
  14. """Simple memory cache for single process environments. This class exists
  15. mainly for the development server and is not 100% thread safe. It tries
  16. to use as many atomic operations as possible and no locks for simplicity
  17. but it could happen under heavy load that keys are added multiple times.
  18. :param threshold: the maximum number of items the cache stores before
  19. it starts deleting some.
  20. :param default_timeout: the default timeout that is used if no timeout is
  21. specified on :meth:`~BaseCache.set`. A timeout of
  22. 0 indicates that the cache never expires.
  23. :param ignore_errors: If set to ``True`` the :meth:`~BaseCache.delete_many`
  24. method will ignore any errors that occurred during
  25. the deletion process. However, if it is set to
  26. ``False`` it will stop on the first error. Defaults
  27. to ``False``.
  28. """
  29. def __init__(self, threshold=500, default_timeout=300, ignore_errors=False):
  30. BaseCache.__init__(self, default_timeout=default_timeout)
  31. CachelibSimpleCache.__init__(
  32. self, threshold=threshold, default_timeout=default_timeout
  33. )
  34. self.ignore_errors = ignore_errors
  35. @classmethod
  36. def factory(cls, app, config, args, kwargs):
  37. kwargs.update(
  38. dict(
  39. threshold=config["CACHE_THRESHOLD"],
  40. ignore_errors=config["CACHE_IGNORE_ERRORS"],
  41. )
  42. )
  43. return cls(*args, **kwargs)