Guides RabbitMQ Last updated:

Part 2.3: Getting started with RabbitMQ and Python

Part 2.3: Getting started with RabbitMQ and Python
Part 2.3 of RabbitMQ for beginners shows how to get started with RabbitMQ and Python.

This part follows the scenario from Part 1: What is RabbitMQ?: a web application sends a “PDF processing” message to a queue, and a worker picks it up, generates the PDF and emails it to the user. If you’re new to RabbitMQ and message queuing, start there.

The code is in our docs

The Python code for this guide lives in Python with RabbitMQ and LavinMQ. It uses Pika, and it’s tested and kept up to date, so it works with today’s RabbitMQ. There are three files:

  • amqp.py connects to your RabbitMQ server.
  • publisher.py plays the web application: it publishes a message to a queue.
  • worker.py plays the PDF worker: it consumes the messages from the queue.

What to look for in the code

  • A durable queue. The queue survives a broker restart.
  • Ack after the work is done. The worker acknowledges a message once it’s handled. If the worker crashes before that, RabbitMQ delivers the message again. You can see this in action in the simulation in Part 1.
  • Prefetch. The worker takes up to 10 messages at a time, so one busy worker doesn’t hold on to the whole queue.
  • One connection, reused. The connection opens once and stays open for all messages, instead of one connection per message.

Run it

  1. Create a free RabbitMQ instance on CloudAMQP with the Little Lemur plan.
  2. Copy the AMQP URL from your instance’s details page, and set it as the BROKER_URL environment variable in both terminals.
  3. Run python worker.py in one terminal and python publisher.py in another.

Running background tasks in Python? Celery with RabbitMQ shows how to use RabbitMQ as the Celery broker.

Next up is Part 3: The management interface, where you can watch your messages in the queue.

Guide — RabbitMQ for beginners

CloudAMQP - industry-leading RabbitMQ as a Service

Fully managed RabbitMQ clusters on all major clouds. Free plan available - no credit card required.

Sign up for free