Search code examples
pythonenvironment-variablesconfigfastapipydantic

How to have two class inherited from pydantic_settings (Base setting), FastAPI


I am trying to have two classes inherited from in pydantic_settings BaseSettings.

from pydantic_settings import BaseSettings
from dotenv import load_dotenv
load_dotenv(verbose=True)

class Setting(BaseSettings):
     name:str
     age:int
    
     class Config:
         env_file = ".env"
    
settings = Setting()
    
class JWT(BaseSettings):
     s_key:str
     otp:int
    
     class Config:
        env_file = ".env"
    
jwt = JWT()

But i am getting this error :

Extra inputs are not permitted [type=extra_forbidden, input_value='300', input_type=str]

If i use all variables in single class it works.(my .env has all fields mentioned in this config)


Solution

  • Pydantic settings load environment variables automatically and BaseSettings does not allow extra fields. In addition, you should use SettingsConfigDict instead of Config class after Pydantic V2

    from pydantic_settings import BaseSettings, SettingsConfigDict
    
    
    class Setting(BaseSettings):
        model_config = SettingsConfigDict(env_file=".env", extra="ignore")  # see `extra` field. default is `forbid`
        name: str
        age: int
    
        
    settings = Setting()
        
    class JWT(BaseSettings):
        model_config = SettingsConfigDict(env_file=".env", extra="allow")  # same here
        s_key: str
        otp: int
    
    
    jwt = JWT()
    

    extra can be one of

    • allow
    • ignore
    • forbid; this is default

    Here's the actual Pydantic code in pydantic/config.py

    ExtraValues = Literal['allow', 'ignore', 'forbid']
    

    TL;DR

    Set extra field in SettingsConfigDict except forbid.

    Ref: https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support