From a4f373aa6ad5f410b26a605a4c82031611009190 Mon Sep 17 00:00:00 2001 From: Ziga Luksic Date: Thu, 2 Nov 2023 15:58:55 +0100 Subject: [PATCH] make save and load use env profile --- sentinelhub/commands.py | 2 ++ sentinelhub/config.py | 13 +++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/sentinelhub/commands.py b/sentinelhub/commands.py index 68140cc2..89e6e2ad 100644 --- a/sentinelhub/commands.py +++ b/sentinelhub/commands.py @@ -66,6 +66,8 @@ def config(show: bool, profile: str | None, **params: Any) -> None: if getattr(sh_config, param) != value: setattr(sh_config, param, value) + sh_config.save(profile=profile) + for param, value in sh_config.to_dict(mask_credentials=False).items(): if value != getattr(old_config, param): click.echo(f"The value of parameter `{param}` was updated to {value!r}") diff --git a/sentinelhub/config.py b/sentinelhub/config.py index a40e4df0..026af574 100644 --- a/sentinelhub/config.py +++ b/sentinelhub/config.py @@ -114,8 +114,7 @@ def __init__(self, profile: str | None = None, *, use_defaults: bool = False, ** :param use_defaults: Does not load the configuration file, returns config object with defaults only. :param kwargs: Any fields of `SHConfig` to be updated. Overrides settings from `config.toml` and environment. """ - if profile is None: - profile = os.environ.get(SH_PROFILE_ENV_VAR, default=DEFAULT_PROFILE) + profile = self._get_profile(profile) if not use_defaults: env_kwargs = { @@ -141,12 +140,17 @@ def __repr__(self) -> str: content = ",\n ".join(f"{key}={value!r}" for key, value in config_dict.items()) return f"{self.__class__.__name__}(\n {content},\n)" + @staticmethod + def _get_profile(profile: str | None) -> str: + return profile if profile is not None else os.environ.get(SH_PROFILE_ENV_VAR, default=DEFAULT_PROFILE) + @classmethod - def load(cls, profile: str = DEFAULT_PROFILE) -> SHConfig: + def load(cls, profile: str | None = None) -> SHConfig: """Loads configuration parameters from the config file at `SHConfig.get_config_location()`. :param profile: Which profile to load from the configuration file. """ + profile = cls._get_profile(profile) filename = cls.get_config_location() if not os.path.exists(filename): cls(use_defaults=True).save(profile) # store default configuration to standard location @@ -159,11 +163,12 @@ def load(cls, profile: str = DEFAULT_PROFILE) -> SHConfig: return cls(use_defaults=True, **configurations_dict[profile]) - def save(self, profile: str = DEFAULT_PROFILE) -> None: + def save(self, profile: str | None = None) -> None: """Saves configuration parameters to the config file at `SHConfig.get_config_location()`. :param profile: Under which profile to save the configuration. """ + profile = self._get_profile(profile) file_path = Path(self.get_config_location()) file_path.parent.mkdir(parents=True, exist_ok=True)