Claude Code for kombu: Python Message Transport Abstraction Library — Claude Skills 360 Blog
Blog / AI / Claude Code for kombu: Python Message Transport Abstraction Library
AI

Claude Code for kombu: Python Message Transport Abstraction Library

Published: May 17, 2028
Read time: 5 min read
By: Claude Skills 360

kombu is a messaging library that abstracts AMQP, Redis, SQS, and other transports. pip install kombu. Connect: from kombu import Connection; conn = Connection("amqp://guest:guest@localhost//"). Redis: Connection("redis://localhost:6379/0"). SQS: Connection("sqs://"). Exchange: from kombu import Exchange; ex = Exchange("tasks", type="direct"). Queue: from kombu import Queue; q = Queue("emails", exchange=ex, routing_key="emails"). Producer: with conn.Producer() as p: p.publish({"task": "send"}, exchange=ex, routing_key="emails", serializer="json"). Consumer: with conn.Consumer(q, callbacks=[on_message]): conn.drain_events(). SimpleQueue: with conn.SimpleQueue("tasks") as sq: sq.put({"job": "process"}); msg = sq.get(block=True); msg.ack(). Declare: q.declare(). Exchange types: "direct" "fanout" "topic" "headers". Serializer: "json" "msgpack" "yaml" "pickle". Compression: "zlib" "bzip2". Retry: conn.ensure_connection(max_retries=3). Context: with conn: .... Channel: ch = conn.channel(); p = Producer(ch). Ack: message.ack(). Reject: message.reject(requeue=True). conn.as_uri(). conn.transport_cls. Claude Code generates kombu producers, consumer loops, multi-broker setups, and Celery-compatible task pipelines.

CLAUDE.md for kombu

## kombu Stack
- Version: kombu >= 5.3 | pip install kombu
- Connect: Connection("amqp://user:pass@host//") | Connection("redis://host:6379/0")
- Exchange/Queue: Exchange("name", type="direct") | Queue("q", exchange=ex, routing_key="rk")
- Publish: with conn.Producer() as p: p.publish(body, exchange=ex, routing_key="rk", serializer="json")
- Consume: with conn.Consumer(queues, callbacks=[cb]): conn.drain_events(timeout=1)
- SimpleQueue: conn.SimpleQueue("name") — dict-like, auto-declares

kombu Multi-Broker Messaging Pipeline

# app/messaging.py — kombu producer, consumer, fanout, multi-broker, and helpers
from __future__ import annotations

import json
import logging
import socket
import time
from contextlib import contextmanager
from dataclasses import asdict, dataclass
from typing import Any, Callable

from kombu import Connection, Exchange, Producer, Queue
from kombu.mixins import ConsumerMixin
from kombu.transport import pyamqp


log = logging.getLogger(__name__)


# ─────────────────────────────────────────────────────────────────────────────
# 1. Connection helpers
# ─────────────────────────────────────────────────────────────────────────────

def make_connection(
    url: str = "amqp://guest:guest@localhost//",
    heartbeat: float = 60.0,
    connect_timeout: float = 4.0,
    ssl: bool = False,
    transport_options: dict | None = None,
) -> Connection:
    """
    Create a kombu Connection.
    url: broker URL — supports AMQP, redis://, sqs://, memory:// (in-process for tests)

    Examples:
        make_connection("amqp://guest:guest@localhost//")
        make_connection("redis://localhost:6379/0")
        make_connection("memory://")   # in-memory for unit tests
    """
    return Connection(
        url,
        heartbeat=heartbeat,
        connect_timeout=connect_timeout,
        ssl=ssl,
        transport_options=transport_options or {},
    )


@contextmanager
def connection_ctx(url: str = "amqp://guest:guest@localhost//", **kwargs):
    """
    Context manager yielding a connected Connection.

    Usage:
        with connection_ctx("redis://localhost/0") as conn:
            publish(conn, "events", {"type": "user.created"})
    """
    conn = make_connection(url, **kwargs)
    with conn:
        yield conn


def ensure_connected(
    conn: Connection,
    max_retries: int = 5,
    interval_start: float = 2.0,
    interval_step: float = 1.0,
    interval_max: float = 10.0,
) -> Connection:
    """
    Ensure connection is open, reconnecting with exponential back-off.
    Returns the connected connection.
    """
    conn.ensure_connection(
        max_retries=max_retries,
        interval_start=interval_start,
        interval_step=interval_step,
        interval_max=interval_max,
    )
    return conn


# ─────────────────────────────────────────────────────────────────────────────
# 2. Exchange and queue setup
# ─────────────────────────────────────────────────────────────────────────────

