Skip to main content

pyramid-kafka

A Pyramid plugin for Apache Kafka integration using confluent-kafka. Provides producer/consumer support with lazy initialization, Pyramid event integration, and a CLI consumer runner.

Installation

uv add pyramid-kafka

Or with pip:

pip install pyramid-kafka

Quick Start

1. Include the plugin

from pyramid.config import Configurator

def main(global_config, **settings):
    config = Configurator(settings=settings)
    config.include("pyramid_kafka")
    return config.make_wsgi_app()

2. Configure your .ini file

# Required
kafka.bootstrap_servers = localhost:9092

# Consumer settings (required for consumer only)
kafka.group_id = my-service
kafka.auto_offset_reset = earliest

# Optional
kafka.client_id = my-service
kafka.topics = my.topic.v1 another.topic.v1
kafka.handler = myapp.stream:process_message
kafka.commit_strategy = auto

# Pass-through to confluent-kafka (any librdkafka setting)
kafka.extra.security.protocol = SASL_SSL
kafka.extra.sasl.mechanisms = PLAIN
kafka.extra.sasl.username = my-key
kafka.extra.sasl.password = my-secret

3. Produce events

Option A: Subclass KafkaEvent

from pyramid_kafka import KafkaEvent

class OrderCreated(KafkaEvent):
    def __init__(self, request, order):
        super().__init__(
            request,
            topic="orders.created.v1",
            key=str(order.id),
            order_id=str(order.id),
            amount=float(order.amount),
        )

# Fire the event from your view or service:
request.registry.notify(OrderCreated(request, order))

Option B: Register any Pyramid event

from dataclasses import dataclass

@dataclass
class PaymentReceived:
    request: object
    payment_id: str
    amount: float

# In your app's startup/includeme:
config.register_kafka_event(
    PaymentReceived,
    topic="payments.received.v1",
    key=lambda e: e.payment_id,
    value=lambda e: {"payment_id": e.payment_id, "amount": e.amount},
)

# Then just fire the standard Pyramid event:
request.registry.notify(PaymentReceived(request=request, payment_id="p-1", amount=50.0))

If value is omitted, the library auto-extracts all public fields (uses dataclasses.fields() for dataclasses, vars() for others, excluding request and private attributes).

4. Consume messages

Run the built-in CLI consumer:

kafka-consumer development.ini

The consumer reads kafka.topics (space or comma-separated) and kafka.handler from settings. The handler is a dotted Python path to a callable with signature (request, message) -> None. Do not call consumer.commit in application code.

Behavior change: kafka.commit_strategy = auto (the default) no longer uses librdkafka interval auto-commit. The CLI commits the offset only after the handler returns successfully. A failing handler does not advance the offset, so the message is redelivered — including forever if the handler always fails. Custom poll loops that use registry.kafka.consumer without this CLI must commit offsets themselves.

# myapp/stream.py
import json

def process_message(request, message):
    value = json.loads(message.value().decode("utf-8"))
    topic = message.topic()
    # Route to your business logic...

CLI options override settings:

kafka-consumer development.ini --handler myapp.stream:process_message --topics "topic-a,topic-b" --timeout 2.0

Configuration Reference

Setting Required Default Description
kafka.bootstrap_servers Yes — Comma-separated Kafka broker list
kafka.group_id Consumer only — Consumer group ID
kafka.auto_offset_reset No earliest Where to start consuming (earliest / latest)
kafka.client_id No — Client identifier
kafka.topics Consumer only — Space or comma-separated topic list
kafka.handler Consumer only — Dotted path to handler callable (module:function)
kafka.commit_strategy No auto auto or transaction. Producer: immediate send vs buffer until pyramid_tm commit. Consumer auto commits after handler success (not librdkafka interval auto-commit). transaction commits the offset after the Pyramid transaction succeeds.
kafka.extra.* No — Pass-through to confluent-kafka/librdkafka config

API

KafkaManager

Attached to config.registry.kafka after config.include("pyramid_kafka").

  • manager.producer — Lazily-initialized confluent_kafka.Producer
  • manager.consumer — Lazily-initialized confluent_kafka.Consumer
  • manager.produce(topic, value, key=None) — JSON-serialize and produce a message
  • manager.close() — Flush producer and close consumer

KafkaEvent

Base class for Kafka-bound Pyramid events. Subclass it and fire via request.registry.notify().

config.register_kafka_event(event_type, topic, key=None, value=None)

Pyramid config directive to wire any event class to Kafka. topic can be a string or callable (event) -> str. key and value are optional callables (event) -> str|dict.

Development

Prerequisites

  • Python 3.11+
  • uv for dependency management

Setup

git clone https://github.com/cartaorobbin/pyramid-kafka.git
cd pyramid-kafka
uv sync --dev

Running Tests

uv run pytest

Linting and Formatting

uv run ruff check .
uv run black .

Building Documentation

uv run mkdocs serve

License

MIT

Metadata

Release files for pyramid-kafka 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyramid-kafka 0.4.0
File Size Uploaded Provenance
pyramid_kafka-0.4.0.tar.gz 72.6 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for pyramid-kafka 0.4.0
File Interpreter ABI Platform
pyramid_kafka-0.4.0-py3-none-any.whl Python 3 none any Details

Total release size: 85.4 kB

Release files / pyramid_kafka-0.4.0.tar.gz

Download URL pyramid_kafka-0.4.0.tar.gz
Size 72.6 kB
Tags Source
SHA-256 checksum
How to use checksums
0ec7a7ab9a3b20adfef426fec592184820ca7b041d0a76b7b4a599e3428a6893
BLAKE2b-256 checksum
How to use checksums
0800aa4f38dc37e92ed5a4a434b6e3197f6c67bda452630be373f92a591bda20
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 16, 2026.

Transparency log

Release files / pyramid_kafka-0.4.0-py3-none-any.whl

Download URL pyramid_kafka-0.4.0-py3-none-any.whl
Size 12.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c3f162821b85fcf850a0ebf7f4cd4e7ffb2a41f87eae975515c75ec95c0fb775
BLAKE2b-256 checksum
How to use checksums
0c17ea812728f7b685cf6d4edae68c8de446184104c9c1b9856f37f18cb6af86
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 16, 2026.

Transparency log

Security for pyramid-kafka 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pyramid_kafka-0.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 16, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page