Pika Python AMQP Client

1.3.2 · active · verified Thu Apr 09

Pika is a Python AMQP client library that provides both synchronous (BlockingConnection) and asynchronous (e.g., AsyncioConnection) interfaces for interacting with AMQP 0-9-1 brokers like RabbitMQ. The library is actively maintained, with regular patch and minor releases (currently at 1.3.2, with 1.4.0 in beta), addressing bug fixes, performance improvements, and Python compatibility.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a simple Pika producer using BlockingConnection to connect to a RabbitMQ instance (defaulting to localhost) and publish a message to a 'hello' queue. It also shows the basic setup for a consumer callback (commented out) and proper connection/channel closure.

import pika
import os

def callback(ch, method, properties, body):
    print(f" [x] Received {body.decode()}")

# Get RabbitMQ host from environment or default to localhost
rabbitmq_host = os.environ.get('RABBITMQ_HOST', 'localhost')

connection = None
channel = None
try:
    # Establish connection
    connection = pika.BlockingConnection(pika.ConnectionParameters(host=rabbitmq_host))
    channel = connection.channel()

    # Declare a queue
    channel.queue_declare(queue='hello')

    # Publish a message
    channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
    print(" [x] Sent 'Hello World!'")

    # Start consuming (example consumer setup)
    # channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
    # print(' [*] Waiting for messages. To exit press CTRL+C')
    # channel.start_consuming()

finally:
    # Ensure channel and connection are closed
    if channel and channel.is_open:
        channel.close()
    if connection and connection.is_open:
        connection.close()

view raw JSON →