def make_exchange(
    name: str,
    exchange_type: str = "direct",
    durable: bool = True,
    auto_delete: bool = False,
) -> Exchange:
    """
    Create a kombu Exchange.
    exchange_type: "direct" | "fanout" | "topic" | "headers"
    """
    return Exchange(name, type=exchange_type, durable=durable, auto_delete=auto_delete)


def make_queue(
    name: str,
    exchange: Exchange | None = None,
    routing_key: str = "",
    durable: bool = True,
    exclusive: bool = False,
    auto_delete: bool = False,
    message_ttl: int | None = None,
    dead_letter_exchange: str | None = None,
) -> Queue:
    """
    Create a kombu Queue.
    message_ttl: milliseconds before message is routed to DLX.
    dead_letter_exchange: exchange name for expired/rejected messages.
    """
    kwargs: dict = {
        "durable":      durable,
        "exclusive":    exclusive,
        "auto_delete":  auto_delete,
    }
    queue_args: dict = {}
    if message_ttl is not None:
        queue_args["x-message-ttl"] = message_ttl
    if dead_letter_exchange:
        queue_args["x-dead-letter-exchange"] = dead_letter_exchange
    if queue_args:
        kwargs["queue_arguments"] = queue_args

    if exchange:
        return Queue(name, exchange=exchange, routing_key=routing_key, **kwargs)
    return Queue(name, **kwargs)


def declare_entities(
    conn: Connection,
    *entities: Exchange | Queue,
) -> None:
    """
    Declare exchanges and queues on the broker.
    Idempotent — safe to call on startup.
    """
    ch = conn.channel()
    for entity in entities:
        entity.declare(channel=ch)


# ─────────────────────────────────────────────────────────────────────────────
# 3. Publishing
# ─────────────────────────────────────────────────────────────────────────────

def publish(
    conn: Connection,
    body: dict | str | bytes,
    exchange: Exchange | str = "",
    routing_key: str = "",
    serializer: str = "json",
    compression: str | None = None,
    headers: dict | None = None,
    delivery_mode: int = 2,
    expiration: str | None = None,
    retry: bool = True,
    retry_policy: dict | None = None,
) -> None:
    """
    Publish a message.
    delivery_mode: 2 = persistent (survives broker restart), 1 = transient.
    expiration: message TTL as string milliseconds e.g. "30000".
    retry: auto-retry on transient connection errors.

    Example:
        publish(conn, {"user_id": 42, "action": "signup"}, exchange=user_ex, routing_key="user.signup")
    """
    with conn.Producer() as producer:
        producer.publish(
            body,
            exchange=exchange,
            routing_key=routing_key,
            serializer=serializer,
            compression=compression,
            headers=headers or {},
            delivery_mode=delivery_mode,
            expiration=expiration,
            retry=retry,
            retry_policy=retry_policy or {
                "interval_start": 0,
                "interval_step":  1,
                "interval_max":   5,
                "max_retries":    3,
            },
        )


class MessagePublisher:
    """
    Reusable publisher with a persistent connection and channel.

    Usage:
        pub = MessagePublisher("redis://localhost/0", exchange_name="events")
        pub.send({"event": "order.created", "order_id": 123}, routing_key="order.created")
        pub.close()
    """

    def __init__(
        self,
        url: str = "amqp://guest:guest@localhost//",
        exchange_name: str = "default",
        exchange_type: str = "topic",
        default_routing_key: str = "#",
        serializer: str = "json",
    ) -> None:
        self._conn         = make_connection(url)
        self._exchange     = make_exchange(exchange_name, exchange_type)
        self._default_rk   = default_routing_key
        self._serializer   = serializer
        self._producer: Producer | None = None
        self._connect()

    def _connect(self) -> None:
        ensure_connected(self._conn)
        self._producer = self._conn.Producer()

    def send(
        self,
        body: dict | str | bytes,
        routing_key: str | None = None,
        headers: dict | None = None,
    ) -> None:
        rk = routing_key or self._default_rk
        try:
            self._producer.publish(body, exchange=self._exchange, routing_key=rk,
                                   serializer=self._serializer, headers=headers or {},
                                   delivery_mode=2, retry=True)
        except Exception:
            log.warning("Publish failed — reconnecting")
            self._connect()
            self._producer.publish(body, exchange=self._exchange, routing_key=rk,
                                   serializer=self._serializer, delivery_mode=2, retry=True)

    def close(self) -> None:
        self._conn.release()


# ─────────────────────────────────────────────────────────────────────────────
# 4. Consumer (ConsumerMixin pattern)
# ─────────────────────────────────────────────────────────────────────────────

