tyrant.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """celery.backends.tyrant"""
  2. try:
  3. import pytyrant
  4. except ImportError:
  5. pytyrant = None
  6. from celery.loaders import load_settings
  7. from celery.backends.base import KeyValueStoreBackend
  8. from celery.exceptions import ImproperlyConfigured
  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):
  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. if not pytyrant:
  24. raise ImproperlyConfigured(
  25. "You need to install the pytyrant library to use the "
  26. + "Tokyo Tyrant backend.")
  27. settings = load_settings()
  28. self.tyrant_host = tyrant_host or \
  29. getattr(settings, "TT_HOST", self.tyrant_host)
  30. self.tyrant_port = tyrant_port or \
  31. getattr(settings, "TT_PORT", self.tyrant_port)
  32. if self.tyrant_port:
  33. self.tyrant_port = int(self.tyrant_port)
  34. if not self.tyrant_host or not self.tyrant_port:
  35. raise ImproperlyConfigured(
  36. "To use the Tokyo Tyrant backend, you have to "
  37. "set the TT_HOST and TT_PORT settings in your settings.py")
  38. super(TyrantBackend, self).__init__()
  39. self._connection = None
  40. def open(self):
  41. """Get :class:`pytyrant.PyTyrant`` instance with the current
  42. server configuration.
  43. The connection is then cached until you do an
  44. explicit :meth:`close`.
  45. """
  46. # connection overrides bool()
  47. if self._connection is None:
  48. self._connection = pytyrant.PyTyrant.open(self.tyrant_host,
  49. self.tyrant_port)
  50. return self._connection
  51. def close(self):
  52. """Close the tyrant connection and remove the cache."""
  53. # connection overrides bool()
  54. if self._connection is not None:
  55. self._connection.close()
  56. self._connection = None
  57. def process_cleanup(self):
  58. self.close()
  59. def get(self, key):
  60. return self.open().get(key)
  61. def set(self, key, value):
  62. self.open()[key] = value