xenoslib 0.1.30__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {xenoslib-0.1.30/xenoslib.egg-info → xenoslib-0.3.0}/PKG-INFO +1 -1
  2. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/about.py +1 -1
  3. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/base.py +62 -0
  4. xenoslib-0.3.0/xenoslib/tools/config_loader.py +290 -0
  5. {xenoslib-0.1.30 → xenoslib-0.3.0/xenoslib.egg-info}/PKG-INFO +1 -1
  6. xenoslib-0.1.30/xenoslib/tools/config_loader.py +0 -211
  7. {xenoslib-0.1.30 → xenoslib-0.3.0}/LICENSE +0 -0
  8. {xenoslib-0.1.30 → xenoslib-0.3.0}/README.md +0 -0
  9. {xenoslib-0.1.30 → xenoslib-0.3.0}/setup.cfg +0 -0
  10. {xenoslib-0.1.30 → xenoslib-0.3.0}/setup.py +0 -0
  11. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/__init__.py +0 -0
  12. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/__main__.py +0 -0
  13. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/dev.py +0 -0
  14. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/extend.py +0 -0
  15. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/linux.py +0 -0
  16. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/mail.py +0 -0
  17. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/mock.py +0 -0
  18. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/onedrive.py +0 -0
  19. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/tools/__init__.py +0 -0
  20. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/win_trayicon.py +0 -0
  21. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib/windows.py +0 -0
  22. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib.egg-info/SOURCES.txt +0 -0
  23. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib.egg-info/dependency_links.txt +0 -0
  24. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib.egg-info/requires.txt +0 -0
  25. {xenoslib-0.1.30 → xenoslib-0.3.0}/xenoslib.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: xenoslib
3
- Version: 0.1.30
3
+ Version: 0.3.0
4
4
  Summary: Xenos' common lib
5
5
  Home-page: https://github.com/XenosLu/xenoslib.git
6
6
  Author: Xenocider
@@ -4,4 +4,4 @@ __url__ = "https://github.com/XenosLu/xenoslib.git"
4
4
  __author__ = "Xenocider"
5
5
  __author_email__ = "xenos.lu@gmail.com"
6
6
  __license__ = "MIT License"
7
- __version__ = "0.1.30"
7
+ __version__ = "0.3.0"
@@ -4,6 +4,68 @@ import argparse
4
4
  import sys
5
5
  import time
6
6
  import inspect
7
+ import logging
8
+ import os
9
+
10
+ from logging.handlers import TimedRotatingFileHandler
11
+
12
+
13
+ def init_logger(
14
+ use_file: bool = True,
15
+ level: int = logging.INFO,
16
+ backup_count: int = 0, # New parameter: number of log files to retain (0 means keep all)
17
+ ) -> logging.Logger:
18
+ """
19
+ Automatically names logger after caller's filename, rotates by time, and retains specified number of log files
20
+
21
+ Args:
22
+ use_file: Whether to enable file logging
23
+ level: Logging level (DEBUG/INFO/WARN/ERROR)
24
+ backup_count: Number of historical log files to retain (default 0=keep all)
25
+ """
26
+ # 1. Dynamically get caller's filename
27
+ caller_frame = inspect.stack()[1]
28
+ caller_path = caller_frame.filename
29
+ caller_name = os.path.splitext(os.path.basename(caller_path))[0]
30
+
31
+ # 2. Configure log directory and filename
32
+ log_dir = "logs"
33
+ os.makedirs(log_dir, exist_ok=True)
34
+ log_filename = f"{caller_name}.log"
35
+ full_path = os.path.join(log_dir, log_filename)
36
+
37
+ # 3. Avoid duplicate initialization
38
+ logger = logging.getLogger(caller_name)
39
+ if logger.hasHandlers():
40
+ return logger
41
+
42
+ logger.setLevel(level)
43
+ formatter = logging.Formatter(
44
+ "%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d - %(message)s",
45
+ datefmt="%Y-%m-%d %H:%M:%S",
46
+ )
47
+
48
+ # 4. Console handler (required)
49
+ console_handler = logging.StreamHandler()
50
+ console_handler.setFormatter(formatter)
51
+ handlers = [console_handler]
52
+
53
+ # 5. File handler (daily rotation + file retention policy)
54
+ if use_file:
55
+ file_handler = TimedRotatingFileHandler(
56
+ full_path,
57
+ when="midnight", # Rotate daily
58
+ interval=1,
59
+ backupCount=backup_count, # Key parameter: controls number of retained files
60
+ encoding="utf-8",
61
+ )
62
+ file_handler.setFormatter(formatter)
63
+ handlers.append(file_handler)
64
+
65
+ for handler in handlers:
66
+ logger.addHandler(handler)
67
+
68
+ return logger
7
69
 
8
70
 
9
71
  def sleep(seconds, mute=False):
@@ -0,0 +1,290 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ import os
4
+ import logging
5
+
6
+ import yaml
7
+
8
+ from xenoslib.base import SingletonWithArgs
9
+
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class ConfigLoader(SingletonWithArgs):
15
+ """Centralized configuration management with optional Vault integration.
16
+
17
+ Args:
18
+ config_file_path (str): Path to the YAML configuration file. Defaults to "config.yml".
19
+ vault_secret_id (str, optional): Secret ID for Vault authentication.
20
+ If provided, enables Vault functionality and imports hvac module.
21
+
22
+ Attributes:
23
+ cache (dict): Cache storage for frequently accessed configuration values.
24
+
25
+ Example:
26
+ # Without Vault (hvac not imported)
27
+ >>> config = ConfigLoader("config.yml")
28
+
29
+ # With Vault (hvac imported on demand)
30
+ >>> config = ConfigLoader("config.yml", vault_secret_id="my-secret-id")
31
+
32
+ # Write to Vault using attribute style
33
+ >>> config.test_section.test_key = "new_value"
34
+
35
+ # Write to Vault using dictionary style
36
+ >>> config["test_section"]["test_key"] = "new_value"
37
+ """
38
+
39
+ VAULT_SUFFIX = "@vault"
40
+ KV_MOUNT_POINT = "kv"
41
+
42
+ cache = {}
43
+ vault_client = None
44
+
45
+ def __init__(self, config_file_path="config.yml", vault_secret_id=None):
46
+ """Initialize the ConfigLoader with a configuration file and optional Vault secret."""
47
+ with open(config_file_path, "r") as f:
48
+ config_data = yaml.safe_load(f)
49
+ self._raw_config = config_data if isinstance(config_data, dict) else {}
50
+
51
+ if vault_secret_id is not None:
52
+ self.vault_secret_id = vault_secret_id
53
+ self._check_and_renew_vault_client()
54
+
55
+ def _init_vault_client(self):
56
+ """Initialize and authenticate the Vault client (imports hvac on demand)."""
57
+ try:
58
+ import hvac # Lazy import
59
+ except ImportError as e:
60
+ raise ImportError(
61
+ "hvac package is required for Vault integration. Install with: pip install hvac"
62
+ ) from e
63
+
64
+ try:
65
+ vault_config = self._raw_config.get("vault", {})
66
+ vault_url = vault_config.get("url")
67
+ vault_space = vault_config.get("space")
68
+ vault_role_id = vault_config.get("role_id")
69
+
70
+ if not all([vault_url, vault_space, vault_role_id]):
71
+ raise KeyError("Missing required Vault configuration in config.yml")
72
+
73
+ self.vault_client = hvac.Client(url=vault_url, namespace=vault_space, timeout=45)
74
+ self.vault_client.auth.approle.login(
75
+ role_id=vault_role_id, secret_id=self.vault_secret_id
76
+ )
77
+ except Exception as e:
78
+ self.vault_client = None
79
+ raise Exception(f"Failed to initialize Vault client: {str(e)}") from e
80
+
81
+ def _check_and_renew_vault_client(self):
82
+ if not self.vault_client or not self.vault_client.is_authenticated():
83
+ self._init_vault_client()
84
+
85
+ def _is_vault_reference(self, section_config, key_name):
86
+ """检查键是否是Vault引用"""
87
+ return f"{key_name}{self.VAULT_SUFFIX}" in section_config
88
+
89
+ def get(self, section, key_name, use_cache=True):
90
+ """Retrieve a configuration value."""
91
+ section_config = self._raw_config.get(section)
92
+ if section_config is None:
93
+ raise KeyError(f"Section '{section}' not found")
94
+
95
+ if key_name in section_config:
96
+ return section_config[key_name]
97
+
98
+ if self._is_vault_reference(section_config, key_name):
99
+ if self.vault_client is None:
100
+ raise Exception(
101
+ f"Vault access required for {key_name} but Vault is not initialized"
102
+ )
103
+
104
+ cache_key = f"{section}:{key_name}"
105
+ if use_cache and cache_key in self.cache:
106
+ return self.cache[cache_key]
107
+ value = self._get_value_from_vault(section, key_name)
108
+ self.cache[cache_key] = value
109
+ return value
110
+
111
+ raise KeyError(f"Key '{key_name}' not found in section '{section}'")
112
+
113
+ def set(self, section, key_name, value, use_cache=True):
114
+ """Set a configuration value to Vault."""
115
+ section_config = self._raw_config.get(section)
116
+ if section_config is None:
117
+ raise KeyError(f"Section '{section}' not found")
118
+
119
+ if not self._is_vault_reference(section_config, key_name):
120
+ raise KeyError(f"Key '{key_name}' is not a Vault reference in section '{section}'")
121
+
122
+ if self.vault_client is None:
123
+ raise Exception(f"Vault access required for {key_name} but Vault is not initialized")
124
+
125
+ self._set_value_to_vault(section, key_name, value)
126
+
127
+ cache_key = f"{section}:{key_name}"
128
+ if use_cache:
129
+ self.cache[cache_key] = value
130
+
131
+ def _get_value_from_vault(self, section, key_name):
132
+ """Retrieve a secret value from Vault."""
133
+ try:
134
+ section_config = self._raw_config[section]
135
+ vault_path = section_config.get("vault_path")
136
+ if not vault_path:
137
+ raise KeyError(f"Missing vault_path in section '{section}'")
138
+
139
+ vault_key_ref = f"{key_name}{self.VAULT_SUFFIX}"
140
+ vault_key = section_config[vault_key_ref]
141
+
142
+ namespace = section_config.get("vault_namespace") or self._raw_config["vault"]["space"]
143
+ self.vault_client.adapter.namespace = namespace
144
+
145
+ data = self.vault_client.secrets.kv.read_secret_version(
146
+ path=vault_path, mount_point=self.KV_MOUNT_POINT, raise_on_deleted_version=True
147
+ )
148
+ return data["data"]["data"][vault_key]
149
+ except Exception as e:
150
+ raise Exception(f"Failed to fetch {key_name} from Vault: {str(e)}") from e
151
+
152
+ def _set_value_to_vault(self, section, key_name, value):
153
+ """Set a secret value to Vault."""
154
+ try:
155
+ self._check_and_renew_vault_client()
156
+
157
+ section_config = self._raw_config[section]
158
+ vault_path = section_config.get("vault_path")
159
+ if not vault_path:
160
+ raise KeyError(f"Missing vault_path in section '{section}'")
161
+
162
+ vault_key_ref = f"{key_name}{self.VAULT_SUFFIX}"
163
+ vault_key = section_config[vault_key_ref]
164
+
165
+ namespace = section_config.get("vault_namespace") or self._raw_config["vault"]["space"]
166
+ self.vault_client.adapter.namespace = namespace
167
+
168
+ try:
169
+ data = self.vault_client.secrets.kv.read_secret_version(
170
+ path=vault_path, mount_point=self.KV_MOUNT_POINT, raise_on_deleted_version=True
171
+ )
172
+ secret_data = data["data"]["data"]
173
+ except Exception:
174
+ logger.warning(f"Secret not found, creating new secret at {vault_path}")
175
+ secret_data = {}
176
+
177
+ secret_data[vault_key] = value
178
+
179
+ self.vault_client.secrets.kv.create_or_update_secret(
180
+ path=vault_path, secret=secret_data, mount_point=self.KV_MOUNT_POINT
181
+ )
182
+
183
+ logger.info(f"Updated Vault secret: {vault_path}/{vault_key}")
184
+ except Exception as e:
185
+ raise Exception(f"Failed to set {key_name} to Vault: {str(e)}") from e
186
+
187
+ def __getitem__(self, section):
188
+ """Dictionary-style access to configuration sections."""
189
+ if section not in self._raw_config:
190
+ raise KeyError(f"Section '{section}' not found")
191
+ return SectionProxy(self, section)
192
+
193
+ def __setitem__(self, section, proxy):
194
+ """Prevent direct assignment to sections."""
195
+ raise TypeError("ConfigLoader does not support direct section assignment")
196
+
197
+ def __getattr__(self, section):
198
+ """Attribute-style access to configuration sections."""
199
+ try:
200
+ return self[section]
201
+ except KeyError as e:
202
+ raise AttributeError(str(e))
203
+
204
+
205
+ class SectionProxy:
206
+ """Proxy class for configuration section access."""
207
+
208
+ def __init__(self, config_loader, section):
209
+ self._loader = config_loader
210
+ self._section = section
211
+
212
+ def __getitem__(self, key):
213
+ """Dictionary-style access to configuration values."""
214
+ return self._loader.get(self._section, key)
215
+
216
+ def __setitem__(self, key, value):
217
+ """Dictionary-style setting of configuration values to Vault."""
218
+ self.set(key, value)
219
+
220
+ def get(self, key, default=None):
221
+ """Dictionary-style access to configuration values."""
222
+ try:
223
+ return self._loader.get(self._section, key)
224
+ except KeyError:
225
+ return default
226
+
227
+ def set(self, key, value):
228
+ """Set a configuration value to Vault."""
229
+ self._loader.set(self._section, key, value)
230
+
231
+ def __getattr__(self, key):
232
+ """Attribute-style access to configuration values."""
233
+ try:
234
+ return self[key]
235
+ except KeyError as e:
236
+ raise AttributeError(str(e))
237
+
238
+ def __setattr__(self, name, value):
239
+ """Attribute-style setting of configuration values to Vault."""
240
+ if name.startswith("_"):
241
+ super().__setattr__(name, value)
242
+ else:
243
+ self.set(name, value)
244
+
245
+ def __repr__(self):
246
+ """String representation of the section's configuration."""
247
+ return yaml.dump(self._loader._raw_config[self._section])
248
+
249
+
250
+ if __name__ == "__main__":
251
+ config_without_vault = ConfigLoader("config.yml")
252
+ print("Without Vault:", config_without_vault.get("jira", "url"))
253
+
254
+ config_with_vault = ConfigLoader("config.yml", vault_secret_id=os.getenv("VAULT_SECRET_ID"))
255
+
256
+ # 属性方式读取
257
+ print("With Vault (attr):", config_with_vault.test.test)
258
+
259
+ # 字典方式读取
260
+ print("With Vault (dict):", config_with_vault["cis"]["cis_client_id"])
261
+
262
+ # 测试不存在的值
263
+ print("Try val not exists: ", config_with_vault.test.get("not_exists"))
264
+
265
+ # 写入示例 - 属性方式
266
+ try:
267
+ print("Current test value (attr read):", config_with_vault.test.test)
268
+ config_with_vault.test.test = "new_value_123"
269
+ print("After write (attr read):", config_with_vault.test.test)
270
+ except Exception as e:
271
+ print("Attribute write failed:", str(e))
272
+
273
+ # 写入示例 - 字典方式
274
+ try:
275
+ print("Current test value (dict read):", config_with_vault["test"]["test"])
276
+ config_with_vault["test"]["test"] = "new_value_456"
277
+ print("After write (dict read):", config_with_vault["test"]["test"])
278
+
279
+ # 混合方式验证
280
+ print("After write (attr read):", config_with_vault.test.test)
281
+ except Exception as e:
282
+ print("Dictionary write failed:", str(e))
283
+
284
+ # 写入新键示例
285
+ try:
286
+ print("Setting new key...")
287
+ config_with_vault["database"]["new_password"] = "secure123!"
288
+ print("New password:", config_with_vault.database.new_password)
289
+ except Exception as e:
290
+ print("New key write failed:", str(e))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: xenoslib
3
- Version: 0.1.30
3
+ Version: 0.3.0
4
4
  Summary: Xenos' common lib
