PageRenderTime 217ms CodeModel.GetById 71ms app.highlight 72ms RepoModel.GetById 69ms app.codeStats 0ms

/queues/backends/beanstalkd.py

http://queues.googlecode.com/
Python | 69 lines | 52 code | 12 blank | 5 comment | 3 complexity | b42db576eaf5d15a9b99503d31217870 MD5 | raw file
 1"""
 2Backend for beanstalkd queue.
 3
 4This backend requires the beanstalkc library to be installed.
 5"""
 6
 7from queues.backends.base import BaseQueue
 8from queues import InvalidBackend, QueueException
 9import os
10
11
12try:
13    import beanstalkc
14except ImportError:
15    raise InvalidBackend("Unable to import the beanstalkc library.")
16
17try:
18    from django.conf import settings
19    CONN = getattr(settings, 'QUEUE_BEANSTALKD_CONNECTION', None)
20except:
21    CONN = os.environ.get('QUEUE_BEANSTALKD_CONNECTION', None)
22
23if not CONN:
24    raise InvalidBackend("QUEUE_BEANSTALKD_CONNECTION not set.")
25
26
27class Queue(BaseQueue):
28    def __init__(self, name='default'):
29        host, port = CONN.split(':')
30        self._connection = beanstalkc.Connection(host=host, port=int(port))
31        self.backend = 'beanstalkd'
32        self.name = name
33        self._connection.use(name)
34
35    def read(self):
36        try:
37            job = self._connection.reserve()
38            message = job.body
39            job.delete()
40            return message
41        except (beanstalkc.DeadlineSoon, beanstalkc.CommandFailed, beanstalkc.UnexpectedResponse), e:
42            raise QueueException, e
43
44    def write(self, message):
45        try:
46            return self._connection.put(message)
47        except (beanstalkc.CommandFailed, beanstalkc.UnexpectedResponse), e:
48            raise QueueException, e
49
50    def __len__(self):
51        try:
52            return int(self._connection.stats().get('current-jobs-ready', 0))
53        except (beanstalkc.CommandFailed, beanstalkc.UnexpectedResponse), e:
54            raise QueueException, e
55
56    def __repr__(self):
57        return "<Queue %s>" % self.name
58
59def create_queue():
60    """This isn't required, so we noop.  Kept here for swapability."""
61    return True
62
63def delete_queue(name):
64    """Beanstalkd backends don't provide a way to do this."""
65    raise NotImplementedError
66
67def get_list():
68    """Beanstalkd backends don't provide a way to do this."""
69    raise NotImplementedError