Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
82 lines (67 sloc) 3.21 KB
import simplejson
import amqplib.client_0_8 as amqp
class Queue():
"""Base class for AMQP queue service."""
def __init__(self, queue_name):
self.conn = amqp.Connection('HOST_HERE', userid='guest', password='guest', ssl=False)
self.queue_name = queue_name =
def declare(self):
return, passive=False, durable=True, exclusive=False, auto_delete=False)
def __len__(self):
"""Return number of messages waiting in this queue"""
_,n_msgs,_ = self.declare()
return n_msgs
def consumers(self):
"""Return how many clients are currently listening to this queue."""
_,_,n_consumers = self.declare()
return n_consumers
class QueueProducer(Queue):
def __init__(self, queue_name):
"""Create new queue producer (guy that creates messages.)
Will create a queue if the given name does not already exist."""
Queue.__init__(self, queue_name)'/data',active=True,read=False,write=True)'sqs_exchange', 'direct', durable=True, auto_delete=False)
qname, n_msgs, n_consumers = self.declare()
print "Connected to %s (%d msgs, %d consumers)" % (qname, n_msgs, n_consumers), 'sqs_exchange', self.queue_name)
def delete(self):
"""Delete a queue and closes the queue connection."""
def write(self, message):
"""Write a single message to the queue. Message can be a dict or a list or whatever."""
m = amqp.Message(simplejson.dumps(message), content_type='text/x-json'), 'sqs_exchange', self.queue_name)
class QueueConsumer(Queue):
def __init__(self, queue_name):
"""Create new queue consumer (guy that listens to messages.)"""
Queue.__init__(self, queue_name)'/data',active=True, read=True, write=False), 'sqs_exchange', self.queue_name)
def ack(self, delivery_tag):
"""Acknowledge receipt of the message (which will remove it off the queue.)
Do this after you've completed your processing of the message.
Otherwise after some amount of time (about a minute) it will go back on the queue.
(object, tag) = consumer.get()
if(object is not None):
error = doSomethingWithMessage(object)
if(error is None):
def get(self):
"""Get a message. Returns the object and a delivery tag."""
m =
if(m is not None):
ret = simplejson.loads(m.body)
except ValueError:
print "Problem decoding json for body " + str(m.body) + ". deleting."
return (None, None)
return (ret, m.delivery_tag)
return (None,None)
Jump to Line
Something went wrong with that request. Please try again.