5
5
  Home-page: https://github.com/XenosLu/xenoslib.git
6
6
  Author: Xenocider
@@ -1,211 +0,0 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- import os
4
- import logging
5
-
6
- import yaml
7
-
8
- from xenoslib.base import SingletonWithArgs
9
-
10
-
11
- logger = logging.getLogger(__name__)
12
-
13
-
14
- class ConfigLoader(SingletonWithArgs):
15
- """Centralized configuration management with optional Vault integration.
16
-
17
- Args:
18
- config_file_path (str): Path to the YAML configuration file. Defaults to "config.yml".
19
- vault_secret_id (str, optional): Secret ID for Vault authentication.
20
- If provided, enables Vault functionality and imports hvac module.
21
-
22
- Attributes:
23
- cache (dict): Cache storage for frequently accessed configuration values.
24
-
25
- Example:
26
- # Without Vault (hvac not imported)
27
- >>> config = ConfigLoader("config.yml")
28
-
29
- # With Vault (hvac imported on demand)
30
- >>> config = ConfigLoader("config.yml", vault_secret_id="my-secret-id")
31
- """
32
-
33
- cache = {}
34
- vault_client = None
35
-
36
- def __init__(self, config_file_path="config.yml", vault_secret_id=None):
37
- """Initialize the ConfigLoader with a configuration file and optional Vault secret."""
38
- with open(config_file_path, "r") as f:
39
- self._raw_config = yaml.safe_load(f) or {}
40
-
41
- if vault_secret_id is not None:
42
- self.vault_secret_id = vault_secret_id
43
- self._check_and_renew_vault_client()
44
-
45
- def _init_vault_client(self):
46
- """Initialize and authenticate the Vault client (imports hvac on demand).
47
-
48
- Args:
49
- vault_secret_id (str): Secret ID for Vault authentication.
50
-
51
- Raises:
52
- ImportError: If hvac package is not installed.
53
- KeyError: If required Vault configuration is missing.
54
- Exception: If Vault authentication fails.
55
- """
56
- try:
57
- import hvac # Lazy import
58
- except ImportError as e:
59
- raise ImportError(
60
- "hvac package is required for Vault integration. " "Install with: pip install hvac"
61
- ) from e
62
-
63
- try:
64
- vault_config = self._raw_config.get("vault", {})
65
- vault_url = vault_config.get("url")
66
- vault_space = vault_config.get("space")
67
- vault_role_id = vault_config.get("role_id")
68
-
69
- if not all([vault_url, vault_space, vault_role_id]):
70
- raise KeyError("Missing required Vault configuration in config.yml")
71
-
72
- self.vault_client = hvac.Client(url=vault_url, namespace=vault_space, timeout=45)
73
- self.vault_client.auth.approle.login(
74
- role_id=vault_role_id, secret_id=self.vault_secret_id
75
- )
76
- except Exception as e:
77
- self.vault_client = None
78
- raise Exception(f"Failed to initialize Vault client: {str(e)}")
79
-
80
- def _check_and_renew_vault_client(self):
81
- # 检查当前Token的状态,包括过期时间和可续租性
82
- if not self.vault_client or not self.vault_client.is_authenticated():
83
- # 如果当前Token无效,则重新认证
84
- self._init_vault_client()
85
-
86
- def get(self, section, key_name, use_cache=True):
87
- """Retrieve a configuration value.
88
-
89
- Args:
90
- section (str): The configuration section name.
91
- key_name (str): The key name within the section.
92
- use_cache (bool): Whether to use cached values. Defaults to True.
93
-
94
- Returns:
95
- The configuration value, which may come from:
96
- - Direct configuration value
97
- - Vault secret (if Vault is initialized)
98
- - Cache (if enabled)
99
-
100
- Raises:
101
- KeyError: If the section or key is not found.
102
- Exception: If Vault access is required but not available.
103
- """
104
- if section not in self._raw_config:
105
- raise KeyError(f"Section '{section}' not found")
106
-
107
- # Check for direct value first
108
- if key_name in self._raw_config[section]:
109
- return self._raw_config[section][key_name]
110
-
111
- # Handle Vault reference if Vault is enabled
112
- vault_key = f"{key_name}@vault"
113
- if vault_key in self._raw_config[section]:
114
- if self.vault_client is None:
115
- raise Exception(
116
- f"Vault access required for {key_name} but Vault is not initialized"
117
- )
118
-
119
- cache_key = f"{section}_{key_name}"
120
-
121
- if use_cache and cache_key in self.cache:
122
- return self.cache[cache_key]
123
- value = self._get_value_from_vault(section, key_name)
124
- self.cache[cache_key] = value
125
- return value
126
-
127
- raise KeyError(f"Key '{key_name}' or '{vault_key}' not found in section '{section}'")
128
-
129
- def _get_value_from_vault(self, section, key_name):
130
- """Retrieve a secret value from Vault.
131
-
132
- Args:
133
- section (str): The configuration section name.
134
- key_name (str): The key name within the section.
135
-
136
- Returns:
137
- The secret value from Vault.
138
-
139
- Raises:
140
- Exception: If Vault access fails.
141
- """
142
- try:
143
- vault_path = self._raw_config[section]["vault_path"]
144
- vault_key = self._raw_config[section][f"{key_name}@vault"]
145
- vault_namepsace = self._raw_config[section].get("vault_namespace")
146
- if vault_namepsace:
147
- self.vault_client.adapter.namespace = vault_namepsace
148
- else:
149
- self.vault_client.adapter.namespace = self._raw_config["vault"]["space"]
150
- data = self.vault_client.secrets.kv.read_secret_version(
151
- path=vault_path, mount_point="kv", raise_on_deleted_version=True
152
- )
153
- return data["data"]["data"][vault_key]
154
- except Exception as e:
155
- raise Exception(f"Failed to fetch {key_name} from Vault: {str(e)}")
156
-
157
- def __getitem__(self, section):
158
- """Dictionary-style access to configuration sections."""
159
- if section not in self._raw_config:
160
- raise KeyError(f"Section '{section}' not found")
161
- return SectionProxy(self, section)
162
-
163
- def __getattr__(self, section):
164
- """Attribute-style access to configuration sections."""
165
- try:
166
- return self[section]
167
- except KeyError as e:
168
- raise AttributeError(str(e))
169
-
170
-
171
- class SectionProxy:
172
- """Proxy class for configuration section access."""
173
-
174
- def __init__(self, config_loader, section):
175
- self._loader = config_loader
176
- self._section = section
177
-
178
- def __getitem__(self, key):
179
- """Dictionary-style access to configuration values."""
180
- return self._loader.get(self._section, key)
181
-
182
- def get(self, key, default=None):
183
- """Dictionary-style access to configuration values."""
184
- try:
185
- return self._loader.get(self._section, key)
186
- except KeyError:
187
- return default
188
-
189
- def __getattr__(self, key):
190
- """Attribute-style access to configuration values."""
191
- try:
192
- return self[key]
193
- except KeyError as e:
194
- raise AttributeError(str(e))
195
-
196
- def __repr__(self):
197
- """String representation of the section's configuration."""
198
- return yaml.dump(self._loader._raw_config[self._section])
199
-
200
-
201
- if __name__ == "__main__":
202
- config_without_vault = ConfigLoader("config.yml")
203
- print("Without Vault:", config_without_vault.get("jira", "url"))
204
-
205
- # This will only work if you provide a valid Vault secret ID
206
- # and hvac package is installed
207
- config_with_vault = ConfigLoader("config.yml", vault_secret_id=os.getenv("VAULT_SECRET_ID"))
208
-
209
- print("With Vault:", config_with_vault.test.test)
210
- print("With Vault:", config_with_vault["cis"]["cis_client_id"])
211
- print("Try val not exists: ", config_with_vault.test.get("not_exists"))
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes