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.typedmarker
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"))
Async and sync semantics
- Prefer
Broker.handle_async(...)in async applications. Broker.handle(...)is for synchronous handlers. If you provide async_pipeline, it requires creating an event loop internally; calling it from within an already-running event loop will raise aRuntimeError.Event.fire(...)/EventHub.publish(...)are fire-and-forget. If you subscribe any async handlers, publish from an async context or usefire_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.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cqrs_framing-0.2.0.tar.gz | 15.0 kB | Without provenance | Details for cqrs_framing-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cqrs_framing-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for cqrs_framing-0.2.0-py3-none-any.whl |
Total release size: 31.5 kB
Release files / cqrs_framing-0.2.0.tar.gz
| Download URL | cqrs_framing-0.2.0.tar.gz |
|---|---|
| Size | 15.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
68c54c284ffe2ec945ebeb4618eb22d539ced3b2b2f21a4f8ec72091ae971c2d
|
|
BLAKE2b-256 checksum How to use checksums |
87f3edef7bc87cafb6815d915b9d502f49b42a20b157b98ee2dfb2597ea39b38
|
| 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.0-py3-none-any.whl
| Download URL | cqrs_framing-0.2.0-py3-none-any.whl |
|---|---|
| Size | 16.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1ef1753212e1b56a80b88c43f496b77de7e3fe267463b62a86410dfa6e72bf32
|
|
BLAKE2b-256 checksum How to use checksums |
ed06d351682befad4ac17efab6617382c7437b30fd56c89ffa1d99955cab2c95
|
| 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.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.
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.