Skip to main content

Generic mediator pattern with pipeline behaviors

Project description

gridflow-python-mediator

Generic mediator pattern implementation with zero dependencies and pipeline behavior support.

Extracted from: GridFlow backend/src/apps/token_generator/application/common/mediator/

Installation

# Core (zero dependencies)
pip install gridflow-python-mediator

# With logging support
pip install gridflow-python-mediator[logging]

Features

  • Zero Dependencies: Pure Python implementation
  • Pipeline Behaviors: Logging, timing, validation
  • Type-Safe: Full generic type support
  • Async/Sync: Supports both async and sync handlers

Usage

Basic Mediator

from gridflow_python_mediator import Mediator

# Define request and handler
class GetUserRequest:
    def __init__(self, user_id: int):
        self.user_id = user_id

class GetUserHandler:
    async def handle(self, request: GetUserRequest):
        # Fetch user logic
        return {"id": request.user_id, "name": "John"}

# Setup mediator
mediator = Mediator()
mediator.register_handler(GetUserRequest, GetUserHandler())

# Send request
request = GetUserRequest(user_id=1)
result = await mediator.send(request)

With CQRS

from python_cqrs_core import BaseCommand, ICommandHandler
from gridflow_python_mediator import Mediator

class CreateUserCommand(BaseCommand):
    name: str
    email: str

class CreateUserHandler(ICommandHandler[CreateUserCommand, int]):
    async def handle(self, command: CreateUserCommand) -> int:
        # Create user
        return user_id

mediator = Mediator()
mediator.register_handler(CreateUserCommand, CreateUserHandler())

cmd = CreateUserCommand(name="John", email="john@example.com")
user_id = await mediator.send(cmd)

Pipeline Behaviors

from gridflow_python_mediator import (
    Mediator,
    LoggingBehavior,
    TimingBehavior,
    ValidationBehavior
)

mediator = Mediator()

# Add behaviors (executed in order)
mediator.add_pipeline_behavior(LoggingBehavior().handle)
mediator.add_pipeline_behavior(TimingBehavior().handle)
mediator.add_pipeline_behavior(ValidationBehavior().handle)

# Behaviors run before handler
result = await mediator.send(request)

Custom Behavior

async def auth_behavior(request, handler):
    """Check authentication before handler."""
    if not request.user_id:
        raise ValueError("Unauthorized")
    return None  # Continue to handler

mediator.add_pipeline_behavior(auth_behavior)

API Reference

Mediator

Generic request/response dispatcher.

Methods:

register_handler(request_type, handler)

Register handler for request type.

Parameters:

  • request_type (Type): Request class
  • handler (Any): Handler instance with handle() method

async send(request) -> TResult

Dispatch request to handler.

Parameters:

  • request (TRequest): Request to send

Returns:

  • Result from handler

add_pipeline_behavior(behavior)

Add pipeline behavior.

Parameters:

  • behavior (Callable): Async function(request, handler) -> Optional[result]

Built-in Behaviors

LoggingBehavior

Logs request type before/after handler.

Requires: structlog>=23.0.0

TimingBehavior

Measures and logs execution duration.

Requires: structlog>=23.0.0

ValidationBehavior

Validates Pydantic models before handler.

Design Patterns

Mediator Pattern

Decouples senders from receivers:

  • Single point of dispatch
  • Handler registration
  • Pipeline behaviors

Pipeline Pattern

Behaviors execute in order:

  1. Logging
  2. Timing
  3. Validation
  4. Handler

Dependencies

  • Core: None (zero dependencies!)
  • Optional: structlog>=23.0.0 (for logging behaviors)

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gridflow_python_mediator-0.1.0.tar.gz (7.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gridflow_python_mediator-0.1.0-py3-none-any.whl (6.8 kB view details)

Uploaded Python 3

File details

Details for the file gridflow_python_mediator-0.1.0.tar.gz.

File metadata

  • Download URL: gridflow_python_mediator-0.1.0.tar.gz
  • Upload date:
  • Size: 7.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for gridflow_python_mediator-0.1.0.tar.gz
Algorithm Hash digest
SHA256 b8fa61fb4fa7947bbb970bde1e39bd4546f54f73b5eb473608933ffe8f61f0da
MD5 d4d93931ea170ba0193169e5f3e401be
BLAKE2b-256 2e8f8a66a399655778178f3f10481a3b45abcc311de3a58481f9d440d3a77749

See more details on using hashes here.

Provenance

The following attestation bundles were made for gridflow_python_mediator-0.1.0.tar.gz:

Publisher: publish-pypi.yml on firstunicorn/python-web-toolkit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file gridflow_python_mediator-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for gridflow_python_mediator-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4665be691550893c6f6d650b269f4e78b1d2a4485bc00b39a262163993183982
MD5 aabf13bb8f4dde41c3663d0badc6a9fc
BLAKE2b-256 b76925978a9547a3d268c0d00eae52c72a762ca3dbfb9e4697f3c7686c5592ff

See more details on using hashes here.

Provenance

The following attestation bundles were made for gridflow_python_mediator-0.1.0-py3-none-any.whl:

Publisher: publish-pypi.yml on firstunicorn/python-web-toolkit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page