Skip to content

Settings

commons.settings

Classes:

Name Description
AppSettings

Common app settings.

OpenAISettings

Common settings class for OpenAI settings.

AzureOpenAISettings

Common settings class for native Azure OpenAI settings.

AzureOpenAIEmbeddingSettings

Settings class for Azure OpenAI embedding models.

MSSQLSettings

MSSQL database connection settings.

LocalDatabaseSettings

Local SQLite database settings.

DatabaseSettings

Database configuration settings.

LocalStorageSettings

Local filesystem storage settings.

AzureStorageSettings

Azure Blob Storage settings.

StorageSettings

Storage configuration settings.

RoleAssignmentConfig

Configuration for a role assignment.

StandardUser

A user defined in settings configuration.

StandardUserSettings

Settings container for user definitions.

SMTPSettings

Connection to an SMTP server for sending mails.

Functions:

Name Description
read_settings
read_settings_object

Read a nested settings dict and transform it into an object.

Attributes:

Name Type Description
T
LOG

T module-attribute

T = TypeVar('T')

LOG module-attribute

LOG = logging.getLogger(__name__)

AppSettings dataclass

AppSettings(
    version: str = "",
    environment: str = "",
    data_dir: str = "",
    public_url: str = "",
    **_kwargs
)

Common app settings.

Methods:

Name Description
read

Attributes:

Name Type Description
data_dir Path
version str
environment str
public_url str

Public URL of the app, e.g. https://app.example.com, without a trailing slash; empty when unknown (locally).

Source code in src/commons/settings.py
def __init__(
    self, version: str = "", environment: str = "", data_dir: str = "", public_url: str = "", **_kwargs
) -> None:
    self.version = version
    self.environment = environment
    self.public_url = str(public_url).rstrip("/")

    if not self.version:
        self.version = _get_git_commit_ref() or "<no version>"

    if not self.environment:
        self.environment = "local"

    if not data_dir:
        self.data_dir = (path_operators.get_project_root_dir() / ".app_data").absolute()
    else:
        self.data_dir = Path(data_dir)

data_dir instance-attribute

data_dir: Path

version instance-attribute

version: str = version

environment instance-attribute

environment: str = environment

public_url instance-attribute

public_url: str = str(public_url).rstrip('/')

Public URL of the app, e.g. https://app.example.com, without a trailing slash; empty when unknown (locally).

read staticmethod

read() -> AppSettings
Source code in src/commons/settings.py
@staticmethod
def read() -> "AppSettings":
    return read_settings_object("", AppSettings)

OpenAISettings dataclass

OpenAISettings(
    api_key: str = "",
    model: str = "gpt-5-mini",
    embedding_model: str = "text-embedding-3-small",
    **_kwargs
)

Common settings class for OpenAI settings.

Methods:

Name Description
read

Attributes:

Name Type Description
model str
embedding_model str
api_key str
Source code in src/commons/settings.py
def __init__(
    self, api_key: str = "", model: str = "gpt-5-mini", embedding_model: str = "text-embedding-3-small", **_kwargs
) -> None:
    self._api_key = api_key
    self.model = model
    self.embedding_model = embedding_model

model class-attribute instance-attribute

model: str = model

embedding_model class-attribute instance-attribute

embedding_model: str = embedding_model

api_key property

api_key: str

read staticmethod

read() -> OpenAISettings
Source code in src/commons/settings.py
@staticmethod
def read() -> "OpenAISettings":
    return read_settings_object("models.openai", OpenAISettings)

AzureOpenAISettings dataclass

AzureOpenAISettings(
    api_key: str = "",
    azure_deployment: str = "gpt-4o-mini",
    azure_endpoint: str = "",
    api_version: str = "2025-01-01-preview",
    embedding_model: str = "text-embedding-3-small",
    **_kwargs
)

Common settings class for native Azure OpenAI settings.

Methods:

Name Description
read

Attributes:

Name Type Description
azure_deployment str
azure_endpoint str
api_version str
embedding_model str
api_key str
Source code in src/commons/settings.py
def __init__(
    self,
    api_key: str = "",
    azure_deployment: str = "gpt-4o-mini",
    azure_endpoint: str = "",
    api_version: str = "2025-01-01-preview",
    embedding_model: str = "text-embedding-3-small",
    **_kwargs,
) -> None:
    self._api_key = api_key
    self.azure_deployment = azure_deployment
    self.azure_endpoint = azure_endpoint
    self.api_version = api_version
    # Deprecated: use AzureOpenAIEmbeddingSettings instead. Kept for backwards compatibility.
    self.embedding_model = embedding_model

azure_deployment class-attribute instance-attribute

azure_deployment: str = azure_deployment

azure_endpoint class-attribute instance-attribute

azure_endpoint: str = azure_endpoint

api_version class-attribute instance-attribute

api_version: str = api_version

embedding_model class-attribute instance-attribute

embedding_model: str = embedding_model

api_key property

api_key: str

read staticmethod

Source code in src/commons/settings.py
@staticmethod
def read() -> "AzureOpenAISettings":
    return read_settings_object("models.azure_openai", AzureOpenAISettings)

AzureOpenAIEmbeddingSettings dataclass

AzureOpenAIEmbeddingSettings(
    api_key: str = "",
    azure_deployment: str = "text-embedding-3-small",
    azure_endpoint: str = "",
    api_version: str = "2023-05-15",
    **_kwargs
)

Settings class for Azure OpenAI embedding models.

Methods:

Name Description
read

Attributes:

Name Type Description
azure_deployment str
azure_endpoint str
api_version str
api_key str
Source code in src/commons/settings.py
def __init__(
    self,
    api_key: str = "",
    azure_deployment: str = "text-embedding-3-small",
    azure_endpoint: str = "",
    api_version: str = "2023-05-15",
    **_kwargs,
) -> None:
    self._api_key = api_key
    self.azure_deployment = azure_deployment
    self.azure_endpoint = azure_endpoint
    self.api_version = api_version

azure_deployment class-attribute instance-attribute

azure_deployment: str = azure_deployment

azure_endpoint class-attribute instance-attribute

azure_endpoint: str = azure_endpoint

api_version class-attribute instance-attribute

api_version: str = api_version

api_key property

api_key: str

read staticmethod

Source code in src/commons/settings.py
@staticmethod
def read() -> "AzureOpenAIEmbeddingSettings":
    return read_settings_object("models.embeddings.azure_openai", AzureOpenAIEmbeddingSettings)

MSSQLSettings dataclass

MSSQLSettings(
    server: str = "",
    database: str = "",
    username: str = "",
    password: str = "",
    port: int = 1433,
    query: dict[str, str] | None = None,
)

MSSQL database connection settings.

Attributes:

Name Type Description
server str

The FQN of the database server.

database str

The name of the database to access.

username str

The username used to access the database.

password str

The password to access the database.

port int

TCP port of the database server. Defaults to 1433.

query dict[str, str] | None

Optional overrides for the ODBC connection-string query parameters (driver, Encrypt, TrustServerCertificate, Connection Timeout, ...). Values provided here are merged on top of the built-in defaults, so only keys that need to change must be listed.

server class-attribute instance-attribute

server: str = ''

database class-attribute instance-attribute

database: str = ''

username class-attribute instance-attribute

username: str = ''

password class-attribute instance-attribute

password: str = ''

port class-attribute instance-attribute

port: int = 1433

query class-attribute instance-attribute

query: dict[str, str] | None = None

LocalDatabaseSettings dataclass

LocalDatabaseSettings(path: str | None = None)

Local SQLite database settings.

Attributes:

Name Type Description
path str | None

The file path for the local SQLite database file.

path class-attribute instance-attribute

path: str | None = None

DatabaseSettings dataclass

DatabaseSettings(
    mode: Literal["local", "mssql"] = "local",
    local: dict[str, Any] | None = None,
    mssql: dict[str, Any] | None = None,
)

Database configuration settings.

Attributes:

Name Type Description
mode Literal['local', 'mssql']

The database mode for the application. - local: Will instantiate a local SQLite database. The database file path can be configured via local.path. If the path is relative, it is resolved against AppSettings.data_dir. Defaults to .app_data/database.db when not configured. - mssql: Will use mssql settings to connect to a MSSQL database instance.

local LocalDatabaseSettings | None

Local SQLite database settings (optional, used when mode is local).

mssql MSSQLSettings | None

MSSQL connection settings (required when mode is mssql).

Methods:

Name Description
read

Read database settings from configuration.

Source code in src/commons/settings.py
def __init__(
    self,
    mode: Literal["local", "mssql"] = "local",
    local: dict[str, Any] | None = None,
    mssql: dict[str, Any] | None = None,
) -> None:
    self.mode = mode
    self.local = LocalDatabaseSettings(**local) if local else None
    self.mssql = MSSQLSettings(**mssql) if mssql else None

mode class-attribute instance-attribute

mode: Literal['local', 'mssql'] = mode

