Skip to content

Manager

SnapEnv Base Settings.

This module contains the base settings and configurations used across different environments within the SnapEnv framework. It provides constants, environment detection, and directory setup necessary for the application to function correctly, especially in containerized environments such as Docker.

The module also defines the SnapEnvCommonSettings class, which manages the configuration parameters, their sources, and provides methods to retrieve environment-specific information like the local server name and platform.

ATTRIBUTE DESCRIPTION
SECRETS_DIR

Directory path where secret files are located, depending on whether the code is running inside a Docker container or not.

TYPE: str

PLATFORM

Mapping of platform identifiers to their respective names.

TYPE: dict

ENVIRONMENT

Current environment identifier, sourced from the ENVIRONMENT environment variable.

TYPE: str

Secret Directory Setup

The module ensures that the secrets directory exists unless running inside a Docker container, where Docker handles directory management.

Environment File Selection

The .env file used by the application is determined by the value of the ENVIRONMENT environment variable.

  • If ENVIRONMENT is set to a value (e.g., 'production'), the application will look for a file named <ENVIRONMENT>.env (e.g., production.env).
  • This file name is specified in the model_config attribute of the SnapEnvCommonSettings class under env_file.
  • The .env file should be located in the root directory of the project.
  • If ENVIRONMENT is not set, the application will default to using .env as the configuration file.

SnapEnvCommonSettings ¤

Bases: BaseSettings

SnapEnv common configuration parameters shared between all instances.

This class reads configuration parameters defined within the class, from environment variables, and from the configuration file's. The source priority is as follows (from highest to lowest):

  • env_settings
  • dotenv_settings
  • init_settings
  • file_secret_settings
Environment Variables

The following environment variables should be defined:

  • HOSTNAME (on Linux servers only, set by OS)
  • COMPUTERNAME (on Windows servers only, set by OS)
  • ENVIRONMENT (on all servers)
File Paths

Paths where the .env file should be placed:

  • Linux: /home/<user>/.local
  • macOS: /home/<user>/.local
  • Windows: C:\Users\<user>\AppData\Roaming\Python
  • Python/Poetry/Docker: Root dir of the project

Paths where secret files should be placed:

  • Linux: /home/<user>/.local/secrets
  • macOS: /home/<user>/.local/secrets
  • Windows: C:\Users\<user>\AppData\Roaming\Python\secrets
  • Docker: /run/secrets
ATTRIBUTE DESCRIPTION
model_config

Configuration dictionary for settings including secrets and .env file handling.

TYPE: SettingsConfigDict

METHOD DESCRIPTION
settings_customise_sources

Customizes the source priority order.

Source code in src/snapenv_core/settings/manager.py
class SnapEnvCommonSettings(BaseSettings):
    r"""
    SnapEnv common configuration parameters shared between all instances.

    This class reads configuration parameters defined within the class,
    from environment variables, and from the configuration file's. The source priority
    is as follows (from highest to lowest):

    - env_settings
    - dotenv_settings
    - init_settings
    - file_secret_settings

    Environment Variables
    ---------------------
    The following environment variables should be defined:

    - HOSTNAME (on Linux servers only, set by OS)
    - COMPUTERNAME (on Windows servers only, set by OS)
    - ENVIRONMENT (on all servers)

    File Paths
    ----------
    Paths where the <environment>.env file should be placed:

    - Linux: /home/<user\>/.local
    - macOS: /home/<user\>/.local
    - Windows: C:\\Users\\<user\>\\AppData\\Roaming\\Python
    - Python/Poetry/Docker: Root dir of the project

    Paths where secret files should be placed:

    - Linux: /home/<user\>/.local/secrets
    - macOS: /home/<user\>/.local/secrets
    - Windows: C:\\Users\\<user\>\\AppData\\Roaming\\Python\\secrets
    - Docker: /run/secrets

    Attributes
    ----------
    model_config : SettingsConfigDict
        Configuration dictionary for settings including secrets and .env file handling.

    Methods
    -------
    settings_customise_sources(settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings):
        Customizes the source priority order.
    """

    model_config = SettingsConfigDict(
        extra="ignore",
        secrets_dir=SECRETS_DIR,
        env_file_encoding="utf-8",
        env_file=f"{ENVIRONMENT}.env",
    )

    @classmethod
    def settings_customise_sources(
        cls,
        settings_cls: type[BaseSettings],
        init_settings: PydanticBaseSettingsSource,
        env_settings: PydanticBaseSettingsSource,
        dotenv_settings: PydanticBaseSettingsSource,
        file_secret_settings: PydanticBaseSettingsSource,
    ) -> tuple[PydanticBaseSettingsSource, ...]:
        """
        Change source priority order (env trumps environment).

        Parameters
        ----------
        settings_cls : type[BaseSettings]
            The settings class.
        init_settings : PydanticBaseSettingsSource
            Initial settings source.
        env_settings : PydanticBaseSettingsSource
            Environment variable settings source.
        dotenv_settings : PydanticBaseSettingsSource
            Dotenv file settings source.
        file_secret_settings : PydanticBaseSettingsSource
            Secret file settings source.

        Returns
        -------
        tuple[PydanticBaseSettingsSource, ...]
            Tuple of settings sources in the new priority order.
        """
        return (env_settings, dotenv_settings, init_settings, file_secret_settings)

