Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read variables from .env file using pydantic?

I am trying to read variables from .env file, that looks like this:

A = 'aaa'
B = 'bbb'

To read variables I create Settings() class in test_vars.py:

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    a: str
    b: str

    model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8')


config = Settings()

These two files are in the same directory.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When trying to create Settings() class, I get this error:

pydantic_core._pydantic_core.ValidationError: 2 validation errors for Settings
a
  Field required [type=missing, input_value={}, input_type=dict]

Probably I should edit .env somehow, but I’m not sure.

>Solution :

You code works fine.

When you run this code it will look for the .env file in the current working directory. So, you should run this code from the directory, where your .env file is placed. Or you can specify correct path to the env file from your working directory.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading