tyrant.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """celery.backends.tyrant"""
  2. from __future__ import absolute_import
  3. try:
  4. import pytyrant
  5. except ImportError:
  6. pytyrant = None # noqa
  7. from ..exceptions import ImproperlyConfigured
  8. from .base import KeyValueStoreBackend
  9. class TyrantBackend(KeyValueStoreBackend):
  10. """Tokyo Cabinet based task backend store.
  11. .. attribute:: tyrant_host
  12. The hostname to the Tokyo Tyrant server.
  13. .. attribute:: tyrant_port
  14. The port to the Tokyo Tyrant server.
  15. """
  16. tyrant_host = None
  17. tyrant_port = None
  18. def __init__(self, tyrant_host=None, tyrant_port=None, **kwargs):
  19. """Initialize Tokyo Tyrant backend instance.
  20. Raises :class:`celery.exceptions.ImproperlyConfigured` if
  21. :setting:`TT_HOST` or :setting:`TT_PORT` is not set.
  22. """
  23. super(TyrantBackend, self).__init__(**kwargs)
  24. if not pytyrant:
  25. raise ImproperlyConfigured(
  26. "You need to install the pytyrant library to use the "
  27. + "Tokyo Tyrant backend.")
  28. self.tyrant_host = (tyrant_host or
  29. self.app.conf.get("TT_HOST") or
  30. self.tyrant_host)
  31. self.tyrant_port = (tyrant_port or
  32. self.app.conf.get("TT_PORT") or
  33. self.tyrant_port)
  34. if self.tyrant_port:
  35. self.tyrant_port = int(self.tyrant_port)
  36. if not self.tyrant_host or not self.tyrant_port:
  37. raise ImproperlyConfigured(
  38. "To use the Tokyo Tyrant backend, you have to "
  39. "set the TT_HOST and TT_PORT settings in your settings.py")
  40. self._connection = None
  41. def open(self):
  42. """Get :class:`pytyrant.PyTyrant` instance with the current
  43. server configuration.
  44. The connection is then cached until you do an
  45. explicit :meth:`close`.
  46. """
  47. # connection overrides bool()
  48. if self._connection is None:
  49. self._connection = pytyrant.PyTyrant.open(self.tyrant_host,
  50. self.tyrant_port)
  51. return self._connection
  52. def close(self):
  53. """Close the tyrant connection and remove the cache."""
  54. # connection overrides bool()
  55. if self._connection is not None:
  56. self._connection.close()
  57. self._connection = None
  58. def process_cleanup(self):
  59. self.close()
  60. def get(self, key):
  61. return self.open().get(key)
  62. def set(self, key, value):
  63. self.open()[key] = value
  64. def delete(self, key):
  65. self.open().pop(key, None)
  66. def __reduce__(self, args=(), kwargs={}):
  67. kwargs.update(
  68. dict(tyrant_host=self.tyrant_host,
  69. tyrant_port=self.tyrant_port))
  70. return super(TyrantBackend, self).__reduce__(args, kwargs)