0
# Configuration
1
2
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.
3
4
## Capabilities
5
6
### Config Class
7
8
The central configuration management class that handles loading, updating, and accessing configuration values.
9
10
```python { .api }
11
class Config:
12
"""Application configuration management."""
13
14
def __init__(self, **kwargs):
15
"""
16
Initialize configuration.
17
18
Parameters:
19
- **kwargs: Initial configuration values
20
"""
21
22
def load_environment_vars(self, prefix: str = "SANIC_"):
23
"""
24
Load configuration from environment variables.
25
26
Parameters:
27
- prefix: Environment variable prefix
28
"""
29
30
def from_envvar(self, variable_name: str):
31
"""
32
Load configuration from environment variable pointing to config file.
33
34
Parameters:
35
- variable_name: Environment variable name
36
"""
37
38
def from_pyfile(self, filename: str):
39
"""
40
Load configuration from Python file.
41
42
Parameters:
43
- filename: Configuration file path
44
"""
45
46
def from_object(self, obj):
47
"""
48
Load configuration from object or module.
49
50
Parameters:
51
- obj: Configuration object or module
52
"""
53
54
def update_config(self, config: dict):
55
"""
56
Update configuration with dictionary values.
57
58
Parameters:
59
- config: Configuration dictionary
60
"""
61
62
def get(self, key: str, default=None):
63
"""
64
Get configuration value with default.
65
66
Parameters:
67
- key: Configuration key
68
- default: Default value if key not found
69
70
Returns:
71
Configuration value
72
"""
73
74
def __getitem__(self, key: str):
75
"""Get configuration value by key."""
76
77
def __setitem__(self, key: str, value):
78
"""Set configuration value by key."""
79
80
def __contains__(self, key: str) -> bool:
81
"""Check if configuration key exists."""
82
```
83
84
### Server Configuration
85
86
Core server behavior and network configuration options.
87
88
```python { .api }
89
# Server Host and Port
90
HOST: str = "127.0.0.1"
91
PORT: int = 8000
92
UNIX: str = None # Unix socket path
93
94
# SSL/TLS Configuration
95
SSL: dict = None
96
CERT: str = None # SSL certificate path
97
KEY: str = None # SSL private key path
98
TLS: dict = None # TLS configuration
99
100
# Worker and Process Configuration
101
WORKERS: int = 1
102
WORKER_CLASS: str = "sanic.worker.GunicornWorker"
103
BACKLOG: int = 100
104
WORKER_CONNECTIONS: int = 1000
105
WORKER_MAX_REQUESTS: int = 0
106
WORKER_MAX_REQUESTS_JITTER: int = 0
107
108
# Connection and Timeout Settings
109
KEEP_ALIVE: bool = True
110
KEEP_ALIVE_TIMEOUT: int = 5
111
REQUEST_TIMEOUT: int = 60
112
RESPONSE_TIMEOUT: int = 60
113
WEBSOCKET_TIMEOUT: int = 10
114
WEBSOCKET_PING_INTERVAL: int = 20
115
WEBSOCKET_PING_TIMEOUT: int = 20
116
117
# Request Limits
118
REQUEST_MAX_SIZE: int = 100 * 1024 * 1024 # 100MB
119
REQUEST_BUFFER_SIZE: int = 65536
120
REQUEST_MAX_HEADER_SIZE: int = 8192
121
122
# Graceful Shutdown
123
GRACEFUL_SHUTDOWN_TIMEOUT: int = 15.0
124
```
125
126
### Development and Debugging
127
128
Configuration options for development, debugging, and testing environments.
129
130
```python { .api }
131
# Debug and Development
132
DEBUG: bool = False
133
TESTING: bool = False
134
AUTO_RELOAD: bool = False
135
AUTO_EXTEND: bool = True
136
137
# Logging Configuration
138
ACCESS_LOG: bool = True
139
NOISY_EXCEPTIONS: bool = False
140
USE_UVLOOP: bool = True
141
USE_UJSON: bool = True
142
143
# Development Features
144
MOTD: bool = True
145
MOTD_DISPLAY: dict = None
146
LOGO: str = None
147
```
148
149
### Security Configuration
150
151
Security-related configuration options for production deployments.
152
153
```python { .api }
154
# CORS and Security Headers
155
CORS: bool = False
156
CORS_ORIGINS: str = "*"
157
CORS_METHODS: str = "GET,POST,PUT,DELETE,OPTIONS"
158
CORS_HEADERS: str = "Origin,Accept,Content-Type,X-Requested-With,X-CSRF-Token"
159
160
# Forwarded Headers
161
FORWARDED_SECRET: str = None
162
REAL_IP_HEADER: str = None
163
PROXIES_COUNT: int = None
164
165
# Request ID
166
REQUEST_ID_HEADER: str = "X-Request-ID"
167
```
168
169
### Static Files and Templates
170
171
Configuration for serving static files and template rendering.
172
173
```python { .api }
174
# Static Files
175
STATIC_URL_PATH: str = "/static"
176
STATIC_FOLDER: str = "static"
177
178
# Template Configuration
179
TEMPLATES_AUTO_RELOAD: bool = False
180
```
181
182
### Custom Configuration
183
184
Application-specific configuration values and custom settings.
185
186
```python { .api }
187
# Database Configuration (custom)
188
DATABASE_URL: str = None
189
DATABASE_POOL_SIZE: int = 10
190
DATABASE_POOL_MAX_OVERFLOW: int = 20
191
192
# Cache Configuration (custom)
193
CACHE_TYPE: str = "simple"
194
CACHE_DEFAULT_TIMEOUT: int = 300
195
196
# Application Settings (custom)
197
SECRET_KEY: str = None
198
JWT_SECRET_KEY: str = None
199
JWT_EXPIRATION_DELTA: int = 3600
200
```
201
202
## Usage Examples
203
204
### Basic Configuration Setup
205
206
```python
207
from sanic import Sanic
208
209
app = Sanic("MyApp")
210
211
# Set configuration values
212
app.config.DEBUG = True
213
app.config.HOST = "0.0.0.0"
214
app.config.PORT = 8080
215
app.config.WORKERS = 4
216
217
# Custom configuration
218
app.config.DATABASE_URL = "postgresql://user:pass@localhost/mydb"
219
app.config.SECRET_KEY = "your-secret-key"
220
221
if __name__ == "__main__":
222
app.run()
223
```
224
225
### Environment Variable Configuration
226
227
```python
228
import os
229
from sanic import Sanic
230
231
app = Sanic("MyApp")
232
233
# Load environment variables with SANIC_ prefix
234
app.config.load_environment_vars()
235
236
# Custom environment variables
237
app.config.DATABASE_URL = os.getenv("DATABASE_URL")
238
app.config.SECRET_KEY = os.getenv("SECRET_KEY")
239
240
# Environment variables will be loaded as:
241
# SANIC_DEBUG=true -> app.config.DEBUG = True
242
# SANIC_HOST=0.0.0.0 -> app.config.HOST = "0.0.0.0"
243
# SANIC_PORT=8080 -> app.config.PORT = 8080
244
```
245
246
### Configuration from File
247
248
```python
249
# config.py
250
DEBUG = True
251
HOST = "0.0.0.0"
252
PORT = 8080
253
DATABASE_URL = "postgresql://user:pass@localhost/mydb"
254
SECRET_KEY = "your-secret-key"
255
256
# app.py
257
from sanic import Sanic
258
259
app = Sanic("MyApp")
260
261
# Load from Python file
262
app.config.from_pyfile("config.py")
263
264
# Or from environment variable pointing to config file
265
# export MYAPP_CONFIG=/path/to/config.py
266
app.config.from_envvar("MYAPP_CONFIG")
267
```
268
269
### Configuration Object
270
271
```python
272
class DevelopmentConfig:
273
DEBUG = True
274
HOST = "127.0.0.1"
275
PORT = 8000
276
DATABASE_URL = "sqlite:///dev.db"
277
278
class ProductionConfig:
279
DEBUG = False
280
HOST = "0.0.0.0"
281
PORT = 80
282
DATABASE_URL = "postgresql://user:pass@prod-db/mydb"
283
SSL = {
284
"cert": "/path/to/cert.pem",
285
"key": "/path/to/key.pem"
286
}
287
288
# Load configuration from object
289
app = Sanic("MyApp")
290
if os.getenv("ENVIRONMENT") == "production":
291
app.config.from_object(ProductionConfig)
292
else:
293
app.config.from_object(DevelopmentConfig)
294
```
295
296
### SSL/TLS Configuration
297
298
```python
299
app = Sanic("MyApp")
300
301
# Basic SSL configuration
302
app.config.SSL = {
303
"cert": "/path/to/certificate.pem",
304
"key": "/path/to/private_key.pem"
305
}
306
307
# Advanced SSL configuration
308
app.config.SSL = {
309
"cert": "/path/to/certificate.pem",
310
"key": "/path/to/private_key.pem",
311
"ca_certs": "/path/to/ca_certificates.pem",
312
"ciphers": "ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20:!aNULL:!MD5:!DSS",
313
"ssl_version": 2, # ssl.PROTOCOL_TLS
314
"do_handshake_on_connect": False,
315
"check_hostname": False
316
}
317
318
# Run with SSL
319
app.run(host="0.0.0.0", port=8443)
320
```
321
322
### Custom Configuration Access
323
324
```python
325
from sanic import Sanic
326
327
app = Sanic("MyApp")
328
329
# Set custom configuration
330
app.config.update_config({
331
"DATABASE_POOL_SIZE": 20,
332
"CACHE_TIMEOUT": 600,
333
"CUSTOM_FEATURE_ENABLED": True
334
})
335
336
@app.route("/info")
337
async def app_info(request):
338
return json({
339
"debug": request.app.config.DEBUG,
340
"database_pool_size": request.app.config.DATABASE_POOL_SIZE,
341
"cache_timeout": request.app.config.get("CACHE_TIMEOUT", 300),
342
"custom_feature": request.app.config.get("CUSTOM_FEATURE_ENABLED", False)
343
})
344
```
345
346
### Configuration Validation
347
348
```python
349
from sanic import Sanic
350
from sanic.exceptions import SanicException
351
352
app = Sanic("MyApp")
353
354
@app.before_server_start
355
async def validate_config(app, loop):
356
"""Validate configuration before starting server."""
357
358
required_configs = ["DATABASE_URL", "SECRET_KEY"]
359
missing_configs = [
360
config for config in required_configs
361
if not app.config.get(config)
362
]
363
364
if missing_configs:
365
raise SanicException(
366
f"Missing required configuration: {', '.join(missing_configs)}"
367
)
368
369
# Validate specific values
370
if app.config.get("WORKERS", 1) < 1:
371
raise SanicException("WORKERS must be at least 1")
372
373
if app.config.get("REQUEST_TIMEOUT", 60) < 1:
374
raise SanicException("REQUEST_TIMEOUT must be positive")
375
```