A modern Python web server and web framework designed for high performance and speed using async/await syntax.
—
Sanic's flexible configuration system supports environment variables, configuration files, and programmatic configuration. It provides built-in configuration options for server behavior, security, performance tuning, and custom application settings.
The central configuration management class that handles loading, updating, and accessing configuration values.
class Config:
"""Application configuration management."""
def __init__(self, **kwargs):
"""
Initialize configuration.
Parameters:
- **kwargs: Initial configuration values
"""
def load_environment_vars(self, prefix: str = "SANIC_"):
"""
Load configuration from environment variables.
Parameters:
- prefix: Environment variable prefix
"""
def from_envvar(self, variable_name: str):
"""
Load configuration from environment variable pointing to config file.
Parameters:
- variable_name: Environment variable name
"""
def from_pyfile(self, filename: str):
"""
Load configuration from Python file.
Parameters:
- filename: Configuration file path
"""
def from_object(self, obj):
"""
Load configuration from object or module.
Parameters:
- obj: Configuration object or module
"""
def update_config(self, config: dict):
"""
Update configuration with dictionary values.
Parameters:
- config: Configuration dictionary
"""
def get(self, key: str, default=None):
"""
Get configuration value with default.
Parameters:
- key: Configuration key
- default: Default value if key not found
Returns:
Configuration value
"""
def __getitem__(self, key: str):
"""Get configuration value by key."""
def __setitem__(self, key: str, value):
"""Set configuration value by key."""
def __contains__(self, key: str) -> bool:
"""Check if configuration key exists."""Core server behavior and network configuration options.
# Server Host and Port
HOST: str = "127.0.0.1"
PORT: int = 8000
UNIX: str = None # Unix socket path
# SSL/TLS Configuration
SSL: dict = None
CERT: str = None # SSL certificate path
KEY: str = None # SSL private key path
TLS: dict = None # TLS configuration
# Worker and Process Configuration
WORKERS: int = 1
WORKER_CLASS: str = "sanic.worker.GunicornWorker"
BACKLOG: int = 100
WORKER_CONNECTIONS: int = 1000
WORKER_MAX_REQUESTS: int = 0
WORKER_MAX_REQUESTS_JITTER: int = 0
# Connection and Timeout Settings
KEEP_ALIVE: bool = True
KEEP_ALIVE_TIMEOUT: int = 5
REQUEST_TIMEOUT: int = 60
RESPONSE_TIMEOUT: int = 60
WEBSOCKET_TIMEOUT: int = 10
WEBSOCKET_PING_INTERVAL: int = 20
WEBSOCKET_PING_TIMEOUT: int = 20
# Request Limits
REQUEST_MAX_SIZE: int = 100 * 1024 * 1024 # 100MB
REQUEST_BUFFER_SIZE: int = 65536
REQUEST_MAX_HEADER_SIZE: int = 8192
# Graceful Shutdown
GRACEFUL_SHUTDOWN_TIMEOUT: int = 15.0Configuration options for development, debugging, and testing environments.
# Debug and Development
DEBUG: bool = False
TESTING: bool = False
AUTO_RELOAD: bool = False
AUTO_EXTEND: bool = True
# Logging Configuration
ACCESS_LOG: bool = True
NOISY_EXCEPTIONS: bool = False
USE_UVLOOP: bool = True
USE_UJSON: bool = True
# Development Features
MOTD: bool = True
MOTD_DISPLAY: dict = None
LOGO: str = NoneSecurity-related configuration options for production deployments.
# CORS and Security Headers
CORS: bool = False
CORS_ORIGINS: str = "*"
CORS_METHODS: str = "GET,POST,PUT,DELETE,OPTIONS"
CORS_HEADERS: str = "Origin,Accept,Content-Type,X-Requested-With,X-CSRF-Token"
# Forwarded Headers
FORWARDED_SECRET: str = None
REAL_IP_HEADER: str = None
PROXIES_COUNT: int = None
# Request ID
REQUEST_ID_HEADER: str = "X-Request-ID"Configuration for serving static files and template rendering.
# Static Files
STATIC_URL_PATH: str = "/static"
STATIC_FOLDER: str = "static"
# Template Configuration
TEMPLATES_AUTO_RELOAD: bool = FalseApplication-specific configuration values and custom settings.
# Database Configuration (custom)
DATABASE_URL: str = None
DATABASE_POOL_SIZE: int = 10
DATABASE_POOL_MAX_OVERFLOW: int = 20
# Cache Configuration (custom)
CACHE_TYPE: str = "simple"
CACHE_DEFAULT_TIMEOUT: int = 300
# Application Settings (custom)
SECRET_KEY: str = None
JWT_SECRET_KEY: str = None
JWT_EXPIRATION_DELTA: int = 3600from sanic import Sanic
app = Sanic("MyApp")
# Set configuration values
app.config.DEBUG = True
app.config.HOST = "0.0.0.0"
app.config.PORT = 8080
app.config.WORKERS = 4
# Custom configuration
app.config.DATABASE_URL = "postgresql://user:pass@localhost/mydb"
app.config.SECRET_KEY = "your-secret-key"
if __name__ == "__main__":
app.run()import os
from sanic import Sanic
app = Sanic("MyApp")
# Load environment variables with SANIC_ prefix
app.config.load_environment_vars()
# Custom environment variables
app.config.DATABASE_URL = os.getenv("DATABASE_URL")
app.config.SECRET_KEY = os.getenv("SECRET_KEY")
# Environment variables will be loaded as:
# SANIC_DEBUG=true -> app.config.DEBUG = True
# SANIC_HOST=0.0.0.0 -> app.config.HOST = "0.0.0.0"
# SANIC_PORT=8080 -> app.config.PORT = 8080# config.py
DEBUG = True
HOST = "0.0.0.0"
PORT = 8080
DATABASE_URL = "postgresql://user:pass@localhost/mydb"
SECRET_KEY = "your-secret-key"
# app.py
from sanic import Sanic
app = Sanic("MyApp")
# Load from Python file
app.config.from_pyfile("config.py")
# Or from environment variable pointing to config file
# export MYAPP_CONFIG=/path/to/config.py
app.config.from_envvar("MYAPP_CONFIG")class DevelopmentConfig:
DEBUG = True
HOST = "127.0.0.1"
PORT = 8000
DATABASE_URL = "sqlite:///dev.db"
class ProductionConfig:
DEBUG = False
HOST = "0.0.0.0"
PORT = 80
DATABASE_URL = "postgresql://user:pass@prod-db/mydb"
SSL = {
"cert": "/path/to/cert.pem",
"key": "/path/to/key.pem"
}
# Load configuration from object
app = Sanic("MyApp")
if os.getenv("ENVIRONMENT") == "production":
app.config.from_object(ProductionConfig)
else:
app.config.from_object(DevelopmentConfig)app = Sanic("MyApp")
# Basic SSL configuration
app.config.SSL = {
"cert": "/path/to/certificate.pem",
"key": "/path/to/private_key.pem"
}
# Advanced SSL configuration
app.config.SSL = {
"cert": "/path/to/certificate.pem",
"key": "/path/to/private_key.pem",
"ca_certs": "/path/to/ca_certificates.pem",
"ciphers": "ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20:!aNULL:!MD5:!DSS",
"ssl_version": 2, # ssl.PROTOCOL_TLS
"do_handshake_on_connect": False,
"check_hostname": False
}
# Run with SSL
app.run(host="0.0.0.0", port=8443)from sanic import Sanic
app = Sanic("MyApp")
# Set custom configuration
app.config.update_config({
"DATABASE_POOL_SIZE": 20,
"CACHE_TIMEOUT": 600,
"CUSTOM_FEATURE_ENABLED": True
})
@app.route("/info")
async def app_info(request):
return json({
"debug": request.app.config.DEBUG,
"database_pool_size": request.app.config.DATABASE_POOL_SIZE,
"cache_timeout": request.app.config.get("CACHE_TIMEOUT", 300),
"custom_feature": request.app.config.get("CUSTOM_FEATURE_ENABLED", False)
})from sanic import Sanic
from sanic.exceptions import SanicException
app = Sanic("MyApp")
@app.before_server_start
async def validate_config(app, loop):
"""Validate configuration before starting server."""
required_configs = ["DATABASE_URL", "SECRET_KEY"]
missing_configs = [
config for config in required_configs
if not app.config.get(config)
]
if missing_configs:
raise SanicException(
f"Missing required configuration: {', '.join(missing_configs)}"
)
# Validate specific values
if app.config.get("WORKERS", 1) < 1:
raise SanicException("WORKERS must be at least 1")
if app.config.get("REQUEST_TIMEOUT", 60) < 1:
raise SanicException("REQUEST_TIMEOUT must be positive")Install with Tessl CLI
npx tessl i tessl/pypi-sanic