Skip to content

Commit

Permalink
Fix dotenv settings source problem in handling extra variables with s…
Browse files Browse the repository at this point in the history
…ame prefix in name (#386)
  • Loading branch information
hramezani authored Sep 10, 2024
1 parent a9eb22e commit 287cb22
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
4 changes: 3 additions & 1 deletion pydantic_settings/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -981,7 +981,9 @@ def __call__(self) -> dict[str, Any]:
env_used = False
for field_name, field in self.settings_cls.model_fields.items():
for _, field_env_name, _ in self._extract_field_info(field, field_name):
if env_name.startswith(field_env_name):
if env_name == field_env_name or (
lenient_issubclass(field.annotation, BaseModel) and env_name.startswith(field_env_name)
):
env_used = True
break
if not env_used:
Expand Down
14 changes: 14 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -4978,3 +4978,17 @@ def settings_customise_sources(
env.set('one', '1')
s = Settings(one=True, two=True)
assert s.four is True


def test_dotenv_extra_allow_similar_fields(tmp_path):
p = tmp_path / '.env'
p.write_text('POSTGRES_USER=postgres\nPOSTGRES_USER_2=postgres2\nPOSTGRES_NAME=name')

class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=p, extra='allow')

POSTGRES_USER: str

s = Settings()
assert s.POSTGRES_USER == 'postgres'
assert s.model_dump() == {'POSTGRES_USER': 'postgres', 'postgres_name': 'name', 'postgres_user_2': 'postgres2'}

0 comments on commit 287cb22

Please sign in to comment.