-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig_file_example.py
More file actions
402 lines (326 loc) · 11.8 KB
/
config_file_example.py
File metadata and controls
402 lines (326 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
"""
Configuration file examples for NocoDB Simple Client.
This example demonstrates how to load configuration from YAML and TOML files
using the [config] optional dependency group.
INSTALLATION:
pip install "nocodb-simple-client[config]"
This installs the required dependencies:
- PyYAML: YAML file support
- tomli: TOML file support (Python < 3.11 only; Python 3.11+ uses stdlib tomllib)
"""
import importlib.util
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
from nocodb_simple_client.config import NocoDBConfig
# =============================================================================
# DEPENDENCY CHECK
# =============================================================================
# Check for YAML support (PyYAML)
YAML_AVAILABLE = importlib.util.find_spec("yaml") is not None
# Check for TOML support (stdlib tomllib for 3.11+ or tomli for older versions)
TOML_AVAILABLE = (
importlib.util.find_spec("tomllib") is not None or importlib.util.find_spec("tomli") is not None
)
if not YAML_AVAILABLE and not TOML_AVAILABLE:
print("=" * 60)
print("ERROR: Config file dependencies not installed!")
print("=" * 60)
print()
print("To use YAML/TOML configuration files, install the [config] extra:")
print()
print(' pip install "nocodb-simple-client[config]"')
print()
print("This will install: PyYAML, tomli (for Python < 3.11)")
print()
print("Note: Python 3.11+ includes tomllib in the standard library.")
print("=" * 60)
sys.exit(1)
# =============================================================================
# EXAMPLE 1: YAML Configuration
# =============================================================================
def example_yaml_config():
"""Demonstrate loading configuration from a YAML file."""
print("\n" + "=" * 60)
print("Example 1: YAML Configuration")
print("=" * 60)
if not YAML_AVAILABLE:
print("YAML support not available. Install PyYAML:")
print(' pip install "nocodb-simple-client[config]"')
return
# Create a sample YAML configuration file
yaml_content = """
# NocoDB Configuration
# Save this as: nocodb-config.yaml
base_url: "https://your-nocodb-instance.com"
api_token: "your-api-token-here"
# Connection settings
timeout: 60.0
max_retries: 3
backoff_factor: 0.5
# Connection pooling
pool_connections: 20
pool_maxsize: 50
# Security
verify_ssl: true
# Debugging
debug: false
log_level: "INFO"
# Custom headers (optional)
extra_headers:
X-Request-Source: "my-application"
X-Client-Version: "1.0.0"
"""
with TemporaryDirectory() as tmpdir:
config_path = Path(tmpdir) / "nocodb-config.yaml"
config_path.write_text(yaml_content)
print(f"Created sample config: {config_path}")
print()
print("YAML Content:")
print("-" * 40)
print(yaml_content.strip())
print("-" * 40)
print()
# Load configuration from YAML
config = NocoDBConfig.from_file(config_path)
print("Loaded configuration:")
print(f" Base URL: {config.base_url}")
print(f" Timeout: {config.timeout}s")
print(f" Max Retries: {config.max_retries}")
print(f" Pool Size: {config.pool_connections}/{config.pool_maxsize}")
print(f" SSL Verify: {config.verify_ssl}")
print(f" Debug: {config.debug}")
print("\nYAML configuration example completed!")
# =============================================================================
# EXAMPLE 2: TOML Configuration
# =============================================================================
def example_toml_config():
"""Demonstrate loading configuration from a TOML file."""
print("\n" + "=" * 60)
print("Example 2: TOML Configuration")
print("=" * 60)
if not TOML_AVAILABLE:
print("TOML support not available.")
print("For Python < 3.11, install tomli:")
print(' pip install "nocodb-simple-client[config]"')
print()
print("Python 3.11+ includes tomllib in the standard library.")
return
# Detect which TOML library is being used
if importlib.util.find_spec("tomllib") is not None:
toml_source = "tomllib (stdlib, Python 3.11+)"
else:
toml_source = "tomli (third-party)"
print(f"Using: {toml_source}")
print()
# Create a sample TOML configuration file
toml_content = """
# NocoDB Configuration
# Save this as: nocodb-config.toml
base_url = "https://your-nocodb-instance.com"
api_token = "your-api-token-here"
# Connection settings
timeout = 60.0
max_retries = 3
backoff_factor = 0.5
# Connection pooling
pool_connections = 20
pool_maxsize = 50
# Security
verify_ssl = true
# Debugging
debug = false
log_level = "INFO"
# Custom headers (optional)
[extra_headers]
X-Request-Source = "my-application"
X-Client-Version = "1.0.0"
"""
with TemporaryDirectory() as tmpdir:
config_path = Path(tmpdir) / "nocodb-config.toml"
config_path.write_text(toml_content)
print(f"Created sample config: {config_path}")
print()
print("TOML Content:")
print("-" * 40)
print(toml_content.strip())
print("-" * 40)
print()
# Load configuration from TOML
config = NocoDBConfig.from_file(config_path)
print("Loaded configuration:")
print(f" Base URL: {config.base_url}")
print(f" Timeout: {config.timeout}s")
print(f" Max Retries: {config.max_retries}")
print(f" Pool Size: {config.pool_connections}/{config.pool_maxsize}")
print("\nTOML configuration example completed!")
# =============================================================================
# EXAMPLE 3: JSON Configuration (Built-in, no extra dependencies)
# =============================================================================
def example_json_config():
"""Demonstrate loading configuration from a JSON file (no extra dependencies)."""
print("\n" + "=" * 60)
print("Example 3: JSON Configuration (Built-in)")
print("=" * 60)
# JSON is always available (stdlib)
json_content = """{
"base_url": "https://your-nocodb-instance.com",
"api_token": "your-api-token-here",
"timeout": 60.0,
"max_retries": 3,
"backoff_factor": 0.5,
"pool_connections": 20,
"pool_maxsize": 50,
"verify_ssl": true,
"debug": false,
"log_level": "INFO",
"extra_headers": {
"X-Request-Source": "my-application"
}
}"""
with TemporaryDirectory() as tmpdir:
config_path = Path(tmpdir) / "nocodb-config.json"
config_path.write_text(json_content)
print("Note: JSON support requires NO extra dependencies!")
print()
print("JSON Content:")
print("-" * 40)
print(json_content)
print("-" * 40)
print()
# Load configuration from JSON
config = NocoDBConfig.from_file(config_path)
print("Loaded configuration:")
print(f" Base URL: {config.base_url}")
print(f" Timeout: {config.timeout}s")
print("\nJSON configuration example completed!")
# =============================================================================
# EXAMPLE 4: Environment-Specific Configurations
# =============================================================================
def example_environment_configs():
"""Demonstrate managing multiple environment configurations."""
print("\n" + "=" * 60)
print("Example 4: Environment-Specific Configurations")
print("=" * 60)
if not YAML_AVAILABLE:
print("YAML support required for this example.")
return
# Development configuration
dev_config = """
base_url: "http://localhost:8080"
api_token: "dev-token"
timeout: 10.0
max_retries: 1
verify_ssl: false
debug: true
log_level: "DEBUG"
"""
# Staging configuration
staging_config = """
base_url: "https://staging.nocodb.example.com"
api_token: "staging-token"
timeout: 30.0
max_retries: 3
verify_ssl: true
debug: false
log_level: "INFO"
"""
# Production configuration
prod_config = """
base_url: "https://nocodb.example.com"
api_token: "prod-token"
timeout: 120.0
max_retries: 5
backoff_factor: 1.0
pool_connections: 50
pool_maxsize: 100
verify_ssl: true
debug: false
log_level: "WARNING"
"""
with TemporaryDirectory() as tmpdir:
configs = {
"development": dev_config,
"staging": staging_config,
"production": prod_config,
}
for env_name, content in configs.items():
config_path = Path(tmpdir) / f"config.{env_name}.yaml"
config_path.write_text(content)
config = NocoDBConfig.from_file(config_path)
print(f"\n{env_name.upper()}:")
print(f" URL: {config.base_url}")
print(f" Timeout: {config.timeout}s")
print(f" Debug: {config.debug}")
print(f" Log Level: {config.log_level}")
print("\nEnvironment configurations example completed!")
# =============================================================================
# EXAMPLE 5: Graceful Fallback Pattern
# =============================================================================
def example_graceful_fallback():
"""Demonstrate graceful fallback when config dependencies are missing."""
print("\n" + "=" * 60)
print("Example 5: Graceful Fallback Pattern")
print("=" * 60)
print(
"""
This pattern allows your application to work with or without
the [config] extra installed:
from pathlib import Path
from nocodb_simple_client.config import NocoDBConfig
def load_configuration(config_path: Path | None = None):
'''Load config with graceful fallback.'''
# Try file-based configuration first
if config_path and config_path.exists():
suffix = config_path.suffix.lower()
if suffix == '.json':
# JSON always works (stdlib)
return NocoDBConfig.from_file(config_path)
elif suffix in ['.yaml', '.yml']:
try:
return NocoDBConfig.from_file(config_path)
except ValueError as e:
if 'PyYAML' in str(e):
print("YAML not available, falling back to env")
else:
raise
elif suffix == '.toml':
try:
return NocoDBConfig.from_file(config_path)
except ValueError as e:
if 'tomli' in str(e):
print("TOML not available, falling back to env")
else:
raise
# Fallback to environment variables
return NocoDBConfig.from_env()
"""
)
print("\nGraceful fallback pattern demonstrated!")
# =============================================================================
# MAIN ENTRY POINT
# =============================================================================
def main():
"""Run all configuration file examples."""
print("\n" + "=" * 60)
print("NOCODB SIMPLE CLIENT - CONFIG FILE EXAMPLES")
print("=" * 60)
print()
print("These examples demonstrate the [config] optional dependency group.")
print()
print("Installation: pip install 'nocodb-simple-client[config]'")
print()
print("Dependency status:")
print(f" YAML support (PyYAML): {'Available' if YAML_AVAILABLE else 'Not installed'}")
print(f" TOML support: {'Available' if TOML_AVAILABLE else 'Not installed'}")
# Run examples
example_json_config() # Always works (no extra deps)
example_yaml_config() # Requires PyYAML
example_toml_config() # Requires tomli (< 3.11) or stdlib tomllib (3.11+)
example_environment_configs()
example_graceful_fallback()
print("\n" + "=" * 60)
print("All configuration file examples completed!")
print("=" * 60)
if __name__ == "__main__":
main()