Structum Lab - Framework DocumentationΒΆ
Framework Version: 0.1.0 (Alpha) Documentation Status: Alpha License: Apache 2.0 Copyright: Β© 2025 PythonWoods
[!NOTE] Nota sul Versionamento: Attualmente il progetto Γ¨ in fase Alpha. Tutti i pacchetti (Core e Plugin) seguono il versionamento sincronizzato (βLockstepβ) del framework principale (structum).
OverviewΒΆ
Structum (lat. struttura): A solid, invisible, and modular foundation for modern Python applications.
Structum Lab is not another web framework, CLI tool, or ORM. Itβs a foundational framework designed to manage application lifecycle, configuration, observability, and plugin ecosystemsβleaving you free to choose your preferred technologies for the final implementation.
PhilosophyΒΆ
Protocol-First Architecture: Built on
typing.Protocolinterfaces, not rigid inheritanceZero Core Dependencies:
structum-coreuses only Python Standard LibraryEnterprise-Ready: Production features (health checks, metrics, graceful shutdown) from day one
Modular by Design: Install only what you need via independent packages
Quick NavigationΒΆ
π Getting StartedΒΆ
π¦ Modules & PluginsΒΆ
Configuration - Multi-layer config with dot-notation
Authentication - JWT, RBAC, password hashing
Database - Connection pooling, transactions, health checks
Observability - Structured logging & Prometheus metrics
Dependency Injection - DI for FastAPI
InstallationΒΆ
Option A: The βBatteries Includedβ Way (Recommended)ΒΆ
Install the Meta-Package. This provides the core foundation and essential orchestrators.
pip install structum
Option B: A La Carte (Advanced)ΒΆ
If you need a minimal footprint (e.g., for AWS Lambda), install only the Core and specific plugins:
# 1. Install the Core (Interfaces only)
pip install structum-core
# 2. Add specific implementations
pip install structum-dynaconf
pip install structum-observability
Development Environment SetupΒΆ
If you are contributing to the framework:
# Clone repository
git clone [https://github.com/PythonWoods/structum.git](https://github.com/PythonWoods/structum.git)
cd structum
# Install Workspace (Links all packages locally)
uv pip install -e .
# Install Meta-Package in editable mode
uv pip install -e packages/meta
Quick StartΒΆ
1. Minimal Example (Core Only)ΒΆ
The configuration system works out-of-the-box without any setup using structum-core:
from structum_lab.config import get_config
# Get the singleton instance
config = get_config()
# Write configuration (automatically persisted)
config.set("server.host", "0.0.0.0")
config.set("server.port", 8080)
# Read configuration (with safe defaults)
host = config.get("server.host", default="localhost")
port = config.get("server.port", default=8000)
print(f"Server starting on {host}:{port}")
2. Production Example (With Plugins)ΒΆ
Full-featured application using structum (Meta):
from structum_lab.config import set_config_provider, get_config
from structum_lab.plugins.dynaconf import DynaconfConfigProvider
from structum_lab.plugins.observability import setup_logging, get_logger
from structum_lab.plugins.bootstrap import SystemBootstrapper, EnvValidator
def setup_application():
"""
Initialize Structum with production features.
"""
# 1. Validation: Ensure environment is ready
boot = SystemBootstrapper()
boot.add_validator(EnvValidator(required=["APP_ENV", "DB_URL"]))
boot.run_or_exit()
# 2. Configuration: Load multi-layer config
provider = DynaconfConfigProvider(root_path=".", env_prefix="MYAPP")
set_config_provider(provider)
# 3. Observability: Setup structured logging
setup_logging()
get_logger(__name__).info("Application initialized")
if __name__ == "__main__":
setup_application()
Project StructureΒΆ
Structum Lab uses a monorepo architecture with distributed packages:
structum/
βββ packages/ # Distribution Packages
β βββ core/ # [structum-core] Protocols & Base
β βββ meta/ # [structum] Meta-package bundle
β βββ dynaconf/ # [structum-dynaconf] Plugin
β βββ observability/ # [structum-observability] Plugin
β βββ auth/ # [structum-auth] Plugin
β βββ database/ # [structum-database] Plugin
β βββ di/ # [structum-di] Plugin
β βββ bootstrap/ # [structum-bootstrap] Plugin
β
βββ demo/ # Example applications
β βββ 01-logging-basics/
β βββ 02-observability-full/
β βββ ...
β
βββ pyproject.toml # Workspace Orchestrator
Architecture OverviewΒΆ
Protocol-Based DesignΒΆ
Structum separates interfaces (protocols) from implementations (plugins):
βββββββββββββββββββββββββββββββββββββββββββ
β Application Code β
β Uses: get_config(), get_logger() β
ββββββββββββββββββββ¬βββββββββββββββββββββββ
β
ββββββββββββββββββββΌβββββββββββββββββββββββ
β Structum Core (structum-core) β
β β’ ConfigProviderInterface β
β β’ LoggerInterface β
β β’ AuthInterface β
β β’ DatabaseInterface β
ββββββββββββββββββββ¬βββββββββββββββββββββββ
β
ββββββββββββββββββββΌβββββββββββββββββββββββ
β Plugin Implementations β
β ββββββββββββ¬βββββββββββ¬βββββββββββ β
β β Dynaconf βObservableβ Auth β β
β β Provider β Logger β Provider β β
β ββββββββββββ΄βββββββββββ΄βββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββ
Benefits:
Testability: Mock providers without changing application code
Flexibility: Switch implementations (JSON β Dynaconf β Vault) without refactoring
Type Safety: Full static type checking with mypy strict mode
(Le sezioni Core Features, Why Structum, Next Steps, Support e License rimangono invariate)
---
#### `docs/guides/enterprise_architecture.md`
```markdown
# ποΈ From Scripting to Enterprise Architecture
> **A Masterclass in Scaling Complexity with Structum**
Structum is designed to accompany you from your first line of code to your millionth. But "Enterprise" isn't just about code sizeβit's about **Risk Management**.
This guide demonstrates how to transition from a "Hope-Based" architecture to a **"Verification-Based"** architecture using `structum-bootstrap` and `structum-di`.
---
## π The "Professional Paranoia" Mindset
In an Enterprise environment (e.g., Banking, Healthcare), system integrity is paramount. Optimization is secondary to **Correctness** and **Auditability**.
1. **Fail Fast**: If a critical configuration or secret is missing, the application must terminate immediately. Silent failures or partial startups lead to undefined states during runtime.
2. **Explicit Dependencies**: No global variables or implicit assumptions. Every service must strictly declare its requirements.
3. **Isolation**: Business logic must be verifiable in isolation, without side effects from the infrastructure layer.
Structum enables this transition through enforced validation and dependency injection.
---
## πΊοΈ The Architecture Map
| Layer | Component | Structum Package | Responsibility |
| :--- | :--- | :--- | :--- |
| **Perimeter** | `main.py` | `structum-bootstrap` | **Validation**. Ensures the environment is safe. |
| **Wiring** | `container.py` | `structum-di` | **Assembly**. Connects components together. |
| **Logic** | `service.py` | (Pure Python) | **Business**. Pure logic, receiving dependencies. |
| **Foundation** | `core` | `structum-core` | **Capabilities**. Protocols, Config, Logs. |
---
## π End-to-End Example: The Secure Payment Processor
Let's build a mocked "Payment Processor" that demands high security.
### 1. The Perimeter (Bootstrap)
We define a strict set of requirements. Note the paranoia: we check everything.
```python
# bootstrap.py
from structum_lab.plugins.bootstrap import SystemBootstrapper, EnvValidator, DirectoryValidator
def verify_environment():
gatekeeper = SystemBootstrapper()
# 1. Secrets: Must exist. (Values are masked in logs)
gatekeeper.add_validator(EnvValidator(required=[
"STRIPE_API_KEY",
"DB_PASSWORD",
"ENCRYPTION_KEY"
]))
# 2. Compliance: Audit log directory must be writable
gatekeeper.add_validator(DirectoryValidator(paths=["/var/log/audit/payments"]))
# RUN. If this fails, the app process exits with code 1.
gatekeeper.run_or_exit()
2. The Logic (Pure Python)ΒΆ
Notice: No imports from Structum. This service is pure business logic. It receives what it needs.
# services/payment.py
class PaymentProcessor:
def __init__(self, api_key: str, audit_logger):
self.api_key = api_key
self.logger = audit_logger
def process_transaction(self, amount: float):
self.logger.info("Processing transaction", amount=amount)
# ... logic ...
3. The Wiring (DI Container)ΒΆ
This is where Structum connects the generic Core (structum-core) to your specific Logic via structum-di.
# container.py
from structum_lab.plugins.di import StructumContainer
from dependency_injector import providers
from .services.payment import PaymentProcessor
class AppContainer(StructumContainer):
# We use Structum's Config Resource to fetch the API Key safely
payment_processor = providers.Factory(
PaymentProcessor,
api_key=StructumContainer.config.provided.payment.stripe_key,
# We inject a specific Logger context for Audit
audit_logger=StructumContainer.logger("audit.payments")
)
4. The EntrypointΒΆ
# main.py
from .bootstrap import verify_environment
from .container import AppContainer
def main():
# 1. FAIL FAST: Verify Environment
verify_environment()
# 2. ASSEMBLE: Create Container
container = AppContainer()
# 3. EXECUTE: Run Application
processor = container.payment_processor()
processor.process_transaction(100.00)
π The Structum Guarantee: Zero Lock-InΒΆ
Important: You are NEVER forced to use the Dependency Injection Container.
All Structum plugins (auth, bootstrap, database, etc.) are designed to be used directly (βStandalone Modeβ). The Container is simply a convenience adapter for those who prefer Clean Architecture.
See the Standalone Demo for proof.