Skip to main content

Port from .NET to Python of the Neuroglia Framework

Project description

Neuroglia Python Framework

PyPI version Python Version License Documentation Changelog Poetry Docker pre-commit Code style: black FastAPI GitHub

Neuroglia is a lightweight, opinionated framework built on top of FastAPI that provides a comprehensive set of tools and patterns for building clean, maintainable, and scalable microservices. It enforces architectural best practices and provides out-of-the-box implementations of common patterns.

๐Ÿ“š Read the full documentation at bvandewe.github.io/pyneuro/ ๐Ÿ“š

Why Neuroglia?

Choose Neuroglia for complex, domain-driven microservices that need to be maintained for years to come.

๐ŸŽฏ The Philosophy

Neuroglia believes that software architecture matters more than speed of initial development. While you can build APIs quickly with vanilla FastAPI or Django, Neuroglia is designed for applications that will:

  • Scale in complexity over time with changing business requirements
  • Be maintained by teams with varying levels of domain expertise
  • Evolve and adapt without accumulating technical debt
  • Integrate seamlessly with complex enterprise ecosystems

๐Ÿ—๏ธ When to Choose Neuroglia

Choose Neuroglia When Choose Alternatives When
โœ… Building domain-rich applications with complex business logic โŒ Creating simple CRUD APIs or prototypes
โœ… Long-term maintenance is a primary concern โŒ You need something working "yesterday"
โœ… Your team values architectural consistency โŒ Framework learning curve is a blocker
โœ… You need enterprise patterns (CQRS, DDD, Event Sourcing) โŒ Simple request-response patterns suffice
โœ… Multiple developers will work on the codebase โŒ Solo development or small, simple projects
โœ… Integration with event-driven architectures โŒ Monolithic, database-first applications

๐Ÿš€ The Neuroglia Advantage

Compared to vanilla FastAPI:

  • Enforced Structure: No more "how should I organize this?" - clear architectural layers
  • Built-in Patterns: CQRS, dependency injection, and event handling out of the box
  • Enterprise Ready: Designed for complex domains, not just API endpoints

Compared to Django:

  • Microservice Native: Built for distributed systems, not monolithic web apps
  • Domain-Driven: Business logic lives in the domain layer, not mixed with web concerns
  • Modern Async: Full async support without retrofitting legacy patterns

Compared to Spring Boot (Java):

  • Python Simplicity: All the enterprise patterns without Java's verbosity
  • Lightweight: No heavy application server - just the patterns you need
  • Developer Experience: Pythonic APIs with comprehensive tooling

๐Ÿ’ก Real-World Scenarios

Perfect for:

  • ๐Ÿฆ Financial Services: Complex domain rules, audit trails, event sourcing
  • ๐Ÿฅ Healthcare Systems: HIPAA compliance, complex workflows, integration needs
  • ๐Ÿญ Manufacturing: Resource management, real-time monitoring, process orchestration
  • ๐Ÿ›’ E-commerce Platforms: Order processing, inventory management, payment flows
  • ๐ŸŽฏ SaaS Products: Multi-tenant architectures, feature flags, usage analytics

Not ideal for:

  • ๐Ÿ“ Simple content management systems
  • ๐Ÿ”— Basic API proxies or data transformation services
  • ๐Ÿ“ฑ Mobile app backends with minimal business logic
  • ๐Ÿงช Proof-of-concept or throwaway prototypes

๐ŸŽจ The Developer Experience

Neuroglia optimizes for code that tells a story:

# Your business logic is clear and testable
class PlaceOrderHandler(CommandHandler[PlaceOrderCommand, OperationResult[OrderDto]]):
    async def handle_async(self, command: PlaceOrderCommand) -> OperationResult[OrderDto]:
        # Domain logic is explicit and isolated
        order = Order(command.customer_id, command.items)
        await self.repository.save_async(order)
        return self.created(self.mapper.map(order, OrderDto))

# Infrastructure concerns are separated
class OrdersController(ControllerBase):
    @post("/orders", response_model=OrderDto)
    async def place_order(self, command: PlaceOrderCommand) -> OrderDto:
        return await self.mediator.execute_async(command)

The result? Code that's easy to understand, test, and evolve - even years later.

