Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1.3.0 - Added new method get_envs #3

Merged
merged 1 commit into from
Jul 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,25 @@ and this project adheres to [Semantic Versioning].

- /

## [1.3.0] - 2024-07-14

### Added

Added new method `get_envs` that returns all the environment variables set in a dict.
```python
>>> settings.get_envs()
{'PREFIX_APP_IP': '0.0.0.0'}
```

### Fixed

Fixed docstring indentation.

## [1.2.2] - 2024-03-10

## New Release v.1.2.2

## Fixes
### Fixes

Fixes `TypeError: unsupported operand type(s) for |: 'type' and 'type'.` error when using Python version < 3.10

Expand Down Expand Up @@ -81,7 +95,8 @@ print(settings.mysql.databases.prod) # Output: 'new_value'
[semantic versioning]: https://semver.org/spec/v2.0.0.html

<!-- Versions -->
[unreleased]: https://github.com/gilbn/simple-toml-configurator/compare/1.2.2...HEAD
[unreleased]: https://github.com/gilbn/simple-toml-configurator/compare/1.3.0...HEAD
[1.3.0]: https://github.com/gilbn/simple-toml-configurator/releases/tag/1.3.0
[1.2.2]: https://github.com/gilbn/simple-toml-configurator/releases/tag/1.2.2
[1.2.1]: https://github.com/gilbn/simple-toml-configurator/releases/tag/1.2.1
[1.1.0]: https://github.com/gilbn/simple-toml-configurator/releases/tag/1.1.0
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "Simple-TOML-Configurator"
version = "1.2.2"
version = "1.3.0"
license = {text = "MIT License"}
authors = [{name = "GilbN", email = "me@gilbn.dev"}]
description = "A simple TOML configurator for Python"
Expand Down
4 changes: 2 additions & 2 deletions src/simple_toml_configurator/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from .toml_configurator import Configuration
from .toml_configurator import Configuration, ConfigObject

__all__ = ["Configuration"]
__all__ = ["Configuration"]
40 changes: 29 additions & 11 deletions src/simple_toml_configurator/toml_configurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
from pathlib import Path
import tomlkit
from tomlkit import TOMLDocument
from .exceptions import *
from .exceptions import TOMLConfigUpdateError, TOMLWriteConfigError, TOMLCreateConfigError, TOMLLoadConfigError

__version__ = "1.2.2"
__version__ = "1.3.0"

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -88,15 +88,15 @@ def logging_debug(self, value: bool):
configure_logging(log_level)
logger.debug(f"Debug logging set to {value}")

defaults = {
"logging": {
"debug": False
...
}
defaults = {
"logging": {
"debug": False
...
}

config_path = os.environ.get("CONFIG_PATH", "config")
settings = CustomConfiguration()
settings.init_config(config_path, defaults, "app_config"))
config_path = os.environ.get("CONFIG_PATH", "config")
settings = CustomConfiguration()
settings.init_config(config_path, defaults, "app_config"))
```
"""

Expand Down Expand Up @@ -153,6 +153,7 @@ def init_config(self, config_path:str|Path, defaults:dict[str,dict], config_file
self.config_path:str|Path = config_path
self.config_file_name:str = f"{config_file_name}.toml"
self.env_prefix:str = env_prefix
self._envs: dict[str,Any] = {}
self._full_config_path:str = os.path.join(self.config_path, self.config_file_name)
self.config:TOMLDocument = self._load_config()
self._sync_config_values()
Expand Down Expand Up @@ -237,6 +238,22 @@ def get_settings(self) -> dict[str, Any]:
settings[f"{table}_{key}"] = value
return settings

def get_envs(self) -> dict[str, Any]:
"""Get all the environment variables we set as a dictionary.

Examples:
```pycon
>>> defaults = {...}
>>> settings = Configuration()
>>> settings.init_config("config", defaults, "app_config"))
>>> settings.get_envs()
{'PREFIX_APP_IP': '0.0.0.0'}

Returns:
dict[str, Any]: Dictionary with all environment variables name as keys and their value.
"""
return self._envs

def _set_attributes(self) -> dict[str, Any]:
"""Set all config keys as attributes on the class.

Expand Down Expand Up @@ -312,6 +329,7 @@ def _update_os_env(self, table:str, key:str, value:Any) -> None:
else:
env_var = self._make_env_name(table, key)
os.environ[env_var] = str(value)
self._envs[env_var] = value

def _set_os_env(self) -> None:
"""Set all config keys as environment variables.
Expand Down Expand Up @@ -389,7 +407,7 @@ def _write_config_to_file(self) -> None:
"""Update and write the config to file"""
self.logger.debug("Writing config to file")
try:
with Path(self._full_config_path).open("w") as conf:
with Path(self._full_config_path).open("w", encoding="utf-8") as conf:
toml_document = tomlkit.dumps(self.config)
# Use regular expression to replace consecutive empty lines with a single newline
cleaned_toml = re.sub(r'\n{3,}', '\n\n', toml_document)
Expand Down
7 changes: 6 additions & 1 deletion tests/test_toml_configurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,4 +269,9 @@ def test_make_env_name_without_prefix(config_instance: Configuration):
table = "app"
key = "port"
env_name = config_instance._make_env_name(table, key)
assert env_name == "APP_PORT"
assert env_name == "APP_PORT"

def test_get_envs(config_instance: Configuration):
config_instance.logging.debug = False
config_instance.update()
assert config_instance.get_envs() == {"LOGGING_DEBUG": False}
Loading