0
# Configuration and Profiles
1
2
Comprehensive configuration system for HTTP settings, retry behavior, circuit breakers, request customization, and regional failover. The profile system allows fine-grained control over SDK behavior across different deployment environments.
3
4
## Capabilities
5
6
### Client Profile Configuration
7
8
Master configuration object that controls SDK-wide behavior including authentication signatures, internationalization, retry policies, and circuit breaker settings.
9
10
```python { .api }
11
class ClientProfile:
12
def __init__(self, signMethod: str = "TC3-HMAC-SHA256", httpProfile = None, language: str = "zh-CN", debug: bool = False):
13
"""
14
Initialize client configuration profile.
15
16
Parameters:
17
- signMethod (str): API signature algorithm ("TC3-HMAC-SHA256", "HmacSHA1", "HmacSHA256")
18
- httpProfile (HttpProfile, optional): HTTP-specific configuration
19
- language (str): Response language ("zh-CN", "en-US")
20
- debug (bool): Enable debug mode for detailed logging
21
"""
22
23
# Configuration properties
24
self.signMethod: str = signMethod
25
self.httpProfile = httpProfile
26
self.language: str = language
27
self.debug: bool = debug
28
self.retryer = None # StandardRetryer or NoopRetryer
29
self.disable_region_breaker: bool = True
30
self.region_breaker_profile = None # RegionBreakerProfile
31
```
32
33
**Basic Configuration:**
34
35
```python
36
from tencentcloud.common.profile.client_profile import ClientProfile
37
from tencentcloud.cvm.v20170312 import cvm_client
38
from tencentcloud.common import credential
39
40
# Create basic configuration
41
client_profile = ClientProfile()
42
client_profile.signMethod = "TC3-HMAC-SHA256" # Default, most secure
43
client_profile.language = "en-US" # English responses
44
client_profile.debug = True # Enable detailed logging
45
46
# Use with client
47
cred = credential.DefaultCredentialProvider().get_credential()
48
client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)
49
```
50
51
### HTTP Profile Configuration
52
53
Detailed HTTP-level configuration including protocols, endpoints, timeouts, keep-alive settings, proxy configuration, and SSL certificate handling.
54
55
```python { .api }
56
class HttpProfile:
57
def __init__(self, protocol: str = "https", endpoint: str = None, reqMethod: str = "POST", reqTimeout: int = 60):
58
"""
59
Initialize HTTP configuration profile.
60
61
Parameters:
62
- protocol (str): Connection protocol ("https", "http")
63
- endpoint (str, optional): Custom service endpoint
64
- reqMethod (str): HTTP method ("POST", "GET")
65
- reqTimeout (int): Request timeout in seconds (default: 60)
66
"""
67
68
# HTTP configuration properties
69
self.protocol: str = protocol
70
self.endpoint: str = endpoint
71
self.reqMethod: str = reqMethod
72
self.reqTimeout: int = reqTimeout
73
self.keepAlive: bool = False
74
self.proxy: str = None
75
self.certification = None # SSL certificate path or False to skip
76
```
77
78
**HTTP Configuration Examples:**
79
80
```python
81
from tencentcloud.common.profile.http_profile import HttpProfile
82
from tencentcloud.common.profile.client_profile import ClientProfile
83
84
# Basic HTTP configuration
85
http_profile = HttpProfile()
86
http_profile.protocol = "https" # Use HTTPS (recommended)
87
http_profile.reqMethod = "POST" # Default for most APIs
88
http_profile.reqTimeout = 30 # 30-second timeout
89
http_profile.keepAlive = True # Enable connection reuse
90
91
# Custom endpoint (for specific regions or testing)
92
http_profile.endpoint = "cvm.ap-shanghai.tencentcloudapi.com"
93
94
# Attach to client profile
95
client_profile = ClientProfile()
96
client_profile.httpProfile = http_profile
97
```
98
99
**Proxy Configuration:**
100
101
```python
102
# HTTP proxy
103
http_profile = HttpProfile()
104
http_profile.proxy = "http://proxy-server:8080"
105
106
# Authenticated proxy
107
http_profile.proxy = "http://username:password@proxy-server:8080"
108
109
# HTTPS proxy
110
http_profile.proxy = "https://secure-proxy:8443"
111
```
112
113
**SSL Certificate Configuration:**
114
115
```python
116
# Custom certificate file
117
http_profile = HttpProfile()
118
http_profile.certification = "/path/to/certificate.pem"
119
120
# Skip certificate verification (not recommended for production)
121
http_profile.certification = False
122
123
# Use system certificates (default)
124
http_profile.certification = None
125
```
126
127
### Region Failover and Circuit Breaker
128
129
Automatic failover to backup regions when primary endpoints fail, with configurable circuit breaker patterns to handle transient failures gracefully.
130
131
```python { .api }
132
class RegionBreakerProfile:
133
def __init__(self, backup_endpoint: str, max_fail_num: int = 5, max_fail_percent: float = 0.75, window_interval: int = 300, timeout: int = 60, max_requests: int = 5):
134
"""
135
Initialize region circuit breaker configuration.
136
137
Parameters:
138
- backup_endpoint (str): Fallback region endpoint (format: {region}.tencentcloudapi.com)
139
- max_fail_num (int): Maximum failures before circuit opens (default: 5)
140
- max_fail_percent (float): Maximum failure percentage (0.0-1.0, default: 0.75)
141
- window_interval (int): Failure counting window in seconds (default: 300)
142
- timeout (int): Circuit open duration in seconds (default: 60)
143
- max_requests (int): Max successful requests to close circuit (default: 5)
144
"""
145
```
146
147
**Circuit Breaker States:**
148
- **Closed**: Normal operation using primary endpoint
149
- **Open**: All requests go to backup endpoint after failure threshold
150
- **Half-Open**: Testing primary endpoint with limited requests
151
152
**Circuit Breaker Configuration:**
153
154
```python
155
from tencentcloud.common.profile.client_profile import ClientProfile, RegionBreakerProfile
156
157
# Simple circuit breaker setup
158
client_profile = ClientProfile()
159
client_profile.disable_region_breaker = False # Enable circuit breaker
160
161
# Advanced circuit breaker configuration
162
region_breaker = RegionBreakerProfile(
163
backup_endpoint="ap-beijing.tencentcloudapi.com", # Backup region
164
max_fail_num=3, # Open after 3 failures
165
max_fail_percent=0.5, # Or 50% failure rate
166
window_interval=60, # 1-minute failure window
167
timeout=30, # Stay open for 30 seconds
168
max_requests=3 # Close after 3 successful requests
169
)
170
171
client_profile.region_breaker_profile = region_breaker
172
173
# Use with client
174
client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)
175
```
176
177
### Advanced Configuration Patterns
178
179
**Development Environment Configuration:**
180
181
```python
182
from tencentcloud.common.profile.client_profile import ClientProfile
183
from tencentcloud.common.profile.http_profile import HttpProfile
184
import logging
185
186
# Development-friendly configuration
187
http_profile = HttpProfile()
188
http_profile.reqTimeout = 10 # Short timeout for quick feedback
189
http_profile.keepAlive = False # Disable keep-alive for testing
190
191
client_profile = ClientProfile()
192
client_profile.httpProfile = http_profile
193
client_profile.debug = True # Enable debug logging
194
client_profile.language = "en-US" # English error messages
195
196
# Configure client with dev settings
197
client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)
198
client.set_stream_logger(sys.stdout, logging.DEBUG)
199
```
200
201
**Production Environment Configuration:**
202
203
```python
204
from tencentcloud.common.profile.client_profile import ClientProfile, RegionBreakerProfile
205
from tencentcloud.common.profile.http_profile import HttpProfile
206
from tencentcloud.common import retry
207
import logging
208
209
# Production HTTP configuration
210
http_profile = HttpProfile()
211
http_profile.keepAlive = True # Connection reuse
212
http_profile.reqTimeout = 60 # Longer timeout for stability
213
http_profile.certification = "/etc/ssl/certs/ca-certificates.crt" # Explicit cert
214
215
# Production retry configuration
216
logger = logging.getLogger("tencentcloud.retry")
217
logger.setLevel(logging.WARNING) # Only log warnings/errors
218
retryer = retry.StandardRetryer(max_attempts=5, logger=logger)
219
220
# Production circuit breaker
221
region_breaker = RegionBreakerProfile(
222
backup_endpoint="ap-beijing.tencentcloudapi.com",
223
max_fail_num=5,
224
max_fail_percent=0.75,
225
window_interval=300,
226
timeout=60,
227
max_requests=5
228
)
229
230
# Combine all production settings
231
client_profile = ClientProfile()
232
client_profile.httpProfile = http_profile
233
client_profile.retryer = retryer
234
client_profile.disable_region_breaker = False
235
client_profile.region_breaker_profile = region_breaker
236
client_profile.language = "en-US"
237
client_profile.debug = False
238
239
client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)
240
```
241
242
**High-Performance Configuration:**
243
244
```python
245
# Optimized for high-throughput scenarios
246
http_profile = HttpProfile()
247
http_profile.keepAlive = True # Reuse connections
248
http_profile.reqTimeout = 30 # Balance speed vs reliability
249
http_profile.reqMethod = "GET" # GET requests for read operations
250
251
client_profile = ClientProfile()
252
client_profile.httpProfile = http_profile
253
client_profile.debug = False # Disable debug overhead
254
client_profile.retryer = retry.NoopRetryer() # No automatic retries
255
256
client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)
257
```
258
259
**Multi-Region Configuration:**
260
261
```python
262
def create_multi_region_clients(regions, base_profile=None):
263
"""Create optimized clients for multiple regions."""
264
clients = {}
265
266
for region in regions:
267
# Clone base profile or create new one
268
profile = base_profile or ClientProfile()
269
270
# Region-specific HTTP settings
271
http_profile = HttpProfile()
272
http_profile.endpoint = f"cvm.{region}.tencentcloudapi.com"
273
http_profile.keepAlive = True
274
profile.httpProfile = http_profile
275
276
# Create region-specific client
277
clients[region] = cvm_client.CvmClient(cred, region, profile)
278
279
return clients
280
281
# Usage
282
regions = ["ap-shanghai", "ap-beijing", "ap-guangzhou"]
283
clients = create_multi_region_clients(regions)
284
285
# Use region-specific clients
286
for region, client in clients.items():
287
response = client.DescribeInstances(models.DescribeInstancesRequest())
288
print(f"{region}: {response.TotalCount} instances")
289
```
290
291
### Environment-Specific Configuration Helpers
292
293
**Configuration Factory Pattern:**
294
295
```python
296
from tencentcloud.common.profile.client_profile import ClientProfile, RegionBreakerProfile
297
from tencentcloud.common.profile.http_profile import HttpProfile
298
from tencentcloud.common import retry
299
import os
300
301
class TencentCloudConfig:
302
@staticmethod
303
def development():
304
"""Development environment configuration."""
305
http_profile = HttpProfile()
306
http_profile.reqTimeout = 10
307
308
client_profile = ClientProfile()
309
client_profile.httpProfile = http_profile
310
client_profile.debug = True
311
client_profile.language = "en-US"
312
313
return client_profile
314
315
@staticmethod
316
def production():
317
"""Production environment configuration."""
318
http_profile = HttpProfile()
319
http_profile.keepAlive = True
320
http_profile.reqTimeout = 60
321
322
region_breaker = RegionBreakerProfile(
323
backup_endpoint="ap-beijing.tencentcloudapi.com"
324
)
325
326
client_profile = ClientProfile()
327
client_profile.httpProfile = http_profile
328
client_profile.disable_region_breaker = False
329
client_profile.region_breaker_profile = region_breaker
330
client_profile.retryer = retry.StandardRetryer(max_attempts=3)
331
332
return client_profile
333
334
@staticmethod
335
def from_environment():
336
"""Load configuration from environment variables."""
337
env = os.getenv("TENCENTCLOUD_ENV", "development")
338
339
if env == "production":
340
return TencentCloudConfig.production()
341
else:
342
return TencentCloudConfig.development()
343
344
# Usage
345
profile = TencentCloudConfig.from_environment()
346
client = cvm_client.CvmClient(cred, "ap-shanghai", profile)
347
```