Port from .NET to Python of the Neuroglia Framework
Project description
Neuroglia Python Framework
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
Quick Links
- ๐ Getting Started - Set up your first Neuroglia application
- ๐๏ธ Architecture Guide - Understanding the framework's architecture
- ๐ Dependency Injection - Service container and DI patterns
- ๐ฏ CQRS & Mediation - Command and Query handling
- ๐๏ธ Persistence Patterns - Domain events with state persistence
- ๐ง Pipeline Behaviors - Cross-cutting concerns and middleware
- ๐ฏ Resource Oriented Architecture - Declarative resource management patterns
- ๐ MVC Controllers - Building REST APIs
- ๐๏ธ Data Access - Repository pattern and data persistence
- ๐ก Event Handling - CloudEvents and reactive programming
- ๐ Object Mapping - Mapping between different object types
- ๐ญ Observability - OpenTelemetry integration and monitoring
Sample Applications
Learn by example with complete sample applications:
- ๐ Mario's Pizzeria - Complete pizzeria management system with UI, authentication, and observability
- ๐ฆ OpenBank - Event-sourced banking domain with CQRS and EventStoreDB
- ๐งช Lab Resource Manager - Resource Oriented Architecture with watchers and reconciliation
- ๐ฅ๏ธ Desktop Controller - Remote desktop management API
- ๐ช API Gateway - Microservice gateway with authentication
๐ณ Quick Start with Docker
The fastest way to explore Neuroglia is through our sample applications with Docker:
Prerequisites
- Docker and Docker Compose installed
- Git (to clone the repository)
Get Started in 3 Steps
# 1. Clone the repository
git clone https://github.com/bvandewe/pyneuro.git
cd pyneuro
# 2. Start Mario's Pizzeria (includes shared infrastructure)
./mario-pizzeria start
# 3. Access the application
# ๐ Application: http://localhost:8080
# ๐ API Docs: http://localhost:8080/api/docs
# ๐ Keycloak: http://localhost:8090 (admin/admin)
Available Sample Applications
Each sample comes with its own CLI tool for easy management:
# Mario's Pizzeria (State-based persistence + UI)
./mario-pizzeria start
./mario-pizzeria stop
./mario-pizzeria logs
# OpenBank (Event Sourcing with EventStoreDB)
./openbank start
./openbank stop
./openbank logs
# Simple UI Demo (Authentication patterns)
./simple-ui start
./simple-ui stop
./simple-ui logs
Shared Infrastructure
All samples share common infrastructure services:
- ๏ฟฝ๏ธ MongoDB: Database (port 27017)
- ๏ฟฝ MongoDB Express: Database UI (port 8081)
- ๐ Keycloak: Authentication (port 8090)
- ๐ฌ Event Player: Event visualization (port 8085)
- ๐ Grafana: Dashboards (port 3001)
- ๐ Prometheus: Metrics (port 9090)
- ๐ Loki: Logs aggregation
- ๐ Tempo: Distributed tracing (port 3200)
The shared infrastructure starts automatically with your first sample application.
Service Ports
| Sample | Port | Debug Port | Description |
|---|---|---|---|
| Mario's Pizzeria | 8080 | 5678 | Full-featured pizzeria management |
| OpenBank | 8899 | 5699 | Event-sourced banking with EventStore |
| Simple UI | 8082 | 5680 | Authentication patterns demo |
| EventStoreDB | 2113 | - | Event sourcing database (OpenBank) |
| MongoDB Express | 8081 | - | Database admin UI |
| Keycloak | 8090 | - | SSO/OAuth2 server |
| Event Player | 8085 | - | CloudEvents visualization |
| Grafana | 3001 | - | Observability dashboards |
| Prometheus | 9090 | - | Metrics collection |
| Tempo | 3200 | - | Trace visualization |
Test Credentials
The samples come with pre-configured test users:
Admin: admin / admin123
Manager: manager / manager123
Chef: chef / chef123
Driver: driver / driver123
Customer: customer / customer123
Learn More
For detailed deployment documentation, see:
- ๐ Getting Started Guide - Complete setup walkthrough
- ๐ณ Docker Architecture - Infrastructure details
- ๐ Mario's Pizzeria Tutorial - Step-by-step guide
- ๐ฆ OpenBank Guide - Event sourcing patterns
๐ง Quick Start
# Install from PyPI
pip install neuroglia-python
# 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 |
|---|---|---|
| Dependency Injection | Service container and registration | ๐ DI |
| Hosting | Web application hosting and lifecycle | ๐ Hosting |
| MVC | Controllers and routing | ๐ MVC |
| Mediation | CQRS, commands, queries, events | ๐ CQRS |
| Persistence | Domain events with state persistence | ๐ 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 |
| Observability | OpenTelemetry, tracing, metrics | ๐ Observability |
๐ Requirements
- Python 3.9+
- 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file neuroglia_python-0.9.0.tar.gz.
File metadata
- Download URL: neuroglia_python-0.9.0.tar.gz
- Upload date:
- Size: 246.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.1 CPython/3.10.10 Darwin/24.6.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dd87b449dd28bbddf67cc79e96e7213f3230bf4cc7dde17545858de6a12ba53f
|
|
| MD5 |
572d6d3752471cd5c2dfc3696fbc0de3
|
|
| BLAKE2b-256 |
00795bf21d714daf0f2090c0d59960d01a2ce45894e8fb1372a6bae2c76cccc4
|
File details
Details for the file neuroglia_python-0.9.0-py3-none-any.whl.
File metadata
- Download URL: neuroglia_python-0.9.0-py3-none-any.whl
- Upload date:
- Size: 314.6 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cf1634882b7d23781cb30fc260632b3b0c6bf2a50d5f7403bb775e8bc0091fb5
|
|
| MD5 |
b71aa8ebc3de0fe82cb32c77b2686b38
|
|
| BLAKE2b-256 |
ff767687a80bf385fa700bb6a80e7730d5004115f91dfb2616e34f5a2bc5ae58
|