๐Ÿš€ Key Features

  • ๐Ÿ—๏ธ Clean Architecture: Enforces separation of concerns with clearly defined layers (API, Application, Domain, Integration)
  • ๐Ÿ’‰ Dependency Injection: Lightweight container with automatic service discovery and registration
  • ๐ŸŽฏ CQRS & Mediation: Command Query Responsibility Segregation with built-in mediator pattern
  • ๐Ÿ›๏ธ State-Based Persistence: Alternative to event sourcing with automatic domain event dispatching
  • ๐Ÿ”ง Pipeline Behaviors: Cross-cutting concerns like validation, caching, and transactions
  • ๐Ÿ“ก Event-Driven Architecture: Native support for CloudEvents, event sourcing, and reactive programming
  • ๐ŸŽฏ Resource Oriented Architecture: Declarative resource management with watchers, controllers, and reconciliation loops
  • ๐Ÿ”Œ MVC Controllers: Class-based API controllers with automatic discovery and OpenAPI generation
  • ๐Ÿ—„๏ธ Repository Pattern: Flexible data access layer with support for MongoDB, Event Store, and in-memory repositories
  • ๐Ÿ“Š Object Mapping: Bidirectional mapping between domain models and DTOs
  • โšก Reactive Programming: Built-in support for RxPy and asynchronous event handling
  • ๐Ÿ”ง 12-Factor Compliance: Implements all 12-Factor App principles
  • ๐Ÿ“ Rich Serialization: JSON serialization with advanced features

๐ŸŽฏ Architecture Overview

Neuroglia promotes a clean, layered architecture that separates concerns and makes your code more maintainable:

src/
โ”œโ”€โ”€ api/           # ๐ŸŒ API Layer (Controllers, DTOs, Routes)
โ”œโ”€โ”€ application/   # ๐Ÿ’ผ Application Layer (Commands, Queries, Handlers, Services)
โ”œโ”€โ”€ domain/        # ๐Ÿ›๏ธ Domain Layer (Entities, Value Objects, Business Rules)
โ””โ”€โ”€ integration/   # ๐Ÿ”Œ Integration Layer (External APIs, Repositories, Infrastructure)

๐Ÿ“š Documentation

๐Ÿ“– Complete Documentation

Quick Links

Sample Applications

Learn by example with complete sample applications:

๐Ÿณ Docker Development Environment

Get started quickly with Mario's Pizzeria using Docker:

# Start the complete development environment
./mario-docker.sh start

# Access services:
# ๐Ÿ• API Documentation: http://localhost:8080/api/docs
# ๐Ÿ—„๏ธ Database Admin: http://localhost:8081
# ๐Ÿ” Authentication: http://localhost:8090/admin

The Docker environment includes MongoDB (with Mongo Express), Keycloak IDP, Event Player, and other Open Telemetry services (OTEL Collector, Grafana, Prometheus, Loki, Tempo) for a complete development experience.

See deployment/README-mario-docker.md for full details.

๐Ÿ”ง Quick Start

# Install from PyPI
pip install neuroglia

# Or install from source
git clone <repository-url>
cd pyneuro
pip install -e .

Create your first application:

from neuroglia.hosting.web import WebApplicationBuilder

# Create and configure the application
builder = WebApplicationBuilder()
builder.add_controllers(["api.controllers"])

# Build and run
app = builder.build()
app.use_controllers()
app.run()

๐Ÿ—๏ธ Framework Components

Component Purpose Documentation
Core Base types, utilities, module loading ๐Ÿ“– Core
Dependency Injection Service container and registration ๐Ÿ“– DI
Hosting Web application hosting and lifecycle ๐Ÿ“– Hosting
MVC Controllers and routing ๐Ÿ“– MVC
Mediation CQRS, commands, queries, events ๐Ÿ“– Mediation
State Persistence Domain events with state persistence ๐Ÿ“– State Persistence
Pipeline Behaviors Cross-cutting concerns, middleware ๐Ÿ“– Behaviors
Resource Oriented Architecture Watchers, controllers, reconciliation ๐Ÿ“– ROA
Data Repository pattern, event sourcing ๐Ÿ“– Data
Eventing CloudEvents, pub/sub, reactive ๐Ÿ“– Events
Mapping Object-to-object mapping ๐Ÿ“– Mapping
Serialization JSON and other serialization ๐Ÿ“– Serialization

๐Ÿ“‹ Requirements

  • Python 3.11+
  • FastAPI
  • Pydantic
  • RxPy (for reactive features)
  • Motor (for MongoDB support)
  • Additional dependencies based on features used

๐Ÿงช Testing

Neuroglia includes a comprehensive test suite covering all framework features with both unit and integration tests.