local class-attribute instance-attribute

local: LocalDatabaseSettings | None = (
    LocalDatabaseSettings(**local) if local else None
)

mssql class-attribute instance-attribute

mssql: MSSQLSettings | None = (
    MSSQLSettings(**mssql) if mssql else None
)

read staticmethod

read() -> DatabaseSettings

Read database settings from configuration.

Source code in src/commons/settings.py
@staticmethod
def read() -> "DatabaseSettings":
    """Read database settings from configuration."""
    return read_settings_object("database", DatabaseSettings)

LocalStorageSettings dataclass

LocalStorageSettings(root: str | None = None, **_kwargs)

Local filesystem storage settings.

Attributes:

Name Type Description
root str | None

The root directory for the local file store. If None, falls back to AppSettings.data_dir / "files".

Source code in src/commons/settings.py
def __init__(self, root: str | None = None, **_kwargs):
    self.root = root

root class-attribute instance-attribute

root: str | None = root

AzureStorageSettings dataclass

AzureStorageSettings(
    auth_mode: Literal[
        "default_credential",
        "connection_string",
        "account_key",
    ] = "default_credential",
    account_url: str = "",
    container: str = "",
    connection_string: str = "",
    account_name: str = "",
    account_key: str = "",
    **_kwargs
)

Azure Blob Storage settings.

Attributes:

Name Type Description
auth_mode Literal['default_credential', 'connection_string', 'account_key']

Authentication mode for connecting to Azure Storage. - default_credential: Use azure.identity.DefaultAzureCredential (managed identity, az login, env vars). Requires account_url. - connection_string: Authenticate via a full connection string. - account_key: Authenticate via account name + account key. Requires account_name and account_key (and optionally account_url).

account_url str

Blob service endpoint, e.g. https://myaccount.blob.core.windows.net.

container str

Name of the blob container that backs this Files instance.

account_name str

Storage account name (used with account_key auth).

Methods:

Name Description
read
Source code in src/commons/settings.py
def __init__(
    self,
    auth_mode: Literal["default_credential", "connection_string", "account_key"] = "default_credential",
    account_url: str = "",
    container: str = "",
    connection_string: str = "",
    account_name: str = "",
    account_key: str = "",
    **_kwargs,
) -> None:
    self.auth_mode = auth_mode
    self.account_url = account_url
    self.container = container
    self.account_name = account_name
    self._connection_string = connection_string
    self._account_key = account_key

auth_mode class-attribute instance-attribute

auth_mode: Literal[
    "default_credential", "connection_string", "account_key"
] = auth_mode

account_url class-attribute instance-attribute

account_url: str = account_url

container class-attribute instance-attribute

container: str = container

account_name class-attribute instance-attribute

account_name: str = account_name

connection_string property

connection_string: str

account_key property

account_key: str

read staticmethod

Source code in src/commons/settings.py
@staticmethod
def read() -> "AzureStorageSettings":
    return read_settings_object("storage.azure", AzureStorageSettings)

StorageSettings dataclass

StorageSettings(
    mode: Literal["local", "sql", "azure"] = "local",
    local: (
        dict[str, Any] | LocalStorageSettings | None
    ) = None,
    azure: (
        dict[str, Any] | AzureStorageSettings | None
    ) = None,
    **_kwargs: Any
)

Storage configuration settings. Unknown configuration keys are ignored for forward compatibility.

Attributes:

Name Type Description
mode Literal['local', 'sql', 'azure']

The storage backend for the application. - local: Use LocalFiles rooted at local.root (or AppSettings.data_dir / "files" if not set). - sql: Use SQLFiles against the engine produced by DatabaseSettings. No StorageSettings-level config is needed. - azure: Use AzureFiles configured by azure.

local LocalStorageSettings | None

Local filesystem settings (optional, used when mode is local).

azure AzureStorageSettings | None

Azure Blob Storage settings (required when mode is azure).

Methods:

Name Description
read
Source code in src/commons/settings.py
def __init__(
    self,
    mode: Literal["local", "sql", "azure"] = "local",
    local: dict[str, Any] | LocalStorageSettings | None = None,
    azure: dict[str, Any] | AzureStorageSettings | None = None,
    **_kwargs: Any,
) -> None:
    self.mode = mode

    if isinstance(local, dict):
        self.local = LocalStorageSettings(**local)
    else:
        self.local = local

    if isinstance(azure, dict):
        self.azure = AzureStorageSettings(**azure)
    else:
        self.azure = azure

local class-attribute instance-attribute

