tyrant.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. """celery.backends.tyrant"""
  2. try:
  3. import pytyrant
  4. except ImportError:
  5. pytyrant = None # noqa
  6. from celery.backends.base import KeyValueStoreBackend
  7. from celery.exceptions import ImproperlyConfigured
  8. class TyrantBackend(KeyValueStoreBackend):
  9. """Tokyo Cabinet based task backend store.
  10. .. attribute:: tyrant_host
  11. The hostname to the Tokyo Tyrant server.
  12. .. attribute:: tyrant_port
  13. The port to the Tokyo Tyrant server.
  14. """
  15. tyrant_host = None
  16. tyrant_port = None
  17. def __init__(self, tyrant_host=None, tyrant_port=None, **kwargs):
  18. """Initialize Tokyo Tyrant backend instance.
  19. Raises :class:`celery.exceptions.ImproperlyConfigured` if
  20. :setting:`TT_HOST` or :setting:`TT_PORT` is not set.
  21. """
  22. super(TyrantBackend, self).__init__(**kwargs)
  23. if not pytyrant:
  24. raise ImproperlyConfigured(
  25. "You need to install the pytyrant library to use the "
  26. + "Tokyo Tyrant backend.")
  27. self.tyrant_host = (tyrant_host or
  28. self.app.conf.get("TT_HOST") or
  29. self.tyrant_host)
  30. self.tyrant_port = (tyrant_port or
  31. self.app.conf.get("TT_PORT") or
  32. self.tyrant_port)
  33. if self.tyrant_port:
  34. self.tyrant_port = int(self.tyrant_port)
  35. if not self.tyrant_host or not self.tyrant_port:
  36. raise ImproperlyConfigured(
  37. "To use the Tokyo Tyrant backend, you have to "
  38. "set the TT_HOST and TT_PORT settings in your settings.py")
  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
  63. def delete(self, key):
  64. self.open().pop(key, None)