Skip to main content

Modules System Overview

Django-CFG provides a powerful modular system that automatically configures Django services based on your configuration. Modules eliminate boilerplate code and provide production-ready functionality out of the box.

What are Modules?

Modules are auto-configuring services that:

  • 🔧 Auto-discover configuration from your Django-CFG settings
  • ⚡ Zero-setup integration - just import and use
  • 🛡️ Production-ready with error handling and logging
  • 🔌 Extensible - create your own modules easily
  • 📊 Observable - built-in monitoring and health checks

Architecture

Base Module System

All modules inherit from BaseCfgModule:

from django_cfg.modules.base import BaseCfgModule

class MyCustomModule(BaseCfgModule):
def __init__(self):
super().__init__()
self.config = self.get_config() # Auto-discovers Django-CFG config

def my_method(self):
# Access configuration automatically
if hasattr(self.config, 'my_service'):
return self.config.my_service.api_key

Configuration Discovery

Modules automatically find your configuration:

# api/config.py
class MyProjectConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="sendgrid",
sendgrid_api_key=env.email.sendgrid_api_key
)

# Anywhere in your code
from django_cfg import DjangoEmailService

email = DjangoEmailService() # Automatically uses your EmailConfig
email.send_simple("Test", "Hello!", ["user@example.com"])

Built-in Modules

Email Module (DjangoEmailService)

Auto-configuring email service with multiple backends:

from django_cfg import DjangoEmailService

email = DjangoEmailService()

# Simple email
email.send_simple(
subject="Welcome!",
message="Hello World!",
recipient_list=["user@example.com"]
)

# Template-based email
email.send_template(
template_name="welcome_email.html",
context={"user_name": "John"},
recipient_list=["user@example.com"],
subject="Welcome to our platform!"
)

# Bulk email with SendGrid
email.send_bulk_sendgrid(
template_id="d-123456789",
recipients=[
{"email": "user1@example.com", "name": "User 1"},
{"email": "user2@example.com", "name": "User 2"}
],
template_data={"company": "My Company"}
)

Features:

  • ✅ Multiple backends (SMTP, SendGrid, etc.)
  • ✅ Template rendering with Django templates
  • ✅ Bulk email support
  • ✅ Attachment handling
  • ✅ HTML/text alternatives
  • ✅ Error handling and retries

Telegram Module (DjangoTelegram)

Bot integration and notifications:

from django_cfg import DjangoTelegram, send_telegram_message

telegram = DjangoTelegram()

# Send notifications
telegram.send_message(
chat_id="-1001234567890",
text="🚀 Deployment completed successfully!"
)

# Send with formatting
telegram.send_message(
chat_id="@my_channel",
text="*Error Alert*\n`Database connection failed`",
parse_mode="Markdown"
)

# Send files
telegram.send_document(
chat_id="123456789",
document=open("report.pdf", "rb"),
caption="Monthly report"
)

Features: Message sending and formatting, file and media uploads, bot command handling, webhook integration, channel/group management, and error notifications.

🔌 Creating Custom Modules

Basic Custom Module

from django_cfg.modules.base import BaseCfgModule
from typing import Optional

class MyCustomService(BaseCfgModule):
"""Custom service module."""

def __init__(self):
super().__init__()
self.config = self.get_config()
self.my_config = getattr(self.config, 'my_service', None)

def do_something(self) -> str:
"""Perform custom operation."""
if not self.my_config:
raise ValueError("MyService not configured")

# Use configuration
api_key = self.my_config.api_key
base_url = self.my_config.base_url

# Your service logic here
return "Operation completed"

def health_check(self) -> dict:
"""Health check for monitoring."""
try:
# Test your service
result = self.do_something()
return {
"status": "healthy",
"details": "Service is operational"
}
except Exception as e:
return {
"status": "unhealthy",
"details": str(e)
}

Configuration Integration

# api/config.py
from pydantic import BaseModel

class MyServiceConfig(BaseModel):
api_key: str
base_url: str = "https://api.myservice.com"
timeout: int = 30
retries: int = 3

class MyProjectConfig(DjangoConfig):
my_service: MyServiceConfig = MyServiceConfig(
api_key=env.my_service.api_key
)

Best Practices

1. Use Type Hints

from typing import List, Dict, Optional

class MyService(BaseCfgModule):
def process_items(self, items: List[Dict[str, str]]) -> Optional[str]:
pass

2. Handle Configuration Gracefully

def __init__(self):
super().__init__()
self.config = self.get_config()

# Graceful degradation
if not self.config or not hasattr(self.config, 'my_service'):
self.enabled = False
return

self.enabled = True
self.service_config = self.config.my_service

3. Implement Health Checks

def health_check(self) -> dict:
if not self.enabled:
return {"status": "disabled", "details": "Service not configured"}

try:
# Test service connectivity
self._test_connection()
return {"status": "healthy"}
except Exception as e:
return {"status": "unhealthy", "details": str(e)}

4. Add Monitoring and Metrics

import time
from collections import defaultdict

class MonitoredService(BaseCfgModule):
def __init__(self):
super().__init__()
self.metrics = defaultdict(int)
self.response_times = []

def tracked_operation(self, data):
start_time = time.time()

try:
result = self._process(data)
self.metrics["success"] += 1
return result
except Exception as e:
self.metrics["error"] += 1
raise
finally:
duration = time.time() - start_time
self.response_times.append(duration)
self.metrics["total_requests"] += 1

Integration with Django-CFG

Automatic Discovery

Modules automatically discover your Django-CFG configuration:

# No manual configuration needed!
email = DjangoEmailService() # Finds EmailConfig automatically
health = DjangoHealthService() # Finds all health-related configs
telegram = DjangoTelegramService() # Finds TelegramConfig automatically

Configuration Validation

# api/config.py
class MyProjectConfig(DjangoConfig):
email: EmailConfig = EmailConfig(...)

def validate_modules(self):
"""Custom validation for modules."""
# Ensure email is configured for production
if self.is_prod and not self.email.sendgrid_api_key:
raise ValueError("SendGrid API key required for production")

# Validate Telegram config
if hasattr(self, 'telegram') and self.telegram:
if not self.telegram.bot_token:
raise ValueError("Telegram bot token is required")

Explore Modules

Currency & Finance

Communication

AI & Intelligence

Operations

Available Modules:

Configuration & Setup:

Apps Using Modules:

Integrations:

Guides & Tools:

The modular system makes Django-CFG incredibly powerful and flexible while maintaining simplicity! 🚀