0
# Configuration
1
2
Client configuration management including base URL settings, authentication credentials, HTTP policies, pipeline configuration, and connection parameters. The Configuration class centralizes all client settings and provides the foundation for the service client's HTTP pipeline.
3
4
## Capabilities
5
6
### Configuration Creation
7
8
Create and initialize client configuration with base URL and optional settings file.
9
10
```python { .api }
11
class Configuration:
12
def __init__(self, base_url: str, filepath=None):
13
"""
14
Initialize client configuration.
15
16
Parameters:
17
- base_url: REST API base URL
18
- filepath: Optional path to config file
19
"""
20
21
base_url: str
22
credentials: any = None
23
keep_alive: bool = False
24
pipeline: any
25
```
26
27
### User Agent Management
28
29
Configure and manage the User-Agent header for HTTP requests.
30
31
```python { .api }
32
@property
33
def user_agent(self) -> str:
34
"""Get current user agent string."""
35
36
def add_user_agent(self, value: str):
37
"""
38
Add value to current user agent.
39
40
Parameters:
41
- value: String to append to user agent
42
"""
43
44
user_agent_policy: any # UserAgentPolicy instance
45
```
46
47
### HTTP Logging
48
49
Configure HTTP request and response logging for debugging and monitoring.
50
51
```python { .api }
52
@property
53
def enable_http_logger(self) -> bool:
54
"""Get HTTP logging enabled status."""
55
56
@enable_http_logger.setter
57
def enable_http_logger(self, value: bool):
58
"""
59
Enable or disable HTTP logging.
60
61
Parameters:
62
- value: True to enable, False to disable
63
"""
64
65
http_logger_policy: any # HTTPLogger instance
66
```
67
68
### Configuration Loading
69
70
Load configuration settings from external files.
71
72
```python { .api }
73
def load(self, filepath: str):
74
"""
75
Load configuration from file.
76
77
Parameters:
78
- filepath: Path to configuration file
79
"""
80
```
81
82
## HTTP Configuration Properties
83
84
The Configuration class inherits from RequestHTTPSenderConfiguration, providing HTTP-specific settings:
85
86
```python { .api }
87
# Connection settings
88
connection: any # Connection configuration object
89
timeout: int # Request timeout in seconds
90
verify: bool # SSL certificate verification
91
proxies: dict # Proxy configuration
92
headers: dict # Default headers for all requests
93
94
# SSL/TLS settings
95
cert: any # Client certificate configuration
96
stream: bool # Enable response streaming
97
allow_redirects: bool # Follow HTTP redirects
98
max_redirects: int # Maximum redirect count
99
100
# Data handling
101
data_block_size: int # Block size for streaming operations
102
```
103
104
## Usage Examples
105
106
### Basic Configuration
107
108
```python
109
from msrest import Configuration
110
111
# Create basic configuration
112
config = Configuration(base_url='https://api.example.com')
113
114
# Set authentication
115
from msrest.authentication import ApiKeyCredentials
116
config.credentials = ApiKeyCredentials(in_headers={'X-API-Key': 'your-key'})
117
118
# Configure User-Agent
119
config.add_user_agent('MyApp/1.0')
120
print(config.user_agent) # Shows current user agent string
121
```
122
123
### HTTP Settings
124
125
```python
126
from msrest import Configuration
127
128
config = Configuration(base_url='https://api.example.com')
129
130
# Configure HTTP settings
131
config.timeout = 30 # 30 second timeout
132
config.verify = True # Verify SSL certificates
133
config.allow_redirects = True
134
config.max_redirects = 5
135
136
# Set default headers
137
config.headers = {
138
'Accept': 'application/json',
139
'User-Agent': 'MyApp/1.0'
140
}
141
142
# Configure proxy
143
config.proxies = {
144
'http': 'http://proxy.example.com:8080',
145
'https': 'https://proxy.example.com:8080'
146
}
147
```
148
149
### Logging Configuration
150
151
```python
152
from msrest import Configuration
153
import logging
154
155
# Enable HTTP logging
156
config = Configuration(base_url='https://api.example.com')
157
config.enable_http_logger = True
158
159
# Configure Python logging to see HTTP logs
160
logging.basicConfig(level=logging.DEBUG)
161
logger = logging.getLogger('msrest.http_logger')
162
logger.setLevel(logging.DEBUG)
163
```
164
165
### SSL Configuration
166
167
```python
168
from msrest import Configuration
169
170
config = Configuration(base_url='https://api.example.com')
171
172
# Disable SSL verification (not recommended for production)
173
config.verify = False
174
175
# Use custom CA bundle
176
config.verify = '/path/to/ca-bundle.crt'
177
178
# Client certificate authentication
179
config.cert = '/path/to/client.pem'
180
# Or with separate key file
181
config.cert = ('/path/to/client.crt', '/path/to/client.key')
182
```
183
184
### Configuration File Loading
185
186
```python
187
from msrest import Configuration
188
189
# Create config and load from file
190
config = Configuration(base_url='https://api.example.com')
191
config.load('/path/to/config.ini')
192
193
# Or load during initialization
194
config = Configuration(
195
base_url='https://api.example.com',
196
filepath='/path/to/config.ini'
197
)
198
```
199
200
Example configuration file format (INI):
201
```ini
202
[connection]
203
timeout = 30
204
verify = true
205
allow_redirects = true
206
207
[proxy]
208
http = http://proxy.example.com:8080
209
https = https://proxy.example.com:8080
210
211
[headers]
212
Accept = application/json
213
User-Agent = MyApp/1.0
214
```
215
216
### Session Management
217
218
```python
219
from msrest import ServiceClient, Configuration
220
221
# Enable keep-alive for connection reuse
222
config = Configuration(base_url='https://api.example.com')
223
config.keep_alive = True
224
225
# Use with context manager for automatic cleanup
226
with ServiceClient(None, config) as client:
227
# Connection will be kept alive for multiple requests
228
response1 = client.send(client.get('/endpoint1'))
229
response2 = client.send(client.get('/endpoint2'))
230
# Connection automatically closed when exiting context
231
```
232
233
### Custom Pipeline Configuration
234
235
```python
236
from msrest import Configuration
237
from msrest.pipeline import HTTPPolicy
238
239
class CustomHeaderPolicy(HTTPPolicy):
240
def send(self, request, **kwargs):
241
request.http_request.headers['X-Custom-Header'] = 'MyValue'
242
return self.next.send(request, **kwargs)
243
244
# Add custom policy to pipeline
245
config = Configuration(base_url='https://api.example.com')
246
247
# Pipeline will be created when ServiceClient is initialized
248
# Custom policies can be added through the pipeline property
249
```
250
251
### Streaming Configuration
252
253
```python
254
from msrest import Configuration
255
256
config = Configuration(base_url='https://api.example.com')
257
258
# Configure streaming settings
259
config.stream = True # Enable response streaming
260
config.data_block_size = 8192 # 8KB blocks for streaming
261
262
# Use with large file downloads
263
from msrest import ServiceClient
264
265
with ServiceClient(None, config) as client:
266
request = client.get('/large-file')
267
response = client.send(request, stream=True)
268
269
# Stream the response
270
for chunk in client.stream_download(response, callback=None):
271
# Process chunk
272
pass
273
```
274
275
### Environment-Based Configuration
276
277
```python
278
import os
279
from msrest import Configuration
280
from msrest.authentication import BasicAuthentication
281
282
# Load settings from environment variables
283
base_url = os.getenv('API_BASE_URL', 'https://api.example.com')
284
username = os.getenv('API_USERNAME')
285
password = os.getenv('API_PASSWORD')
286
287
config = Configuration(base_url=base_url)
288
289
if username and password:
290
config.credentials = BasicAuthentication(username, password)
291
292
# Configure from environment
293
config.timeout = int(os.getenv('API_TIMEOUT', '30'))
294
config.verify = os.getenv('API_VERIFY_SSL', 'true').lower() == 'true'
295
296
if os.getenv('HTTP_PROXY'):
297
config.proxies = {
298
'http': os.getenv('HTTP_PROXY'),
299
'https': os.getenv('HTTPS_PROXY', os.getenv('HTTP_PROXY'))
300
}
301
```
302
303
## Integration with Service Client
304
305
Configuration objects are passed to ServiceClient during initialization:
306
307
```python
308
from msrest import ServiceClient, Configuration
309
310
# Create configuration
311
config = Configuration(base_url='https://api.example.com')
312
313
# Configure as needed
314
config.timeout = 30
315
config.enable_http_logger = True
316
317
# Create client with configuration
318
client = ServiceClient(None, config)
319
320
# Or use as context manager
321
with ServiceClient(None, config) as client:
322
# Client will use all configuration settings
323
response = client.send(client.get('/data'))
324
```
325
326
The ServiceClient will use the configuration to:
327
- Set base URL for all requests
328
- Apply authentication credentials
329
- Configure HTTP timeout and SSL settings
330
- Enable logging if requested
331
- Set default headers and proxy settings
332
- Manage connection lifecycle based on keep_alive setting