From f0babffe6fade75c1852bae9637291a03dca992c Mon Sep 17 00:00:00 2001 From: Russ Allbery Date: Mon, 19 Feb 2024 15:55:40 -0800 Subject: [PATCH] Accept timedelta config values as strings The conversion to the new pydantic-settings module and use of proper timedelta data types for configuration options meant that parsing of number of seconds as strings from environment variables broke. Add a field validator to convert strings to integers so that they'll be parsed correctly. --- src/vocutouts/config.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/vocutouts/config.py b/src/vocutouts/config.py index 37ce151..6e41924 100644 --- a/src/vocutouts/config.py +++ b/src/vocutouts/config.py @@ -5,7 +5,7 @@ from datetime import timedelta from pathlib import Path -from pydantic import Field, PostgresDsn +from pydantic import Field, PostgresDsn, field_validator from pydantic_settings import BaseSettings, SettingsConfigDict from safir.logging import LogLevel, Profile @@ -91,6 +91,18 @@ class Config(BaseSettings): env_prefix="CUTOUT_", case_sensitive=False ) + @field_validator("lifetime", "sync_timeout", "timeout", mode="before") + @classmethod + def _parse_as_seconds(cls, v: int | str | timedelta) -> int | timedelta: + """Convert timedelta strings so they are parsed as seconds.""" + if isinstance(v, timedelta): + return v + try: + return int(v) + except ValueError as e: + msg = f"value {v} must be an integer number of seconds" + raise ValueError(msg) from e + def uws_config(self) -> UWSConfig: """Convert to configuration for the UWS subsystem.""" return UWSConfig(