settings_customise_sources(settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings) classmethod ¤

Change source priority order (env trumps environment).

PARAMETER DESCRIPTION
settings_cls

The settings class.

TYPE: type[BaseSettings]

init_settings

Initial settings source.

TYPE: PydanticBaseSettingsSource

env_settings

Environment variable settings source.

TYPE: PydanticBaseSettingsSource

dotenv_settings

Dotenv file settings source.

TYPE: PydanticBaseSettingsSource

file_secret_settings

Secret file settings source.

TYPE: PydanticBaseSettingsSource

RETURNS DESCRIPTION
tuple[PydanticBaseSettingsSource, ...]

Tuple of settings sources in the new priority order.

Source code in src/snapenv_core/settings/manager.py
@classmethod
def settings_customise_sources(
    cls,
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]:
    """
    Change source priority order (env trumps environment).

    Parameters
    ----------
    settings_cls : type[BaseSettings]
        The settings class.
    init_settings : PydanticBaseSettingsSource
        Initial settings source.
    env_settings : PydanticBaseSettingsSource
        Environment variable settings source.
    dotenv_settings : PydanticBaseSettingsSource
        Dotenv file settings source.
    file_secret_settings : PydanticBaseSettingsSource
        Secret file settings source.

    Returns
    -------
    tuple[PydanticBaseSettingsSource, ...]
        Tuple of settings sources in the new priority order.
    """
    return (env_settings, dotenv_settings, init_settings, file_secret_settings)

initialize_secret_dir() ¤

Initialize the secret directory if not running inside a Docker container.

This function checks for the presence of the "/.dockerenv" file to determine if the code is running inside a Docker container. If the file does not exist, it creates the directory specified by the SECRETS_DIR module variable.

RETURNS DESCRIPTION
None
RAISES DESCRIPTION
OSError

If the directory creation fails due to insufficient permissions or other file system-related issues.

Notes

The function uses os.makedirs with exist_ok=True, so if the directory specified by SECRETS_DIR already exists, the function will not raise an exception.

Source code in src/snapenv_core/settings/manager.py
def initialize_secret_dir() -> None:
    """
    Initialize the secret directory if not running inside a Docker container.

    This function checks for the presence of the "/.dockerenv" file to determine
    if the code is running inside a Docker container. If the file does not exist,
    it creates the directory specified by the `SECRETS_DIR` module variable.

    Returns
    -------
    None

    Raises
    ------
    OSError
        If the directory creation fails due to insufficient permissions or other
        file system-related issues.

    Notes
    -----
    The function uses `os.makedirs` with `exist_ok=True`, so if the directory
    specified by `SECRETS_DIR` already exists, the function will not raise an
    exception.
    """
    if not os.path.exists("/.dockerenv"):
        os.makedirs(SECRETS_DIR, exist_ok=True)