0
# Configuration
1
2
Flexible configuration classes for customizing HTTP3 client behavior including timeouts, SSL settings, connection pool limits, and other operational parameters. These configuration objects provide fine-grained control over client behavior and can be used with both synchronous and asynchronous clients.
3
4
## Capabilities
5
6
### Timeout Configuration
7
8
Controls various timeout aspects of HTTP requests and connections.
9
10
```python { .api }
11
class TimeoutConfig:
12
def __init__(self, timeout=None, *, connect_timeout=None, read_timeout=None, write_timeout=None):
13
"""
14
Configure timeouts for HTTP operations.
15
16
Parameters:
17
- timeout (float or TimeoutConfig, optional): Overall timeout for all operations
18
- connect_timeout (float, optional): Timeout for connection establishment
19
- read_timeout (float, optional): Timeout for reading response data
20
- write_timeout (float, optional): Timeout for sending request data
21
22
Note: If timeout is provided, individual timeout parameters are ignored.
23
"""
24
25
@property
26
def connect_timeout(self) -> float:
27
"""Timeout for connection establishment in seconds."""
28
29
@property
30
def read_timeout(self) -> float:
31
"""Timeout for reading response data in seconds."""
32
33
@property
34
def write_timeout(self) -> float:
35
"""Timeout for sending request data in seconds."""
36
```
37
38
**Usage Example:**
39
40
```python
41
import http3
42
43
# Simple timeout (applies to all operations)
44
timeout = http3.TimeoutConfig(timeout=30.0)
45
46
# Granular timeout control
47
timeout = http3.TimeoutConfig(
48
connect_timeout=5.0, # 5 seconds to establish connection
49
read_timeout=30.0, # 30 seconds to read response
50
write_timeout=10.0 # 10 seconds to send request
51
)
52
53
# Use with client
54
client = http3.Client(timeout=timeout)
55
56
# Or use tuple shorthand for (connect, read, write)
57
client = http3.Client(timeout=(5.0, 30.0, 10.0))
58
```
59
60
### SSL Configuration
61
62
Manages SSL/TLS settings for secure connections.
63
64
```python { .api }
65
class SSLConfig:
66
def __init__(self, *, cert=None, verify=True):
67
"""
68
Configure SSL/TLS settings.
69
70
Parameters:
71
- cert (CertTypes, optional): Client certificate for mutual TLS
72
- verify (VerifyTypes): SSL certificate verification setting
73
"""
74
75
@property
76
def cert(self) -> CertTypes:
77
"""Client certificate configuration."""
78
79
@property
80
def verify(self) -> VerifyTypes:
81
"""SSL verification setting."""
82
83
def with_overrides(self, cert=None, verify=None):
84
"""
85
Create a new SSLConfig with modified settings.
86
87
Parameters:
88
- cert (CertTypes, optional): Override certificate setting
89
- verify (VerifyTypes, optional): Override verification setting
90
91
Returns:
92
SSLConfig: New configuration instance
93
"""
94
95
async def load_ssl_context(self):
96
"""
97
Load and return the SSL context for this configuration.
98
99
Returns:
100
ssl.SSLContext: Configured SSL context
101
"""
102
```
103
104
**Usage Example:**
105
106
```python
107
import http3
108
109
# Default SSL (verify certificates)
110
ssl_config = http3.SSLConfig()
111
112
# Disable SSL verification (not recommended for production)
113
ssl_config = http3.SSLConfig(verify=False)
114
115
# Custom CA bundle
116
ssl_config = http3.SSLConfig(verify='/path/to/ca-bundle.crt')
117
118
# Client certificate authentication
119
ssl_config = http3.SSLConfig(
120
cert='/path/to/client-cert.pem',
121
verify=True
122
)
123
124
# Client certificate with separate key file
125
ssl_config = http3.SSLConfig(
126
cert=('/path/to/cert.pem', '/path/to/key.pem'),
127
verify=True
128
)
129
130
# Use with client
131
client = http3.Client(verify=ssl_config.verify, cert=ssl_config.cert)
132
```
133
134
### Connection Pool Limits
135
136
Controls connection pooling behavior for optimal resource usage and performance.
137
138
```python { .api }
139
class PoolLimits:
140
def __init__(self, *, soft_limit=None, hard_limit=None, pool_timeout=None):
141
"""
142
Configure connection pool limits.
143
144
Parameters:
145
- soft_limit (int, optional): Preferred maximum connections per host
146
- hard_limit (int, optional): Absolute maximum connections per host
147
- pool_timeout (float, optional): Timeout waiting for connection from pool
148
"""
149
150
@property
151
def soft_limit(self) -> int:
152
"""Preferred maximum connections per host."""
153
154
@property
155
def hard_limit(self) -> int:
156
"""Absolute maximum connections per host."""
157
158
@property
159
def pool_timeout(self) -> float:
160
"""Timeout in seconds for acquiring connection from pool."""
161
```
162
163
**Usage Example:**
164
165
```python
166
import http3
167
168
# Default pool limits
169
pool_limits = http3.PoolLimits()
170
171
# Custom pool configuration
172
pool_limits = http3.PoolLimits(
173
soft_limit=10, # Prefer max 10 connections per host
174
hard_limit=50, # Never exceed 50 connections per host
175
pool_timeout=5.0 # Wait max 5 seconds for available connection
176
)
177
178
# Use with client
179
client = http3.Client(pool_limits=pool_limits)
180
```
181
182
### Default Configuration Values
183
184
HTTP3 provides sensible defaults for all configuration options:
185
186
```python { .api }
187
# Default timeout configuration
188
DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)
189
190
# Default SSL configuration
191
DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)
192
193
# Default pool limits
194
DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)
195
196
# Default maximum redirects
197
DEFAULT_MAX_REDIRECTS = 20
198
199
# Default CA bundle path
200
DEFAULT_CA_BUNDLE_PATH: str # Path to system CA bundle
201
202
# Default user agent string
203
USER_AGENT: str # "python-http3/0.6.7"
204
```
205
206
### Type Aliases
207
208
Configuration-related type aliases for flexible input handling:
209
210
```python { .api }
211
# Certificate types
212
CertTypes = Union[str, Tuple[str, str]]
213
214
# SSL verification types
215
VerifyTypes = Union[str, bool]
216
217
# Timeout types
218
TimeoutTypes = Union[float, Tuple[float, float, float], TimeoutConfig]
219
```
220
221
## Advanced Configuration
222
223
### Custom Cipher Configuration
224
225
HTTP3 uses secure cipher suites by default:
226
227
```python { .api }
228
DEFAULT_CIPHERS: str # Secure cipher suite string
229
```
230
231
### Protocol Configuration
232
233
```python { .api }
234
class Protocol(str, Enum):
235
HTTP_11 = "HTTP/1.1"
236
HTTP_2 = "HTTP/2"
237
```
238
239
### Concurrency Backend
240
241
Configure the async backend for HTTP3:
242
243
```python { .api }
244
class AsyncioBackend:
245
"""Default asyncio-based concurrency backend."""
246
247
async def connect(self, hostname, port, ssl_context, timeout):
248
"""Establish connection to host."""
249
250
def get_semaphore(self, limits):
251
"""Get semaphore for connection limiting."""
252
253
async def run_in_threadpool(self, func, *args, **kwargs):
254
"""Run function in thread pool."""
255
```
256
257
## Usage Examples
258
259
### Complete Client Configuration
260
261
```python
262
import http3
263
264
# Comprehensive client configuration
265
client = http3.Client(
266
# Authentication
267
auth=('username', 'password'),
268
269
# SSL settings
270
verify=True,
271
cert=('/path/to/cert.pem', '/path/to/key.pem'),
272
273
# Timeout configuration
274
timeout=http3.TimeoutConfig(
275
connect_timeout=5.0,
276
read_timeout=30.0,
277
write_timeout=10.0
278
),
279
280
# Connection pool limits
281
pool_limits=http3.PoolLimits(
282
soft_limit=20,
283
hard_limit=100,
284
pool_timeout=5.0
285
),
286
287
# Redirect behavior
288
max_redirects=10,
289
290
# Base URL for relative requests
291
base_url='https://api.example.com/v1',
292
293
# Default cookies
294
cookies={'session': 'abc123'}
295
)
296
```
297
298
### Environment-Based Configuration
299
300
```python
301
import os
302
import http3
303
304
# Configuration from environment variables
305
def create_client():
306
timeout = float(os.getenv('HTTP_TIMEOUT', '30.0'))
307
verify_ssl = os.getenv('VERIFY_SSL', 'true').lower() == 'true'
308
ca_bundle = os.getenv('CA_BUNDLE_PATH')
309
310
return http3.Client(
311
timeout=timeout,
312
verify=ca_bundle if ca_bundle else verify_ssl,
313
pool_limits=http3.PoolLimits(
314
soft_limit=int(os.getenv('POOL_SOFT_LIMIT', '10')),
315
hard_limit=int(os.getenv('POOL_HARD_LIMIT', '100'))
316
)
317
)
318
319
client = create_client()
320
```
321
322
### Configuration Validation
323
324
```python
325
import http3
326
327
def validate_config():
328
try:
329
# Test SSL configuration
330
ssl_config = http3.SSLConfig(verify=True)
331
ssl_context = await ssl_config.load_ssl_context()
332
333
# Test timeout configuration
334
timeout = http3.TimeoutConfig(
335
connect_timeout=5.0,
336
read_timeout=30.0,
337
write_timeout=10.0
338
)
339
340
# Create client with validation
341
client = http3.Client(
342
timeout=timeout,
343
verify=ssl_config.verify,
344
pool_limits=http3.PoolLimits(soft_limit=10, hard_limit=50)
345
)
346
347
return client
348
349
except Exception as e:
350
print(f"Configuration error: {e}")
351
return None
352
```