CloudAMQP with Python Getting started

The recommended library for Python to access RabbitMQ servers is Pika.

Put pika==0.11.0 in your requirement.txt file.

The following code connects to CloudAMQP, declares a queues, publish a message to it, setups a subscription and print messages coming to the queue.

Note: The DEFAULT_SOCKET_TIMEOUT is set to 0.25s, we would recommend to raise this parameter to about 5s to avoid connection timeout, params.socket_timeout = 5 Other connection parameter options for Pika can be found here: Connection Parameters.

The full code can be seen at github.com/cloudamqp/python-amqp-example.

# publish.py
import pika, os

# Access the CLODUAMQP_URL environment variable and parse it (fallback to localhost)
url = os.environ.get('CLOUDAMQP_URL', 'amqp://guest:guest@localhost:5672/%2f')
params = pika.URLParameters(url)
connection = pika.BlockingConnection(params)
channel = connection.channel() # start a channel
channel.queue_declare(queue='hello') # Declare a queue
channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello CloudAMQP!')

print(" [x] Sent 'Hello World!'")
connection.close()
# consume.py
import pika, os

# Access the CLODUAMQP_URL environment variable and parse it (fallback to localhost)
url = os.environ.get('CLOUDAMQP_URL', 'amqp://guest:guest@localhost:5672/%2f')
params = pika.URLParameters(url)
connection = pika.BlockingConnection(params)
channel = connection.channel() # start a channel

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
  print(" [x] Received %r" % body)

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

print(' [*] Waiting for messages:')
channel.start_consuming()

Information about Celery can be found here.

Video

Here's a video recording showing how to setup a CloudAMQP instance and connect to it using Python and the Pika library:

Alternative clients

Rabbitpy
Rabbitpy is a simple and easy to use API for interfacing with RabbitMQ. It is a pure python, thread-safe, minimalistic and pythonic RabbitMQ client library. More information about Rabbitpy can be found here.