0
# Configuration
1
2
Hypercorn's configuration system provides comprehensive control over all server behavior through the Config class. The configuration can be loaded from various sources including Python files, TOML files, dictionaries, or set programmatically.
3
4
## Capabilities
5
6
### Config Class
7
8
The primary configuration class that manages all server settings including network binding, SSL/TLS configuration, worker settings, logging options, and protocol-specific parameters.
9
10
```python { .api }
11
class Config:
12
"""
13
Main configuration class for Hypercorn server.
14
15
Contains all configuration options for server behavior, networking,
16
SSL/TLS, logging, and protocol settings.
17
"""
18
19
def __init__(self):
20
# Network binding
21
self.bind: list[str] # Server binding addresses
22
self.insecure_bind: list[str] # HTTP-only binding addresses
23
self.quic_bind: list[str] # HTTP/3 QUIC binding addresses
24
25
# SSL/TLS Configuration
26
self.certfile: str | None # SSL certificate file path
27
self.keyfile: str | None # SSL private key file path
28
self.keyfile_password: str | None # SSL private key password
29
self.ca_certs: str | None # CA certificate file path
30
self.ciphers: str # SSL cipher configuration
31
self.verify_mode: ssl.VerifyMode | None # SSL certificate verification mode
32
self.verify_flags: ssl.VerifyFlags | None # SSL certificate verification flags
33
34
# Worker Configuration
35
self.workers: int # Number of worker processes
36
self.worker_class: str # Worker class (asyncio, uvloop, trio)
37
self.backlog: int # Socket backlog size
38
self.graceful_timeout: int # Graceful shutdown timeout
39
self.shutdown_timeout: int # Hard shutdown timeout
40
41
# Request Handling
42
self.keep_alive_timeout: int # Keep-alive timeout seconds
43
self.max_requests: int # Max requests per worker
44
self.max_requests_jitter: int # Jitter for max_requests
45
self.h11_max_incomplete_size: int # HTTP/1.1 incomplete request max size
46
self.h2_max_concurrent_streams: int # HTTP/2 max concurrent streams
47
48
# Logging Configuration
49
self.accesslog: str | None # Access log file path
50
self.errorlog: str | None # Error log file path
51
self.logconfig: str | None # Logging configuration file
52
self.access_log_format: str # Access log format string
53
self.logger_class: str # Logger class to use
54
55
# Application Configuration
56
self.application_path: str # Path to ASGI/WSGI application
57
self.root_path: str # ASGI root path
58
self.server_names: list[str] # Valid server names
59
60
# Development/Debug
61
self.debug: bool # Enable debug mode
62
self.reload: bool # Enable auto-reload on file changes
63
self.use_reloader: bool # Use reloader process
64
65
# Process Management
66
self.pid_path: str | None # PID file path
67
self.user: int | None # User ID to run as
68
self.group: int | None # Group ID to run as
69
70
# Protocol Settings
71
self.alpn_protocols: list[str] # ALPN protocol list
72
self.alt_svc_headers: list[str] # Alt-Svc headers
73
74
# WSGI Configuration
75
self.wsgi_max_body_size: int # WSGI max request body size
76
77
@classmethod
78
def from_mapping(cls, mapping: dict) -> Config:
79
"""
80
Create Config instance from dictionary.
81
82
Args:
83
mapping: Dictionary containing configuration key-value pairs
84
85
Returns:
86
Configured Config instance
87
"""
88
89
@classmethod
90
def from_pyfile(cls, filename: str) -> Config:
91
"""
92
Create Config instance from Python configuration file.
93
94
Args:
95
filename: Path to Python file containing configuration variables
96
97
Returns:
98
Configured Config instance
99
"""
100
101
@classmethod
102
def from_toml(cls, filename: str) -> Config:
103
"""
104
Create Config instance from TOML configuration file.
105
106
Args:
107
filename: Path to TOML file containing configuration
108
109
Returns:
110
Configured Config instance
111
"""
112
113
@classmethod
114
def from_object(cls, instance: object | str) -> Config:
115
"""
116
Create Config instance from object, module, or module path.
117
118
Args:
119
instance: Object, module, or string module path containing configuration attributes
120
121
Returns:
122
Configured Config instance
123
"""
124
125
def create_ssl_context(self) -> ssl.SSLContext | None:
126
"""
127
Create SSL context from configuration.
128
129
Returns:
130
SSL context if SSL is enabled, None otherwise
131
"""
132
133
def create_sockets(self) -> Sockets:
134
"""
135
Create server sockets based on configuration.
136
137
Returns:
138
Sockets container with secure, insecure, and QUIC sockets
139
"""
140
141
def response_headers(self, protocol: str) -> list[tuple[bytes, bytes]]:
142
"""
143
Get default response headers for the given protocol.
144
145
Args:
146
protocol: Protocol version ("1.0", "1.1", "2", "3")
147
148
Returns:
149
List of default response headers as (name, value) byte tuples
150
"""
151
152
@property
153
def ssl_enabled(self) -> bool:
154
"""
155
Check if SSL/TLS is enabled.
156
157
Returns:
158
True if SSL certificate and key files are configured
159
"""
160
```
161
162
### Sockets Container
163
164
Container class for managing different types of server sockets created from configuration.
165
166
```python { .api }
167
@dataclass
168
class Sockets:
169
"""
170
Container for server sockets.
171
172
Holds the different socket types created from configuration:
173
secure sockets for HTTPS, insecure sockets for HTTP, and
174
QUIC sockets for HTTP/3.
175
"""
176
secure_sockets: list[socket.socket] # HTTPS sockets
177
insecure_sockets: list[socket.socket] # HTTP sockets
178
quic_sockets: list[socket.socket] # HTTP/3 QUIC sockets
179
```
180
181
### Configuration Constants
182
183
Type definitions and constants used in configuration.
184
185
```python { .api }
186
# Configuration value units
187
BYTES: int # Byte multiplier constant
188
OCTETS: int # Octet multiplier constant
189
SECONDS: int # Second multiplier constant
190
191
# Type aliases
192
FilePath = str # File path type alias
193
SocketKind = str # Socket type identifier
194
```
195
196
### Configuration Exceptions
197
198
Exceptions raised during configuration and socket creation.
199
200
```python { .api }
201
class SocketTypeError(Exception):
202
"""
203
Raised when an incorrect socket type is provided.
204
205
This exception occurs when socket configuration specifies
206
an invalid or unsupported socket type.
207
"""
208
```
209
210
## Configuration Examples
211
212
### Basic Configuration
213
214
```python
215
from hypercorn.config import Config
216
217
# Basic server configuration
218
config = Config()
219
config.bind = ["127.0.0.1:8000"]
220
config.workers = 1
221
config.worker_class = "asyncio"
222
```
223
224
### SSL/HTTPS Configuration
225
226
```python
227
config = Config()
228
config.bind = ["0.0.0.0:443"]
229
config.certfile = "/path/to/cert.pem"
230
config.keyfile = "/path/to/key.pem"
231
config.ssl_enabled = True
232
```
233
234
### Production Configuration
235
236
```python
237
config = Config()
238
config.bind = ["0.0.0.0:8000"]
239
config.workers = 4
240
config.worker_class = "uvloop"
241
config.backlog = 2048
242
config.keep_alive_timeout = 5
243
config.graceful_timeout = 30
244
config.accesslog = "/var/log/hypercorn-access.log"
245
config.errorlog = "/var/log/hypercorn-error.log"
246
```
247
248
### Loading from Files
249
250
```python
251
# From TOML file
252
config = Config.from_toml("hypercorn.toml")
253
254
# From Python file
255
config = Config.from_pyfile("hypercorn_config.py")
256
257
# From dictionary
258
settings = {
259
"bind": ["0.0.0.0:8000"],
260
"workers": 2,
261
"certfile": "cert.pem"
262
}
263
config = Config.from_mapping(settings)
264
```