Skip to main content

CQRS Framing

A Python framework for CQRS (Command Query Responsibility Segregation) and Domain Events, inspired by .NET's CommandQuery.Framing. Features built-in dependency injection using di-done-right.

Features

  • CQRS Pattern: Separate command and query handlers with type-based routing
  • Built-in Dependency Injection: Uses di-done-right for automatic dependency resolution
  • Sync & Async Support: Both synchronous and asynchronous handler execution
  • Pipeline Middleware: Cross-cutting concerns via middleware pattern
  • Domain Events: First-class domain event support with aggregate roots
  • Delegate-Style Events: Subscribe to events using += / -= syntax
  • Framework Agnostic: No dependency on FastAPI or other web frameworks
  • Type Safe: Full type hints and py.typed marker

Installation

pip install cqrs-framing

Quick Start

Handler Contract

All handlers must inherit from either Handler (sync) or AsyncHandler (async):

from cqrs_framing import Handler, AsyncHandler, CancellationToken

# Synchronous handler
class MySyncHandler(Handler[MyCommand, str]):
    def execute(self, message: MyCommand) -> str:
        return "result"

# Asynchronous handler
class MyAsyncHandler(AsyncHandler[MyCommand, str]):
    async def execute(self, message: MyCommand, cancellation_token: CancellationToken) -> str:
        return "result"

Why inheritance is required:

  • ✅ Clear contract discovery in IDEs (autocomplete, hints)
  • ✅ Type checker enforcement (mypy/Pylance catches errors)
  • ✅ Registration-time validation (fails fast if signature is wrong)
  • ✅ Prevents accidental direct invocation bypassing the broker

Define Messages and Handlers

from cqrs_framing import Message, AsyncHandler, CommandResponse, Response, CancellationToken
from dataclasses import dataclass

@dataclass
class CreateUser(Message):
    username: str
    email: str

class CreateUserHandler(AsyncHandler[CreateUser, CommandResponse[str]]):
    async def execute(self, message: CreateUser, cancellation_token: CancellationToken) -> CommandResponse[str]:
        # Your business logic here
        user_id = f"user-{message.username}"
        return Response.ok(user_id)

Register and Execute

from cqrs_framing import Broker, HandlerRegistry

# Setup
registry = HandlerRegistry()
broker = Broker(registry)

# Register handler (will be auto-instantiated by DI)
registry.register(CreateUser, CreateUserHandler)

# Execute command
result = await broker.handle_async(CreateUser(username="john", email="john@example.com"))

Pipeline Middleware

Wrap handler execution with cross-cutting concerns such as logging, validation, timing or transactions. Middleware is async (ctx, next) -> result and runs in the order it was added:

from cqrs_framing import AsyncHandlerContext, Broker, Pipeline, Response

async def logging_middleware(ctx: AsyncHandlerContext, next):
    print(f"-> {type(ctx.request).__name__}")
    result = await next(ctx)
    print(f"<- success={ctx.success}")
    return result

async def validation_middleware(ctx: AsyncHandlerContext, next):
    if isinstance(ctx.request, CreateUser) and not ctx.request.email:
        # Short-circuit: the handler is never called
        ctx.should_continue = False
        ctx.response = Response.failed("Email is required")
        return ctx.response
    return await next(ctx)

pipeline = Pipeline[AsyncHandlerContext]()
pipeline.use(logging_middleware).use(validation_middleware)

broker = Broker(registry, async_pipeline=pipeline)

After the handler runs, the context carries success, exception and error_message, so middleware can inspect or react to the outcome.

Handler-specific pipelines

A pipeline can also be attached to a single handler. It runs inside the broker-wide pipeline, so the order is global pipeline, then handler pipeline, then execute:

audit_pipeline = Pipeline[AsyncHandlerContext]().use(audit_middleware)

registry.register(CreateUser, CreateUserHandler, pipeline=audit_pipeline)

# or with the decorator
@handler(CreateUser, pipeline=audit_pipeline)
class CreateUserHandler(AsyncHandler[CreateUser, CommandResponse[str]]): ...

Use async_pipeline for async handlers and sync_pipeline for sync handlers (see below for the sync caveat).

Async and sync semantics

  • Prefer Broker.handle_async(...) in async applications.
  • Broker.handle(...) is for synchronous handlers. If you provide a sync_pipeline, it requires creating an event loop internally; calling it from within an already-running event loop will raise a RuntimeError.
  • Event.fire(...) / EventHub.publish(...) are fire-and-forget. If you subscribe any async handlers, publish from an async context or use fire_async(...) / publish_async(...).

Handlers with Dependencies

class UserRepository:
    def save(self, user): ...

class CreateUserHandler(AsyncHandler[CreateUser, CommandResponse[str]]):
    def __init__(self, repository: UserRepository):
        self.repository = repository
    
    async def execute(self, message: CreateUser, cancellation_token) -> CommandResponse[str]:
        # Dependencies are auto-injected!
        user_id = f"user-{message.username}"
        self.repository.save({"id": user_id, "username": message.username})
        return Response.ok(user_id)

# Register service in DI container
registry.container.register_instance(UserRepository, UserRepository())

# Register handler (repository will be injected)
registry.register(CreateUser, CreateUserHandler)

Domain Events

from cqrs_framing import AggregateRoot, DomainEvent, EventHub
from dataclasses import dataclass

@dataclass
class UserCreated(DomainEvent):
    user_id: str
    email: str

class User(AggregateRoot):
    def __init__(self, user_id: str, email: str):
        super().__init__()
        self.user_id = user_id
        self.email = email
        self._raise(UserCreated(user_id=user_id, email=email))

# Subscribe to events
hub = EventHub()

def send_welcome_email(event: UserCreated):
    print(f"Sending welcome email to {event.email}")

hub[UserCreated] += send_welcome_email

# Publish events
user = User("123", "john@example.com")
for event in user.pending_events:
    hub.publish(event)

Requirements

  • Python >= 3.10

License

MIT

Metadata

Release files for cqrs-framing 0.2.1

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

Source distribution (sdist)

Source distribution for cqrs-framing 0.2.1
File Size Uploaded Provenance Actions
cqrs_framing-0.2.1.tar.gz 16.4 kB Without provenance Details for cqrs_framing-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cqrs-framing 0.2.1
File Interpreter ABI Platform Actions
cqrs_framing-0.2.1-py3-none-any.whl Python 3 none any Details for cqrs_framing-0.2.1-py3-none-any.whl

Total release size: 33.6 kB

Release files / cqrs_framing-0.2.1.tar.gz

Download URL cqrs_framing-0.2.1.tar.gz
Size 16.4 kB
Tags Source
SHA-256 checksum
How to use checksums
ea7ca1883638b70493364a4d95ee2c8ee8191f57374b869884f022ce5cfa8cd8
BLAKE2b-256 checksum
How to use checksums
afb70c45be22f5ef9ba2fae41d326038117ca3990141a3125442693991f8cd65
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.17

Release files / cqrs_framing-0.2.1-py3-none-any.whl

Download URL cqrs_framing-0.2.1-py3-none-any.whl
Size 17.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5239bc49bce806ea16952eab696e07b48429d3ffa7dac2e159b79dee5612f9df
BLAKE2b-256 checksum
How to use checksums
c79beab5d0aed63e083c0bc9475f227d10453328088ca633dfda112c1bda5c33
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.17

Security for cqrs-framing 0.2.1

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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