local: LocalStorageSettings | None = None

azure class-attribute instance-attribute

azure: AzureStorageSettings | None = None

mode class-attribute instance-attribute

mode: Literal['local', 'sql', 'azure'] = mode

read staticmethod

read() -> StorageSettings
Source code in src/commons/settings.py
@staticmethod
def read() -> "StorageSettings":
    return read_settings_object("storage", StorageSettings)

RoleAssignmentConfig

Bases: BaseModel

Configuration for a role assignment.

Defines which role is assigned to a user within a specific scope.

Attributes:

Name Type Description
role str
scope str

role class-attribute instance-attribute

role: str = Field(
    description="The name of the role to assign."
)

scope class-attribute instance-attribute

scope: str = Field(
    description="The scope path where the role applies (e.g., '/projects/my-project')."
)

StandardUser

Bases: BaseModel

A user defined in settings configuration.

Used for bootstrapping users from configuration files (e.g., settings.toml).

At most one of password or password_hash may be set. Prefer password_hash so no plain-text password is kept in the settings. A user with neither has no password: they can't sign in with a password, only by other means such as an email link or code (commons.users.login_tokens).

Generate a hash with the command line helper (prompts for the password)::

python -m commons.users hash-password

# or non-interactively
echo -n "secret" | python -m commons.users hash-password --stdin

and put the printed value into the settings::

[[users]]
username = "john.doe"
firstname = "John"
lastname = "Doe"
email = "john@example.com"
password_hash = "$2b$12$..."

The hash must match the repository's password verifier (bcrypt by default).

Attributes:

Name Type Description
username str
firstname str
lastname str
email str
password str | None
password_hash str | None
roles list[RoleAssignmentConfig]

username class-attribute instance-attribute

username: str = Field(
    description="Unique username for authentication."
)

firstname class-attribute instance-attribute

firstname: str = Field(description="User's first name.")

lastname class-attribute instance-attribute

lastname: str = Field(description="User's last name.")

email class-attribute instance-attribute

email: str = Field(description="User's email address.")

password class-attribute instance-attribute

password: str | None = Field(
    default=None,
    description="Plain-text password (will be hashed when creating the user).",
)

password_hash class-attribute instance-attribute

password_hash: str | None = Field(
    default=None,
    description="Pre-computed password hash (stored as-is when creating the user).",
)

roles class-attribute instance-attribute

roles: list[RoleAssignmentConfig] = Field(
    default_factory=list,
    description="List of role names to assign to the user.",
)

StandardUserSettings

Bases: BaseModel

Settings container for user definitions.

Reads user configuration from settings files and provides a list of users to be created or synchronized with the user repository (see UsersRepository.init_from_settings()).

Passwords should be configured as password_hash per user; create the hash with python -m commons.users hash-password (see StandardUser).

Methods:

Name Description
read

Read users settings from configuration.

Attributes:

Name Type Description
model_config
users list[StandardUser]

model_config class-attribute instance-attribute

model_config = ConfigDict(extra='ignore')

users class-attribute instance-attribute

users: list[StandardUser] = Field(
    default_factory=list,
    description="List of users defined in configuration.",
)

read staticmethod

Read users settings from configuration.

Source code in src/commons/settings.py
@staticmethod
def read() -> "StandardUserSettings":
    """Read users settings from configuration."""
    return read_settings_object("", StandardUserSettings)

SMTPSettings

Bases: BaseModel

Connection to an SMTP server for sending mails.

Read from app.smtp.*; host and from_address are required. Not specific to login mails: every mail sender of an app can use it (first commons.users.login_tokens.SMTPLoginTokenSender). The connection is always encrypted: ssl uses TLS from the start (port 465), starttls upgrades the connection (port 587).

TOML (e.g. a Strato mailbox)::

[app.smtp]  # settings.toml
host = "smtp.strato.de"
security = "ssl"  # port 465; default "starttls" (587)
username = "login@example.com"
from_address = "CaseSight <login@example.com>"  # must belong to the mailbox

[app.smtp]  # settings.secrets.toml
password = "..."

Env var overrides follow the standard pattern, e.g. APP__SMTP__PASSWORD. Env var values are evaluated as Python literals, so a password that looks like a number must be quoted: APP__SMTP__PASSWORD='"123456"'.

The password is a SecretStr: it doesn't show in repr() or str(); read it with settings.password.get_secret_value().

Methods:

Name Description
read

Read the SMTP settings from app.smtp.

Attributes:

Name Type Description
model_config
host str
port int | None
security Literal['ssl', 'starttls']
username str
password SecretStr
from_address str
timeout float

model_config class-attribute instance-attribute

model_config = ConfigDict(extra='ignore')

host class-attribute instance-attribute

host: str = Field(
    min_length=1,
    description="Host name of the SMTP server.",
)

port class-attribute instance-attribute

port: int | None = Field(
    default=None,
    description="Port; defaults to 465 for `ssl` and 587 for `starttls`.",
)

security class-attribute instance-attribute

security: Literal["ssl", "starttls"] = Field(
    default="starttls",
    description="How the connection is encrypted.",
)

username class-attribute instance-attribute

username: str = Field(
    default="",
    description="User to sign in with; no sign-in if empty.",
)

password class-attribute instance-attribute

password: SecretStr = Field(
    default=SecretStr(""),
    description="Password of the user.",
)

from_address class-attribute instance-attribute

from_address: str = Field(
    min_length=1,
    description="Sender address, e.g. `App <login@example.com>`.",
)

timeout class-attribute instance-attribute

timeout: float = Field(
    default=30,
    gt=0,
    description="Seconds to wait for the server before failing.",
)

read staticmethod

read() -> SMTPSettings

Read the SMTP settings from app.smtp.

Raises:

Type Description
ValidationError

If app.smtp is missing, a required key (host, from_address) is missing or empty, or a value is invalid; the error names the keys.

Source code in src/commons/settings.py
@staticmethod
def read() -> "SMTPSettings":
    """Read the SMTP settings from ``app.smtp``.

    Raises:
        pydantic.ValidationError: If ``app.smtp`` is missing, a required key (``host``,
            ``from_address``) is missing or empty, or a value is invalid; the error names the keys.
    """
    return read_settings_object("smtp", SMTPSettings)

read_settings cached

read_settings(
    user_home_settings_dir: str = ".wellner",
    user_home_settings_file: str = "settings.toml",
) -> dict
Source code in src/commons/settings.py
@lru_cache
def read_settings(user_home_settings_dir: str = ".wellner", user_home_settings_file: str = "settings.toml") -> dict:
    root_dir = path_operators.get_project_root_dir()
    environment = os.environ.get("APP__ENVIRONMENT", "local")
    user_home = Path.home()

    paths = [
        root_dir / "pyproject.toml",
        root_dir / "settings.toml",
        root_dir / f"settings.{environment}.toml",
        root_dir / ".secrets.toml",
        root_dir / "settings.secrets.toml",
        user_home / user_home_settings_dir / user_home_settings_file,
    ]

    result: dict = {}

    for path in paths:
        result = dicts.deep_merge(result, _read_toml(path))

    result = _merge_env_vars(result)

    return result

read_settings_object

read_settings_object(
    key: str,
    model_cls: Type[T],
    user_home_settings_dir: str = ".wellner",
    user_home_settings_file: str = "settings.toml",
) -> T

Read a nested settings dict and transform it into an object.

Parameters:

Name Type Description Default
key str

Dot-separated path to the config section (e.g., "vectorstore.chroma")

required
model_cls Type[T]

Class to instantiate. If it has a model_validate method (Pydantic), that will be used. Otherwise, the dict is unpacked as **kwargs.

required
user_home_settings_dir str

Directory name in user home for settings

'.wellner'
user_home_settings_file str

Settings filename in user home directory

'settings.toml'

Returns:

Type Description
T

Instance of model_cls populated with the config values

Raises:

Type Description
KeyError

If the key path doesn't exist in settings

Source code in src/commons/settings.py
def read_settings_object(
    key: str,
    model_cls: Type[T],
    user_home_settings_dir: str = ".wellner",
    user_home_settings_file: str = "settings.toml",
) -> T:
    """Read a nested settings dict and transform it into an object.

    Args:
        key: Dot-separated path to the config section (e.g., "vectorstore.chroma")
        model_cls: Class to instantiate. If it has a `model_validate` method (Pydantic),
                   that will be used. Otherwise, the dict is unpacked as **kwargs.
        user_home_settings_dir: Directory name in user home for settings
        user_home_settings_file: Settings filename in user home directory

    Returns:
        Instance of model_cls populated with the config values

    Raises:
        KeyError: If the key path doesn't exist in settings
    """
    settings = read_settings(user_home_settings_dir, user_home_settings_file)

    data = _get_nested(settings, key)

    if hasattr(model_cls, "model_validate"):
        return model_cls.model_validate(data)  # type: ignore[attr-defined]

    return model_cls(**data)