May 20, 2009 around 6pm

Working with Python and RabbitMQ

I recently installed [RabbitMQ]( to handle some message queuing needs at [Readernaut]( and thought I'd share how everything came together. If you'd like to learn more about RabbitMQ please read the excellent [Rabbits and Warrens](

To use RabbitMQ with python you need amqplib because Rabbit uses the AMQP standard. To make amqplib a little easier to use I needed a simple script that did three things:

There’s a project called Carrot which handles all this and much more but it’s a little too complex for what I’m doing. All I needed was something very small, straightforward, and EASY. After staring at Carrot for a few days I decided to distill down what I needed into a single script I’m calling Flopsy (this is what happens when you’re coding and watching a movie about Beatrix Potter, right?). So here we go: Step 1: Set global variables:
AMQP_SERVER = ‘localhost’
AMQP_PORT = 5672
AMQP_USER = ‘guest’
Step 2: Create a consumer (a script that consumes messages from the queue):
from flopsy import Connection, Consumer
consumer = Consumer(connection=Connection())
consumer.declare(queue=‘books’, exchange=‘readernaut’, routing_key=‘importer’, auto_delete=False)

def message_callback(message): print ‘Recieved: ‘ + message.body

consumer.register(message_callback) consumer.wait()

Step 3: Create a publisher (a script that publishes messages to the queue):
from flopsy import Connection, Publisher
publisher = Publisher(connection=Connection(), exchange=‘readernaut’, routing_key=‘importer’)
publisher.publish(‘Test message!’)
And there we go! Flopsy weighs in at under 80 lines of code and it can be found on Github. Most of the above will make a lot more sense after reading the Rabbits and Warrens article and investigating RabbitMQ. Update: I just realized, this isn’t at all Django specific so my title is a little misleading (changing). That said, you could most certainly use Flopsy with straight up Python :)