Running Tests

Run All Tests

# Run the complete test suite
pytest

# Run with coverage report
pytest --cov=neuroglia --cov-report=html --cov-report=term

# Run in parallel for faster execution
pytest -n auto

Run Specific Test Categories

# Run only unit tests
pytest tests/unit/

# Run only integration tests
pytest tests/integration/

# Run tests by marker
pytest -m "unit"
pytest -m "integration"
pytest -m "slow"

Run Feature-Specific Tests

# Test dependency injection
pytest tests/unit/test_dependency_injection.py

# Test CQRS and mediation
pytest tests/unit/test_cqrs_mediation.py

# Test data access layer
pytest tests/unit/test_data_access.py

# Test object mapping
pytest tests/unit/test_mapping.py

# Run integration tests
pytest tests/integration/test_full_framework.py

Test Coverage

Our test suite provides comprehensive coverage of the framework:

  • Unit Tests: >95% coverage for core framework components
  • Integration Tests: End-to-end workflow validation
  • Performance Tests: Load testing for critical paths
  • Sample Application Tests: Real-world usage scenarios

Test Organization

tests/
โ”œโ”€โ”€ unit/              # ๐Ÿ”ฌ Unit tests for individual components
โ”œโ”€โ”€ integration/       # ๐Ÿ”— Integration tests for workflows
โ”œโ”€โ”€ fixtures/          # ๐Ÿ› ๏ธ Shared test fixtures and utilities
โ””โ”€โ”€ conftest.py       # โš™๏ธ pytest configuration

What's Tested

  • Basic dependency injection service registration and resolution
  • CQRS command and query handling through the mediator
  • Object mapping between different types
  • Repository pattern with various backend implementations
  • Full framework integration workflows

Test Fixtures

We provide comprehensive test fixtures for:

  • Dependency injection container setup
  • Sample services and repositories
  • Mock data and test entities
  • Configuration and settings

Known Test Limitations

  • Some dependency injection features (like strict service lifetimes) may have implementation-specific behavior
  • MongoDB integration tests require a running MongoDB instance
  • Event Store tests require EventStoreDB connection

Adding Tests

When contributing, please include tests for new features:

import pytest
from neuroglia.dependency_injection import ServiceCollection

class TestNewFeature:

    @pytest.mark.unit
    def test_my_unit_feature(self):
        """Test individual component"""
        result = self.service.do_something()
        assert result == expected_value

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

๐Ÿ“„ License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

๐Ÿ“– Documentation

Complete documentation is available at https://bvandewe.github.io/pyneuro/

Disclaimer

This project was the opportunity for me (cdavernas) to learn Python while porting some of the concepts and services of the .NET version of the Neuroglia Framework

Packaging

# Set `package-mode = true` in pyproject.toml
# Set the version tag in pyproject.toml
# Commit changes
# Create API Token in pypi.org...
# Configure credentials for pypi registry:
poetry config pypi-token.pypi  {pypi-....mytoken}
# Build package locally
poetry build
# Publish package to pypi.org:
poetry publish

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

neuroglia_python-0.5.0.tar.gz (185.8 kB view details)

Uploaded Source

Built Distribution

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

neuroglia_python-0.5.0-py3-none-any.whl (240.1 kB view details)

Uploaded Python 3

File details

Details for the file neuroglia_python-0.5.0.tar.gz.

File metadata

  • Download URL: neuroglia_python-0.5.0.tar.gz
  • Upload date:
  • Size: 185.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.10.10 Darwin/24.6.0

File hashes

Hashes for neuroglia_python-0.5.0.tar.gz
Algorithm Hash digest
SHA256 a88775e39e9f82d32fa0a1ec83b317b6a99dabb7664389144d818d5b3b7daf7f
MD5 ee9a65773181d5c873739404b3b81919
BLAKE2b-256 1f5f9601168503ab07aaafa39a8cd533a349c12a127550a040dd07855169c219

See more details on using hashes here.

File details

Details for the file neuroglia_python-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: neuroglia_python-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 240.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.10.10 Darwin/24.6.0

File hashes

Hashes for neuroglia_python-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 92fb98a0eb5d339b24cdc0b34455519c68483cdfd36b9adb687f55a722efe472
MD5 22f6e9cc046484ca08b21febdc2b5f61
BLAKE2b-256 4dee0dead62f5f01a02e1d2fdb7c24ed46344865ac5b9d299ee663fef6deb86b

See more details on using hashes here.

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