Configuration Management¶
Gobstopper provides a comprehensive configuration system that supports multiple sources, environment-based settings, and validation. This guide covers how to configure your Gobstopper applications for different environments.
Quick Start¶
from gobstopper import Gobstopper, Config
# Load configuration automatically
config = Config.load()
# Create app with config
app = Gobstopper()
Configuration Sources¶
Configuration is loaded from multiple sources with the following precedence (highest to lowest):
Environment Variables (highest priority)
Configuration Files (TOML or JSON)
Default Values (lowest priority)
This allows you to have sensible defaults, override them with config files, and further override specific settings with environment variables.
Configuration Files¶
TOML Format (Recommended)¶
Create config.toml in your project root:
env = "development"
debug = true
[server]
host = "127.0.0.1"
port = 8000
workers = 1
[security]
secret_key = "your-secret-key-min-32-chars"
enable_csrf = true
[tasks]
enabled = true
max_workers = 4
JSON Format¶
Create config.json in your project root:
{
"env": "development",
"debug": true,
"server": {
"host": "127.0.0.1",
"port": 8000,
"workers": 1
},
"security": {
"secret_key": "your-secret-key-min-32-chars",
"enable_csrf": true
}
}
Environment-Specific Configs¶
Gobstopper automatically searches for environment-specific configs:
config.{env}.toml(e.g.,config.production.toml)config.tomlconfig.{env}.jsonconfig.json
Set the environment with:
ENVenvironment variableenvparameter inConfig.load()
# Load production config
config = Config.load(env="production")
# Or use environment variable
# ENV=production python app.py
Environment Variables¶
All configuration options can be set via environment variables using the GOBSTOPPER_ prefix:
# Server settings
export GOBSTOPPER_SERVER_HOST=0.0.0.0
export GOBSTOPPER_SERVER_PORT=8080
export GOBSTOPPER_SERVER_WORKERS=4
# Security settings
export GOBSTOPPER_SECRET_KEY="your-production-secret-key"
export GOBSTOPPER_ENABLE_CSRF=true
# Database/storage
export GOBSTOPPER_SESSION_STORAGE_TYPE=redis
export GOBSTOPPER_TASKS_STORAGE_PATH=/data/tasks.db
# Features
export GOBSTOPPER_CORS_ENABLED=true
export GOBSTOPPER_METRICS_ENABLED=true
Configuration Sections¶
Server Configuration¶
@dataclass
class ServerConfig:
host: str = "127.0.0.1"
port: int = 8000
workers: int = 1
interface: str = "rsgi"
log_level: str = "info"
Security Configuration¶
@dataclass
class SecurityConfig:
secret_key: Optional[str] = None
enable_csrf: bool = True
enable_security_headers: bool = True
hsts_max_age: int = 31536000
hsts_include_subdomains: bool = True
csp_policy: str = "default-src 'self'; object-src 'none'"
referrer_policy: str = "strict-origin-when-cross-origin"
coop_policy: str = "same-origin"
coep_policy: str = "require-corp"
cookie_secure: bool = True
cookie_httponly: bool = True
cookie_samesite: str = "Strict"
cookie_max_age: int = 3600
session_storage_type: str = "file"
session_storage_path: Optional[str] = None
CORS Configuration¶
@dataclass
class CORSConfig:
enabled: bool = False
allow_origins: list[str] = ["*"]
allow_methods: list[str] = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
allow_headers: list[str] = ["*"]
allow_credentials: bool = False
max_age: int = 86400
Static Files Configuration¶
@dataclass
class StaticFilesConfig:
enabled: bool = True
url_path: str = "/static"
directory: str = "static"
use_rust: bool = True
Template Configuration¶
@dataclass
class TemplateConfig:
directory: str = "templates"
use_rust: bool = True
auto_reload: bool = False
cache_size: int = 400
Task Configuration¶
@dataclass
class TaskConfig:
enabled: bool = True
storage_type: str = "duckdb"
storage_path: Optional[str] = None
max_workers: int = 4
default_priority: int = 5
enable_retries: bool = True
max_retries: int = 3
cleanup_days: int = 7
Rate Limit Configuration¶
@dataclass
class RateLimitConfig:
enabled: bool = False
default_rate: int = 100
default_period: int = 60
storage_type: str = "memory"
Logging Configuration¶
@dataclass
class LoggingConfig:
level: str = "info"
format: str = "text"
enable_correlation_id: bool = False
log_file: Optional[str] = None
Metrics Configuration¶
@dataclass
class MetricsConfig:
enabled: bool = False
export_type: str = "prometheus"
endpoint: str = "/metrics"
include_hostname: bool = True
Loading Configuration¶
Automatic Loading¶
from gobstopper import Config
# Auto-detect config file and environment
config = Config.load()
Explicit Loading¶
# Load specific file
config = Config.load(config_file="config.production.toml")
# Load specific environment
config = Config.load(env="production")
# Disable auto-detection
config = Config.load(auto_detect=False)
Validation¶
Validate your configuration before starting the app:
config = Config.load()
# Validate and get list of issues
issues = config.validate()
if issues:
for issue in issues:
print(f"Config issue: {issue}")
# Check for critical issues
critical = [i for i in issues if i.startswith("CRITICAL:")]
if critical:
raise ValueError("Configuration has critical issues")
Production Configuration¶
For production deployments, follow these best practices:
1. Set Environment¶
export ENV=production
2. Use Secure Secret Key¶
# Generate a secure key
export GOBSTOPPER_SECRET_KEY=$(python -c "import secrets; print(secrets.token_urlsafe(32))")
3. Production Config File¶
Create config.production.toml:
env = "production"
debug = false
[server]
host = "0.0.0.0"
port = 8000
workers = 4
log_level = "warning"
[security]
# Set via environment variable
enable_csrf = true
enable_security_headers = true
cookie_secure = true
cookie_httponly = true
cookie_samesite = "Strict"
session_storage_type = "sql"
[cors]
enabled = true
allow_origins = ["https://yourdomain.com"]
allow_credentials = true
[templates]
auto_reload = false
cache_size = 1000
[logging]
level = "warning"
format = "json"
enable_correlation_id = true
[metrics]
enabled = true
4. Production Checklist¶
The config validation will warn you about:
✅ Secret key is set and at least 32 characters
✅ Debug mode is disabled
✅ Cookie secure flag is enabled
✅ Template auto-reload is disabled
✅ Appropriate session storage (not memory)
✅ HTTPS settings are enabled
✅ Security headers are enabled
Custom Configuration¶
Add custom application-specific configuration:
[custom]
app_name = "My App"
max_upload_size = 10485760
feature_flags = { experimental = false, beta = true }
Access custom config:
config = Config.load()
app_name = config.custom.get("app_name", "Default App")
max_upload = config.custom.get("max_upload_size", 5242880)
Docker Integration¶
In Docker, use environment variables:
ENV ENV=production
ENV GOBSTOPPER_SERVER_HOST=0.0.0.0
ENV GOBSTOPPER_SERVER_WORKERS=4
ENV GOBSTOPPER_SECRET_KEY=${SECRET_KEY}
Or mount config file:
COPY config.production.toml /app/config.toml
Configuration as Code¶
For programmatic configuration:
from gobstopper import Config, ServerConfig, SecurityConfig
# Build config manually
config = Config(
env="production",
debug=False,
server=ServerConfig(
host="0.0.0.0",
port=8000,
workers=4
),
security=SecurityConfig(
secret_key="your-secret-key",
enable_csrf=True
)
)
# Validate
issues = config.validate()
if issues:
print("Configuration issues:", issues)
Best Practices¶
Never commit secrets - Use environment variables for sensitive data
Use environment-specific configs -
config.production.toml,config.development.tomlValidate in CI/CD - Run
config.validate()in your deployment pipelineUse TOML for readability - TOML is easier to read and write than JSON
Document custom settings - Add comments to your config files
Start with defaults - Only override what you need
Test configs - Have separate test configs with test databases
Troubleshooting¶
Config file not found¶
Gobstopper automatically searches for config files. If none found, it uses defaults.
# Explicitly specify config file
config = Config.load(config_file="path/to/config.toml")
Environment variables not working¶
Ensure you use the GOBSTOPPER_ prefix and correct section names:
# Correct
export GOBSTOPPER_SERVER_PORT=8080
# Incorrect (won't work)
export SERVER_PORT=8080
Secret key warnings¶
In production, you’ll get a critical warning if secret key is missing:
config = Config.load(env="production")
issues = config.validate()
# ['CRITICAL: secret_key is required in production']
Set it via environment variable:
export GOBSTOPPER_SECRET_KEY="$(python -c 'import secrets; print(secrets.token_urlsafe(32))')"
Migration from Legacy Config¶
If you’re using hardcoded values or environment variables directly:
Before¶
import os
app = Gobstopper(
secret_key=os.getenv("SECRET_KEY"),
debug=True
)
After¶
from gobstopper import Gobstopper, Config
config = Config.load()
app = Gobstopper() # Config automatically loaded
API Reference¶
See the API documentation for complete details on all configuration options and the Config API.