uwsgicache.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """
  2. flask_caching.backends.uwsgicache
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. The uWSGI 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. from cachelib import UWSGICache as CachelibUWSGICache
  10. from flask_caching.backends.base import BaseCache
  11. class UWSGICache(BaseCache, CachelibUWSGICache):
  12. """Implements the cache using uWSGI's caching framework.
  13. .. note::
  14. This class cannot be used when running under PyPy, because the uWSGI
  15. API implementation for PyPy is lacking the needed functionality.
  16. :param default_timeout: The default timeout in seconds.
  17. :param cache: The name of the caching instance to connect to, for
  18. example: mycache@localhost:3031, defaults to an empty string, which
  19. means uWSGI will use the first cache instance initialized.
  20. If the cache is in the same instance as the werkzeug app,
  21. you only have to provide the name of the cache.
  22. """
  23. def __init__(self, default_timeout=300, cache=""):
  24. BaseCache.__init__(self, default_timeout=default_timeout)
  25. CachelibUWSGICache.__init__(
  26. self,
  27. cache=cache,
  28. default_timeout=default_timeout,
  29. )
  30. try:
  31. import uwsgi
  32. self._uwsgi = uwsgi
  33. except ImportError as e:
  34. raise RuntimeError(
  35. "uWSGI could not be imported, are you running under uWSGI?"
  36. ) from e
  37. if "cache2" not in uwsgi.opt:
  38. raise RuntimeError(
  39. "You must enable cache2 in uWSGI configuration: "
  40. "https://uwsgi-docs.readthedocs.io/en/latest/Caching.html"
  41. )
  42. @classmethod
  43. def factory(cls, app, config, args, kwargs):
  44. # The name of the caching instance to connect to, for
  45. # example: mycache@localhost:3031, defaults to an empty string, which
  46. # means uWSGI will cache in the local instance. If the cache is in the
  47. # same instance as the werkzeug app, you only have to provide the name
  48. # of the cache.
  49. uwsgi_cache_name = config.get("CACHE_UWSGI_NAME", "")
  50. kwargs.update(dict(cache=uwsgi_cache_name))
  51. return cls(*args, **kwargs)