pyflexcfg 0.2.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Pavel Tserakhau
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.1
2
+ Name: pyflexcfg
3
+ Version: 0.2.0
4
+ Summary: Flexible configuration handler for Python projects.
5
+ Home-page: https://github.com/pavelterex/PyFlexCfg
6
+ License: MIT
7
+ Author: Pavel T
8
+ Author-email: pavelterex@gmail.com
9
+ Requires-Python: >=3.10,<4.0
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Requires-Dist: cryptography (>=43.0.3,<44.0.0)
20
+ Requires-Dist: pyyaml (>=6.0.2,<7.0.0)
21
+ Project-URL: Repository, https://github.com/pavelterex/PyFlexCfg
22
+ Description-Content-Type: text/markdown
23
+
24
+ # PyFlexCfg
25
+
26
+ Flexible configuration handler for Python projects.
27
+
28
+ ### Description
29
+
30
+ The handler (a.k.a. Cfg) allows to store project's configuration in YAML files and load them at once when imported.
31
+
32
+ ### Installation
33
+
34
+ ```shell
35
+ pip install pyflexcfg
36
+ ```
37
+
38
+ ### Configuration
39
+
40
+ In order to use encryption\decryption for configuration secrets, make sure to
41
+ set an environment variable **PYFLEX_CFG_KEY** with some encryption key, which will be
42
+ used for secrets encryption\decryption.
43
+
44
+ By default, Cfg searches for configuration files in the **config** directory
45
+ within current working dir. In order to specify a different path, crate a nenv variable
46
+ **PYFLEX_CFG_ROOT_PATH** with the absolute path to the configuration root.
47
+
48
+ ### Basic Usage
49
+
50
+ Assuming you have such configuration files structure:
51
+ ```
52
+ \project
53
+ ├─ config
54
+ ├─ general.yaml
55
+ ├─ env
56
+ ├─ dev.yaml
57
+ ├─ prd.yaml
58
+ ```
59
+ And each of the yaml files contains a configuration option **data: test**
60
+
61
+ Just import the Cfg and you can use your configuration at once:
62
+
63
+ ```python
64
+ from pyflexcfg import Cfg
65
+
66
+ print(Cfg.general.data)
67
+ print(Cfg.env.dev.data)
68
+ print(Cfg.env.prd.data)
69
+ ```
70
+
71
+ Make sure the names of directories within your configuration are Python object's attribute name compatible.
72
+
73
+
74
+ ### Override by environment variables
75
+
76
+ There is an option to override values in YAML files with values from environment variables.
77
+ In order to do so, you have to create env variables which reflect the name of config value to be overwritten.
78
+ For example, if you want to overwrite value for
79
+ ```
80
+ Cfg.env.dev.data
81
+ ```
82
+ you have to create env variable like this
83
+ ```
84
+ CFG__ENV__DEV__DATA
85
+ ```
86
+ Having that, you can call
87
+ ```python
88
+ Cfg.update_from_env()
89
+ ```
90
+ and the value from the YAML file will be overwritten by the value from env variable.
91
+
92
+
93
+ ### Handling secrets
94
+
95
+ Any sensitive data to be stored within your configuration files should be encrypted!
96
+
97
+ Encrypt your secret:
98
+ ```python
99
+ from pyflexcfg import AESCipher
100
+
101
+ aes = AESCipher('secret-key')
102
+ aes.encrypt('some-secret-to-encrypt')
103
+ ```
104
+ You will get output like
105
+
106
+ ```python
107
+ b'A1u6BIE2xGtYTSoFRE83H0VHsAW3nrv4WB+T/FEAj1fsh8HIId9r/Rskl0bnDHTI'
108
+ ```
109
+ and it can be stored in yaml file with **!encr** prefix:
110
+
111
+ ```yaml
112
+ my_secret: !encr b'A1u6BIE2xGtYTSoFRE83H0VHsAW3nrv4WB+T/FEAj1fsh8HIId9r/Rskl0bnDHTI'
113
+ ```
114
+
115
+ The next time Cfg will be loading this configuration file it will automatically decrypt
116
+ this value, but do not forget to set up env variable **PYFLEX_CFG_KEY** with your 'secret-key',
117
+ otherwise Cfg won't be able to decrypt the data.
@@ -0,0 +1,94 @@
1
+ # PyFlexCfg
2
+
3
+ Flexible configuration handler for Python projects.
4
+
5
+ ### Description
6
+
7
+ The handler (a.k.a. Cfg) allows to store project's configuration in YAML files and load them at once when imported.
8
+
9
+ ### Installation
10
+
11
+ ```shell
12
+ pip install pyflexcfg
13
+ ```
14
+
15
+ ### Configuration
16
+
17
+ In order to use encryption\decryption for configuration secrets, make sure to
18
+ set an environment variable **PYFLEX_CFG_KEY** with some encryption key, which will be
19
+ used for secrets encryption\decryption.
20
+
21
+ By default, Cfg searches for configuration files in the **config** directory
22
+ within current working dir. In order to specify a different path, crate a nenv variable
23
+ **PYFLEX_CFG_ROOT_PATH** with the absolute path to the configuration root.
24
+
25
+ ### Basic Usage
26
+
27
+ Assuming you have such configuration files structure:
28
+ ```
29
+ \project
30
+ ├─ config
31
+ ├─ general.yaml
32
+ ├─ env
33
+ ├─ dev.yaml
34
+ ├─ prd.yaml
35
+ ```
36
+ And each of the yaml files contains a configuration option **data: test**
37
+
38
+ Just import the Cfg and you can use your configuration at once:
39
+
40
+ ```python
41
+ from pyflexcfg import Cfg
42
+
43
+ print(Cfg.general.data)
44
+ print(Cfg.env.dev.data)
45
+ print(Cfg.env.prd.data)
46
+ ```
47
+
48
+ Make sure the names of directories within your configuration are Python object's attribute name compatible.
49
+
50
+
51
+ ### Override by environment variables
52
+
53
+ There is an option to override values in YAML files with values from environment variables.
54
+ In order to do so, you have to create env variables which reflect the name of config value to be overwritten.
55
+ For example, if you want to overwrite value for
56
+ ```
57
+ Cfg.env.dev.data
58
+ ```
59
+ you have to create env variable like this
60
+ ```
61
+ CFG__ENV__DEV__DATA
62
+ ```
63
+ Having that, you can call
64
+ ```python
65
+ Cfg.update_from_env()
66
+ ```
67
+ and the value from the YAML file will be overwritten by the value from env variable.
68
+
69
+
70
+ ### Handling secrets
71
+
72
+ Any sensitive data to be stored within your configuration files should be encrypted!
73
+
74
+ Encrypt your secret:
75
+ ```python
76
+ from pyflexcfg import AESCipher
77
+
78
+ aes = AESCipher('secret-key')
79
+ aes.encrypt('some-secret-to-encrypt')
80
+ ```
81
+ You will get output like
82
+
83
+ ```python
84
+ b'A1u6BIE2xGtYTSoFRE83H0VHsAW3nrv4WB+T/FEAj1fsh8HIId9r/Rskl0bnDHTI'
85
+ ```
86
+ and it can be stored in yaml file with **!encr** prefix:
87
+
88
+ ```yaml
89
+ my_secret: !encr b'A1u6BIE2xGtYTSoFRE83H0VHsAW3nrv4WB+T/FEAj1fsh8HIId9r/Rskl0bnDHTI'
90
+ ```
91
+
92
+ The next time Cfg will be loading this configuration file it will automatically decrypt
93
+ this value, but do not forget to set up env variable **PYFLEX_CFG_KEY** with your 'secret-key',
94
+ otherwise Cfg won't be able to decrypt the data.
@@ -0,0 +1,5 @@
1
+ from .components.encryption import AESCipher
2
+ from .components.misc import AttrDict
3
+ from .config_handler import ConfigHandler as Cfg
4
+
5
+ __all__ = ['Cfg', 'AESCipher', 'AttrDict']
@@ -0,0 +1,10 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+
4
+ class ICipher(ABC):
5
+
6
+ @abstractmethod
7
+ def encrypt(self, plaintext: str) -> bytes: ...
8
+
9
+ @abstractmethod
10
+ def decrypt(self, encrypted: bytes | str) -> str: ...
@@ -0,0 +1,8 @@
1
+ # Name of the environment variable containing encryption key
2
+ ENCRYPTION_KEY_ENV_VAR = 'PYFLEX_CFG_KEY'
3
+
4
+ # env variable which contains the name of the root directory of project's configuration
5
+ ROOT_CONFIG_PATH_ENV = 'PYFLEX_CFG_ROOT_PATH'
6
+
7
+ # name of the root directory of project's configuration
8
+ ROOT_CONFIG_DIR_NAME = 'config'
@@ -0,0 +1,54 @@
1
+ import base64
2
+ import hashlib
3
+ import os
4
+
5
+ from cryptography.hazmat.backends import default_backend
6
+ from cryptography.hazmat.primitives import padding
7
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
8
+
9
+ from .abstractclasses import ICipher
10
+
11
+ AES_BLOCK_SIZE = 16
12
+
13
+
14
+ class AESCipher(ICipher):
15
+ def __init__(self, key: str):
16
+ """
17
+ Initializes the AES cipher with a static key provided as a string.
18
+ The string key is hashed to ensure it fits the length in bytes required by AES.
19
+
20
+ :param key: encryption key string
21
+ """
22
+ self.key = hashlib.sha256(key.encode('utf-8')).digest()
23
+
24
+ def encrypt(self, plaintext: str) -> bytes:
25
+ """
26
+ Encrypts a plaintext string using AES CBC mode with PKCS7 padding.
27
+
28
+ :param plaintext: plaintext string to encrypt
29
+ :return: encrypted data as bytes IV prepended
30
+ """
31
+ iv = os.urandom(AES_BLOCK_SIZE)
32
+ cipher = Cipher(algorithms.AES(self.key), modes.CBC(iv), backend=default_backend())
33
+ encryptor = cipher.encryptor()
34
+ padder = padding.PKCS7(128).padder()
35
+ padded_data = padder.update(plaintext.encode('utf-8')) + padder.finalize()
36
+ encrypted = encryptor.update(padded_data) + encryptor.finalize()
37
+ return base64.b64encode(iv + encrypted)
38
+
39
+ def decrypt(self, encrypted: bytes | str) -> str:
40
+ """
41
+ Decrypts an encrypted string using AES CBC mode with PKCS7 padding.
42
+
43
+ :param encrypted: encrypted data as bytes or string IV prepended
44
+ :return: decrypted plaintext string
45
+ """
46
+ encrypted = base64.b64decode(encrypted)
47
+ iv = encrypted[:AES_BLOCK_SIZE]
48
+ actual_encrypted_data = encrypted[AES_BLOCK_SIZE:]
49
+ cipher = Cipher(algorithms.AES(self.key), modes.CBC(iv), backend=default_backend())
50
+ decryptor = cipher.decryptor()
51
+ padded_plaintext = decryptor.update(actual_encrypted_data) + decryptor.finalize()
52
+ unpadder = padding.PKCS7(128).unpadder()
53
+ plaintext_bytes = unpadder.update(padded_plaintext) + unpadder.finalize()
54
+ return plaintext_bytes.decode('utf-8')
@@ -0,0 +1,71 @@
1
+ import os
2
+ from pathlib import Path
3
+ from typing import AnyStr, Sequence
4
+
5
+ import yaml
6
+
7
+ from .constants import ROOT_CONFIG_DIR_NAME, ROOT_CONFIG_PATH_ENV
8
+ from .misc import AttrDict
9
+ from .yaml_loader import YamlLoader
10
+
11
+
12
+ class HandlerMeta(type):
13
+ """
14
+ Metaclass for Config Handler class.
15
+
16
+ General purpose is to load values from existing configuration files while being imported,
17
+ so no additional initialization is required.
18
+ """
19
+ config_root = os.getenv(ROOT_CONFIG_PATH_ENV, Path.cwd() / ROOT_CONFIG_DIR_NAME)
20
+
21
+ def __new__(cls, name, bases, namespace):
22
+ init_attrs = AttrDict(namespace)
23
+
24
+ if not cls.config_root.exists():
25
+ raise RuntimeError(f'Configuration root path {cls.config_root} is not found!')
26
+
27
+ cls.load_config(cls.config_root, init_attrs)
28
+ return super().__new__(cls, name, bases, init_attrs)
29
+
30
+ def __str__(cls):
31
+ """ Pretty print current settings. """
32
+ dct = {k: v for k, v in list(cls.__dict__.items()) if not k.startswith('_') and not callable(getattr(cls, k))}
33
+ return str(dct)
34
+
35
+ @classmethod
36
+ def to_attrdict(cls, data: AnyStr | AttrDict | Sequence) -> AnyStr | AttrDict | Sequence:
37
+ if isinstance(data, dict):
38
+ for key, value in data.items():
39
+ data[key] = cls.to_attrdict(value)
40
+ data = AttrDict(**data)
41
+
42
+ elif isinstance(data, list | tuple):
43
+ for index, item in enumerate(data):
44
+ data[index] = cls.to_attrdict(item)
45
+
46
+ return data
47
+
48
+ @classmethod
49
+ def load_config(cls, config_path: Path, dct: AttrDict) -> None:
50
+ """
51
+ Traverse root config dir recursively and update given AttrDict with loaded YAML files' values.
52
+
53
+ :param config_path: root directory of configuration
54
+ :param dct: AttrDict instance to be updated with loaded values
55
+ """
56
+ for item in config_path.iterdir():
57
+ if item.is_dir():
58
+ try:
59
+ dct[item.name] = AttrDict()
60
+ except KeyError:
61
+ raise RuntimeError(f'Directory "{item.name}" is not valid for namespace assignment!')
62
+ cls.load_config(item, dct[item.name])
63
+
64
+ if item.suffix in ('.yml', '.yaml'):
65
+ cls._load_yaml_from_file(dct, item)
66
+
67
+ @classmethod
68
+ def _load_yaml_from_file(cls, dct: AttrDict | object, file: Path) -> None:
69
+ with file.open() as cfg_file:
70
+ data = cls.to_attrdict(yaml.load(cfg_file, YamlLoader))
71
+ setattr(dct, file.stem, data)
@@ -0,0 +1,32 @@
1
+ from typing import Any
2
+
3
+
4
+ class AttrDict(dict):
5
+ """
6
+ Implementation of a dict class, which is also able to operate with attributes in an object-like manner.
7
+
8
+ Since _setitem_ and _getitem_ methods aren't overridden, it can be inherited from a dict class, having all its
9
+ under-the-hood optimisations, instead of inheriting from UserDict class which is less optimised.
10
+ """
11
+
12
+ def __getattr__(self, name: str) -> Any:
13
+ try:
14
+ value = self[name]
15
+ if isinstance(value, dict) and not isinstance(value, AttrDict):
16
+ self[name] = AttrDict(value)
17
+ return self[name]
18
+ except KeyError:
19
+ raise AttributeError(name)
20
+
21
+ def __setattr__(self, key: str, value: Any) -> None:
22
+ self[key] = value
23
+
24
+
25
+ class Secret(str):
26
+ """ Simple implementation of secret string with masked output. """
27
+
28
+ def __repr__(self) -> str:
29
+ return '********'
30
+
31
+ def __str__(self) -> str:
32
+ return '********'
@@ -0,0 +1,58 @@
1
+ import os
2
+ from pathlib import Path, PurePosixPath, PureWindowsPath, PurePath
3
+ from typing import Optional
4
+
5
+ from yaml import Loader, ScalarNode, SequenceNode
6
+
7
+ from .abstractclasses import ICipher
8
+ from .constants import ENCRYPTION_KEY_ENV_VAR
9
+ from .encryption import AESCipher
10
+ from .misc import Secret
11
+
12
+
13
+ class YamlLoader(Loader):
14
+ """ Customized loader for YAML files. """
15
+
16
+ def __init__(self, *args, **kwargs):
17
+ self._cipher: Optional[ICipher] = None
18
+ super().__init__(*args, **kwargs)
19
+
20
+ def string(loader: Loader, node: SequenceNode) -> str:
21
+ """ String-like constructor, combines parts as a string. """
22
+ seq = loader.construct_sequence(node)
23
+ return ''.join([str(i) for i in seq])
24
+
25
+ def path_win(loader: Loader, node: SequenceNode) -> PureWindowsPath:
26
+ """ Path-like constructor, combines parts as a Windows path. """
27
+ seq = loader.construct_sequence(node)
28
+ return PureWindowsPath(*seq)
29
+
30
+ def path_posix(loader: Loader, node: SequenceNode) -> PurePosixPath:
31
+ """ Path-like constructor, combines parts as a Posix path. """
32
+ seq = loader.construct_sequence(node)
33
+ return PurePosixPath(*seq)
34
+
35
+ def home_dir(loader: Loader, node: SequenceNode) -> PurePath:
36
+ """ Constructor for paths (both Windows and Posix), starting from User's HOME directory. """
37
+ _home = Path.home()
38
+ seq = loader.construct_sequence(node)
39
+ return PurePath(_home, *seq)
40
+
41
+ def encrypted(loader: Loader, node: ScalarNode) -> str:
42
+ """ Constructor for encrypted data (strings and bytes). """
43
+ encr_value = loader.construct_scalar(node)
44
+ return Secret(self.cipher.decrypt(encr_value))
45
+
46
+ self.add_constructor('!string', string)
47
+ self.add_constructor('!path_win', path_win)
48
+ self.add_constructor('!path_posix', path_posix)
49
+ self.add_constructor('!home_dir', home_dir)
50
+ self.add_constructor('!encr', encrypted)
51
+
52
+ @property
53
+ def cipher(self):
54
+ if not self._cipher:
55
+ if (key := os.getenv(ENCRYPTION_KEY_ENV_VAR)) is None:
56
+ raise RuntimeError(f'Env variable {ENCRYPTION_KEY_ENV_VAR} is not found!')
57
+ self._cipher = AESCipher(key)
58
+ return self._cipher
@@ -0,0 +1,22 @@
1
+ import os
2
+
3
+ from .components.metaclasses import HandlerMeta
4
+ from .components.misc import AttrDict
5
+
6
+
7
+ class ConfigHandler(AttrDict, metaclass=HandlerMeta):
8
+
9
+ @classmethod
10
+ def update_from_env(cls) -> None:
11
+ """ Override existing config values with ones loaded from env variables. """
12
+ for var_name, var_value in os.environ.items():
13
+ var_name = var_name.lower()
14
+
15
+ if var_name.startswith('cfg__'):
16
+ var_name = var_name.replace('cfg__', 'cls.', 1).replace('__', '.')
17
+
18
+ # try to identify whether the value is boolean or not before putting it in Cfg
19
+ if (var_lower := var_value.lower()) in ('true', 'false'):
20
+ exec(f'{var_name} = bool({var_lower.capitalize()})') # as bool
21
+ else:
22
+ exec(f'{var_name} = "{var_value}"') # as str
@@ -0,0 +1,6 @@
1
+ from pyflexcfg.config_handler import ConfigHandler as Cfg
2
+
3
+
4
+ print(Cfg)
5
+ pass
6
+
@@ -0,0 +1,28 @@
1
+ [tool.poetry]
2
+ name = "pyflexcfg"
3
+ version = "0.2.0"
4
+ description = "Flexible configuration handler for Python projects."
5
+ authors = ["Pavel T <pavelterex@gmail.com>"]
6
+ license = "MIT license"
7
+ readme = "README.md"
8
+ repository = "https://github.com/pavelterex/PyFlexCfg"
9
+ classifiers = [
10
+ "Development Status :: 4 - Beta",
11
+ "Intended Audience :: Developers",
12
+ "License :: OSI Approved :: MIT License",
13
+ "Programming Language :: Python :: 3",
14
+ "Operating System :: OS Independent",
15
+ ]
16
+
17
+ [tool.poetry.dependencies]
18
+ python = "^3.10"
19
+ cryptography = "^43.0.3"
20
+ pyyaml = "^6.0.2"
21
+
22
+ [tool.poetry.group.dev.dependencies]
23
+ pytest = "^8.3.3"
24
+ pytest-assume = "^2.4.3"
25
+
26
+ [build-system]
27
+ requires = ["poetry-core"]
28
+ build-backend = "poetry.core.masonry.api"