LavinMQ with Python

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

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

The following code connects to LavinMQ, 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 HOST_URL environment variable and parse it (fallback to localhost)
url = os.environ.get('HOST_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 HOST_URL environment variable and parse it (fallback to localhost)
url = os.environ.get('HOST_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
def callback(ch, method, properties, body):
  print(" [x] Received " + str(body))

channel.basic_consume('hello',
                      callback,
                      auto_ack=True)

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