Pydantic Settings v2 - getting Field Required Error

mycfg.py

from pydantic_settings import BaseSettings, SettingsConfigDict

class CommonCfg(BaseSettings):
      SYS_USER: str
      LTDRN_REST_ENDPOINT: str
      FULLRN_REST_ENDPOINT: str
      model_config  = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8', case_sensitive=True, extra='forbid')

class ProductionCfg(CommonCfg):
      HOST: str
      model_config = SettingsConfigDict(env_file='prod.env', env_file_encoding='utf-8', case_sensitive=True, extra='forbid')

#print(CommonCfg.model_config)
#cfg_values = CommonCfg()
cfg_values = ProductionCfg()
print(cfg_values.LTDRN_REST_ENDPOINT)
print(cfg_values.FULLRN_REST_ENDPOINT)
print(cfg_values.SYS_USER)
#print(cfg_values.HOST)

my .env file contains

LTDRN_REST_ENDPOINT=/rest/latest/custom/create_limited_draft_rn FULLRN_REST_ENDPOINT=/rest/latest/custom/create_full_draft_rn

my prod.env file contains

HOST=https://at.host.com

command given SYS_USER=xyzuser python mycfg.py

My understanding was when inherit CommonCfg in ProductionCfg I will get LTDRN_REST_ENDPOINT and FULLRN_REST_ENDPOINT values from .env (kind of master file) and HOST from prod.env file. But I get "Field Required" error.

Traceback (most recent call last):

  File "/home/build/python-app/path/mycfg.py", line 34, in <module>
    cfg_values = ProductionCfg()
  File "/home/build/python-app/venv/lib/python3.9/site-packages/pydantic_settings/main.py", line 71, in __init__
    super().__init__(
  File "/home/build/python-app/venv/lib/python3.9/site-packages/pydantic/main.py", line 164, in __init__
    __pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__)
pydantic_core._pydantic_core.ValidationError: 2 validation errors for ProductionCfg
LTDRN_REST_ENDPOINT
  Field required [type=missing, input_value={'HOST': 'https://host...', 'SYS_USER': 'xyzuser'}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.4/v/missing
FULLRN_REST_ENDPOINT
  Field required [type=missing, input_value={'HOST': 'https://host...', 'SYS_USER': 'xyzuser'}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.4/v/missing

If I set default values in CommonCfg it works but I was trying to go by Inheritance of config from common to production.

Upvotes: 0

Views: 736

Answers (1)

Design Team
Design Team

Reputation: 1

I solved this issue by correcting my path the the .env file. I have a config.py file in the same folder as my .env file (folder is called backend).

I had to change my code to SettingsConfigDict(env_file="backend/.env") even though they are in the same place.

Upvotes: 0

Related Questions