tyrant.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """celery.backends.tyrant"""
  2. from django.core.exceptions import ImproperlyConfigured
  3. try:
  4. import pytyrant
  5. except ImportError:
  6. raise ImproperlyConfigured(
  7. "The Tokyo Tyrant backend requires the pytyrant library.")
  8. from celery.backends.base import KeyValueStoreBackend
  9. from django.conf import settings
  10. class Backend(KeyValueStoreBackend):
  11. """Tokyo Cabinet based task backend store.
  12. .. attribute:: tyrant_host
  13. The hostname to the Tokyo Tyrant server.
  14. .. attribute:: tyrant_port
  15. The port to the Tokyo Tyrant server.
  16. """
  17. tyrant_host = None
  18. tyrant_port = None
  19. def __init__(self, tyrant_host=None, tyrant_port=None):
  20. """Initialize Tokyo Tyrant backend instance.
  21. Raises :class:`django.core.exceptions.ImproperlyConfigured` if
  22. :setting:`TT_HOST` or :setting:`TT_PORT` is not set.
  23. """
  24. self.tyrant_host = tyrant_host or \
  25. getattr(settings, "TT_HOST", self.tyrant_host)
  26. self.tyrant_port = tyrant_port or \
  27. getattr(settings, "TT_PORT", self.tyrant_port)
  28. if self.tyrant_port:
  29. self.tyrant_port = int(self.tyrant_port)
  30. if not self.tyrant_host or not self.tyrant_port:
  31. raise ImproperlyConfigured(
  32. "To use the Tokyo Tyrant backend, you have to "
  33. "set the TT_HOST and TT_PORT settings in your settings.py")
  34. super(Backend, self).__init__()
  35. self._connection = None
  36. def open(self):
  37. """Get :class:`pytyrant.PyTyrant`` instance with the current
  38. server configuration.
  39. The connection is then cached until you do an
  40. explicit :meth:`close`.
  41. """
  42. # connection overrides bool()
  43. if self._connection is None:
  44. self._connection = pytyrant.PyTyrant.open(self.tyrant_host,
  45. self.tyrant_port)
  46. return self._connection
  47. def close(self):
  48. """Close the tyrant connection and remove the cache."""
  49. # connection overrides bool()
  50. if self._connection is not None:
  51. self._connection.close()
  52. self._connection = None
  53. def process_cleanup(self):
  54. self.close()
  55. def get(self, key):
  56. return self.open().get(key)
  57. def set(self, key, value):
  58. self.open()[key] = value