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.1.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.1-py3-none-any.whl (6.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: gridflow_python_mediator-0.1.1.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.1.tar.gz
Algorithm Hash digest
SHA256 1f11e7b53ff657aecee2ef609f6603e07d0c32509d54258a52adefe22feff2c7
MD5 cb5ddf103f94f31c9375b77e4c1d41b4
BLAKE2b-256 dd1fe0c3be51942350fda4068a26d77be037bf71f4cfc73c0b85be9ac33c9ac7

See more details on using hashes here.

Provenance

The following attestation bundles were made for gridflow_python_mediator-0.1.1.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.1-py3-none-any.whl.

File metadata

File hashes

Hashes for gridflow_python_mediator-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ec0741fa7ae5be23068c9cb02c9324be8f768a89a6cf163b8f122f685a1af1c8
MD5 d6d3fde19417b5b702be8c59b507bdae
BLAKE2b-256 335cc470a8bdd438661223408195bef114b33cf4285b32b5922f9771cdabb210

See more details on using hashes here.

Provenance

The following attestation bundles were made for gridflow_python_mediator-0.1.1-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