uwsgi.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import platform
  2. import typing as _t
  3. from cachelib.base import BaseCache
  4. from cachelib.serializers import UWSGISerializer
  5. class UWSGICache(BaseCache):
  6. """Implements the cache using uWSGI's caching framework.
  7. .. note::
  8. This class cannot be used when running under PyPy, because the uWSGI
  9. API implementation for PyPy is lacking the needed functionality.
  10. :param default_timeout: The default timeout in seconds.
  11. :param cache: The name of the caching instance to connect to, for
  12. example: mycache@localhost:3031, defaults to an empty string, which
  13. means uWSGI will cache in the local instance. If the cache is in the
  14. same instance as the werkzeug app, you only have to provide the name of
  15. the cache.
  16. """
  17. serializer = UWSGISerializer()
  18. def __init__(
  19. self,
  20. default_timeout: int = 300,
  21. cache: str = "",
  22. ):
  23. BaseCache.__init__(self, default_timeout)
  24. if platform.python_implementation() == "PyPy":
  25. raise RuntimeError(
  26. "uWSGI caching does not work under PyPy, see "
  27. "the docs for more details."
  28. )
  29. try:
  30. import uwsgi # type: ignore
  31. self._uwsgi = uwsgi
  32. except ImportError as err:
  33. raise RuntimeError(
  34. "uWSGI could not be imported, are you running under uWSGI?"
  35. ) from err
  36. self.cache = cache
  37. def get(self, key: str) -> _t.Any:
  38. rv = self._uwsgi.cache_get(key, self.cache)
  39. if rv is None:
  40. return
  41. return self.serializer.loads(rv)
  42. def delete(self, key: str) -> bool:
  43. return bool(self._uwsgi.cache_del(key, self.cache))
  44. def set(
  45. self, key: str, value: _t.Any, timeout: _t.Optional[int] = None
  46. ) -> _t.Optional[bool]:
  47. result = self._uwsgi.cache_update(
  48. key,
  49. self.serializer.dumps(value),
  50. self._normalize_timeout(timeout),
  51. self.cache,
  52. ) # type: bool
  53. return result
  54. def add(self, key: str, value: _t.Any, timeout: _t.Optional[int] = None) -> bool:
  55. return bool(
  56. self._uwsgi.cache_set(
  57. key,
  58. self.serializer.dumps(value),
  59. self._normalize_timeout(timeout),
  60. self.cache,
  61. )
  62. )
  63. def clear(self) -> bool:
  64. return bool(self._uwsgi.cache_clear(self.cache))
  65. def has(self, key: str) -> bool:
  66. return self._uwsgi.cache_exists(key, self.cache) is not None