def make_consumer_worker(
    conn: Connection,
    queues: list[Queue],
    handler: Callable[[dict, Any], None],
    prefetch_count: int = 10,
) -> type:
    """
    Build and return a ConsumerMixin worker class.
    Instantiate and call .run() to start consuming.

    Example:
        Worker = make_consumer_worker(conn, [email_q, sms_q], handle_notification)
        Worker(conn).run()
    """
    class Worker(ConsumerMixin):
        def get_consumers(self, Consumer, channel):
            return [Consumer(
                queues,
                callbacks=[self.on_message],
                prefetch_count=prefetch_count,
            )]

        def on_message(self, body, message):
            try:
                if callable(handler):
                    handler(body, message)
                message.ack()
            except Exception as e:
                log.error("Message handler error: %s", e)
                message.reject(requeue=False)

    return Worker


def consume_once(
    conn: Connection,
    queues: list[Queue] | Queue,
    handler: Callable[[dict, Any], None],
    timeout: float = 5.0,
    limit: int = 100,
) -> int:
    """
    Drain up to `limit` messages with a timeout. Returns count processed.
    Useful for batch processing without a long-running loop.

    Example:
        processed = consume_once(conn, [tasks_q], process_task, timeout=2.0, limit=50)
    """
    if isinstance(queues, Queue):
        queues = [queues]

    processed = [0]

    def on_message(body, message):
        try:
            handler(body, message)
            message.ack()
        except Exception as e:
            log.error("Handler error: %s", e)
            message.reject(requeue=False)
        finally:
            processed[0] += 1

    with conn.Consumer(queues, callbacks=[on_message]):
        try:
            while processed[0] < limit:
                conn.drain_events(timeout=timeout)
        except socket.timeout:
            pass
    return processed[0]


def simple_queue_send(conn: Connection, name: str, body: dict) -> None:
    """
    Send a message using kombu SimpleQueue (auto-declares queue).
    Works with any transport including Redis.
    """
    with conn.SimpleQueue(name) as sq:
        sq.put(body, serializer="json")


def simple_queue_recv(conn: Connection, name: str, block: bool = True, timeout: float = 5.0) -> dict | None:
    """
    Receive one message from a SimpleQueue.
    Returns None on timeout.
    """
    with conn.SimpleQueue(name) as sq:
        try:
            msg = sq.get(block=block, timeout=timeout)
            body = msg.payload
            msg.ack()
            return body
        except sq.Empty:
            return None


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    # In-memory transport — no broker required for this demo
    BROKER_URL = "memory://"

    print("=== Exchanges and queues ===")
    task_ex = make_exchange("tasks", "direct")
    email_q = make_queue("emails", exchange=task_ex, routing_key="emails")
    sms_q   = make_queue("sms",    exchange=task_ex, routing_key="sms")
    print(f"  Exchange: {task_ex}")
    print(f"  Queues:   {email_q}, {sms_q}")

    print("\n=== SimpleQueue round-trip (in-memory) ===")
    conn = make_connection(BROKER_URL)
    simple_queue_send(conn, "demo_queue", {"task": "send_email", "to": "[email protected]"})
    msg = simple_queue_recv(conn, "demo_queue", block=True, timeout=2.0)
    print(f"  Received: {msg}")
    conn.release()

    print("\n=== MessagePublisher (in-memory) ===")
    pub = MessagePublisher(BROKER_URL, exchange_name="events", exchange_type="topic")
    pub.send({"event": "user.created", "id": 42}, routing_key="user.created")
    print("  Published user.created event")
    pub.close()

    print("\nTo test with real RabbitMQ:")
    print("  docker run -d -p 5672:5672 rabbitmq:3-management")
    print("  BROKER_URL = 'amqp://guest:guest@localhost//'")
    print("\nTo test with Redis:")
    print("  docker run -d -p 6379:6379 redis:7")
    print("  BROKER_URL = 'redis://localhost:6379/0'")

For the pika / aio-pika alternative — pika and aio-pika are AMQP-only clients giving direct RabbitMQ protocol access; kombu adds a transport abstraction layer so the same Producer/Consumer code runs against RabbitMQ, Redis, SQS, MongoDB, or an in-memory broker by changing only the connection URL — ideal for applications that need broker portability or test isolation with memory://. For the aiokafka alternative — aiokafka provides asyncio-native Kafka streaming with consumer groups and offset management; kombu targets traditional task queue patterns (direct/topic exchange, ack/nack, DLX) with synchronous or Celery-integrated usage — use aiokafka for high-throughput event streaming, kombu when you want Celery-compatible task queues that can swap brokers. The Claude Skills 360 bundle includes kombu skill sets covering make_connection() with all transport URLs, connection_ctx() manager, ensure_connected() with retry back-off, make_exchange()/make_queue() with type/DLX options, declare_entities() idempotent setup, publish() with retry policy and serialization, MessagePublisher reusable class, make_consumer_worker() ConsumerMixin builder, consume_once() batch drainer, simple_queue_send/recv() Redis-compatible helpers, and in-memory transport for unit testing. Start with the free tier to try multi-broker message transport code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free