Pydantic: BaseSettings can't read from .env file

Created on 4 Apr 2020  路  11Comments  路  Source: samuelcolvin/pydantic

Bug

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.3
            pydantic compiled: True
                 install path: /home/xxx/playground/fastapi/.venv/lib/python3.6/site-packages/pydantic
               python version: 3.6.9 (default, Nov  7 2019, 10:44:02)  [GCC 8.3.0]
                     platform: Linux-5.3.0-7642-generic-x86_64-with-Ubuntu-18.04-bionic
     optional deps. installed: ['email-validator']

The example is from here https://github.com/samuelcolvin/pydantic/pull/1011 and still don't work. Documentation don't help also.

Note that I removed default value for Settings.foo

.env

foo=baz

settings.py

from pydantic import BaseSettings


class Settings(BaseSettings):
    foo: str = 'bar'

    class Config:
        env_file = ".env"


settings = Settings()

Exception

In [1]: from settings import settings
---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
<ipython-input-1-89c4f5117928> in <module>
----> 1 from settings import settings

~/playground/fastapi/settings.py in <module>
      9 
     10 
---> 11 settings = Settings()

~/playground/fastapi/.venv/lib/python3.6/site-packages/pydantic/env_settings.cpython-36m-x86_64-linux-gnu.so in pydantic.env_settings.BaseSettings.__init__()

~/playground/fastapi/.venv/lib/python3.6/site-packages/pydantic/main.cpython-36m-x86_64-linux-gnu.so in pydantic.main.BaseModel.__init__()

ValidationError: 1 validation error for Settings
foo
  field required (type=value_error.missing)

In [2]: 

If I load_dotenv() manually - it works:

In [2]: from dotenv import load_dotenv

In [3]: load_dotenv()
Out[3]: True

In [4]: from settings import settings

In [5]: settings
Out[5]: Settings(foo='baz')

In [6]: 
bug

Most helpful comment

Getting the same issue with v1.6. Shouldn't this be able to work without needing to call load_dotenv()?

All 11 comments

works fine for me.

foo is not a required field, so you're error message works fine.

Try using pydantic v1.4 and check your setup.

Getting the same issue with v1.6. Shouldn't this be able to work without needing to call load_dotenv()?

Just adding my own experience with Pydantic 1.6.1...

from pydantic import BaseSettings
from dotenv import load_dotenv
from pathlib import Path
load_dotenv(dotenv_path=Path("~/.env"))


class AppSettings(BaseSettings):
    es: str

    class Config:
        env_file = "~/.env"


settings = AppSettings()

...results in this error:

Traceback (most recent call last):
  File "settings.py", line 14, in <module>
    settings = AppSettings()
  File "pydantic/env_settings.py", line 33, in pydantic.env_settings.BaseSettings.__init__
  File "pydantic/main.py", line 346, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for AppSettings
es
  field required (type=value_error.missing)

I get the same error without the load_dotenv() line as well

@HenryDashwood The issue here is that you use ~/.env, which is not directly resolved by pathlib.Path.
You could change it to

   class Config:
        env_file = os.path.expanduser('~/.env')

Maybe we could add expanduser directly in the code when env_path is created

Ah that's great. Thanks for that!

1804 is merge and I can't produce this.

Closing this issue, if anyone else is having trouble and can explain the issue, please create a new issue.

Same problem here...

`

   db_url="postgres" # .env file

   class Settings(BaseSettings):
       db_url: str

       class Config:
          env_file = ".env"


   settings = Settings()


  @lru_cache()
  def get_settings():
     return {
        "db_url": settings.db_url,
   }

`
Getting error -> pydantic.error_wrappers.ValidationError: 1 validation error for Settings db_url field required (type=value_error.missing)

It worked for me only with load_dotenv(), so can confirm this is not working nor with relative nor with absolute paths or I'm doing something wrong

@orihomie I had the same issue because I had nested settings classes. To address the issue, I had to add .env file configuration explicitly in each class.

Same here, does NOT work for me IF running my app through python:
python app/main.py
but it DOES work if running it through uvicorn:
uvicorn main:app --reload

I have a config.py file with content:

class Settings(BaseSettings):
    APP_NAME: str = 'FastAPI Template'
    PORT: int
    admin_email: Optional[str]

    class Config:
        env_file = ".env"

.env file is in the same directory as this config.py file.

ENVIRONMENT="dev"
APP_NAME="Flask Template"
PORT=8001

I get the following error:
python app/main.py Traceback (most recent call last): File "app/main.py", line 5, in <module> from api.apiv1 import router_api_v1 File "/Users/aalam/Dropbox/code/fastApi/fastApi-template/app/api/apiv1.py", line 5, in <module> from api.demo_feature_1.v1.main import router as router_v1_demo_feature_1 File "/Users/aalam/Dropbox/code/fastApi/fastApi-template/app/api/demo_feature_1/v1/main.py", line 11, in <module> config = get_settings() File "/Users/aalam/Dropbox/code/fastApi/fastApi-template/app/config.py", line 22, in get_settings return Settings() File "pydantic/env_settings.py", line 34, in pydantic.env_settings.BaseSettings.__init__ File "pydantic/main.py", line 362, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for Settings PORT field required (type=value_error.missing) make: *** [start] Error 1

This is very likely because your .env is not in the current working directory.

From the docs:

either absolute or relative to the current working directory.

E.g. .env being in the same directory as config.py doesn't matter.

We should make this notice more obvious in the docs to stop all these questions.

That said, it is already in the docs, please try to read them before posting questions on closed issues.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

koxudaxi picture koxudaxi  路  25Comments

bradodarb picture bradodarb  路  22Comments

sm-Fifteen picture sm-Fifteen  路  45Comments

chopraaa picture chopraaa  路  18Comments

cazgp picture cazgp  路  34Comments