Skip to content

Commit d082e3e

Browse files
committed
Add a custom CSV parser as fallback for complex pydantic-settings values
1 parent 19bf5b1 commit d082e3e

2 files changed

Lines changed: 39 additions & 5 deletions

File tree

olli/config.py

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,23 @@
11
"""Configuration loading and validation."""
22

3+
import json
4+
import typing as t
35

46
from loguru import logger
5-
from pydantic import BaseModel, field_validator
6-
from pydantic_settings import BaseSettings
7+
from pydantic import BaseModel, field_validator, fields
8+
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource
9+
10+
11+
def custom_decode_complex_value(
12+
__: str,
13+
___: fields.FieldInfo,
14+
value: t.Any,
15+
) -> t.Any:
16+
"""Parse complex values as CSV if they cannot be parsed as JSON."""
17+
try:
18+
return json.loads(value)
19+
except ValueError:
20+
return value.split(",")
721

822

923
class EnvConfig(
@@ -15,6 +29,25 @@ class EnvConfig(
1529
):
1630
"""Our default configuration for models that should load from .env files."""
1731

32+
@classmethod
33+
def settings_customise_sources(
34+
cls,
35+
settings_cls: type[BaseSettings],
36+
init_settings: PydanticBaseSettingsSource,
37+
env_settings: PydanticBaseSettingsSource,
38+
dotenv_settings: PydanticBaseSettingsSource,
39+
file_secret_settings: PydanticBaseSettingsSource,
40+
) -> tuple[PydanticBaseSettingsSource, ...]:
41+
"""Monkey patch default sources to have the custom CSV parser fallback."""
42+
dotenv_settings.decode_complex_value = custom_decode_complex_value
43+
env_settings.decode_complex_value = custom_decode_complex_value
44+
return (
45+
init_settings,
46+
env_settings,
47+
dotenv_settings,
48+
file_secret_settings,
49+
)
50+
1851

1952
class _LokiConfig(EnvConfig, env_prefix="loki_"):
2053
"""Loki specific configuration."""
@@ -69,7 +102,7 @@ def warn_above_ten(cls, value: list[TokenConfig]) -> list[TokenConfig]:
69102
This is because we cannot handle more than 10 token triggers at once until we
70103
batch triggers into groups of 10 to distribute to the webhook.
71104
"""
72-
if len(value) > 10: # noqa: PLR2004
105+
if len(value) > 10:
73106
logger.warning("More than 10 token triggers in one period cannot be handled, be careful.")
74107

75108
return value

pyproject.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,13 @@ olli = "python -m olli"
4646
target-version = "py311"
4747
extend-exclude = [".cache"]
4848
ignore = [
49-
"ANN002", "ANN003", "ANN101", "ANN102",
49+
"ANN002", "ANN003", "ANN101", "ANN102", "ANN401",
5050
"ARG003",
5151
"C901",
5252
"D100", "D104", "D105", "D107", "D203", "D212", "D214", "D215", "D416",
5353
"EM101",
54-
"TRY003"
54+
"PLR",
55+
"TRY003",
5556
]
5657
line-length = 120
5758
select = ["ALL"]

0 commit comments

Comments
 (0)