6

I was following a Python API development course on FreeCodeCamp on YouTube where we moved some static values to environment variables. This is the error I got while trying to reload the app:

pydantic.error_wrappers.ValidationError: 8 validation errors for Settings
database_hostname
  field required (type=value_error.missing)
database_port
  field required (type=value_error.missing)
database_password
  field required (type=value_error.missing)
database_name
  field required (type=value_error.missing)
database_username
  field required (type=value_error.missing)
secret_key
  field required (type=value_error.missing)
algorithm
  field required (type=value_error.missing)
access_token_expire_minutes
  field required (type=value_error.missing)

Here's my schema (config.py):

class Settings(BaseSettings):
    database_hostname: str
    database_port: str
    database_password: str
    database_name: str
    database_username: str
    secret_key: str
    algorithm: str
    access_token_expire_minutes: int

    class Config:
        env_file = '../.env'

Here's my environment (.env):

DATABASE_HOSTNAME=localhost
DATABASE_PORT=5432
DATABASE_PASSWORD=password
DATABASE_NAME=fastapi
DATABASE_USERNAME=postgres
SECRET_KEY=123456789
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60

How do I make my BaseSettings class able to read the environment variables in the .env file?

2 Answers 2

7

I was able to resolve the error by using a full path in the project. I've got the main project folder and within that the .env file and an app folder. My config.py file is in app/ so the relative path to the env file from config is /../.env:

Don't forget to import os

class Settings(BaseSettings):
    database_hostname: str
    database_port: str
    database_password: str
    database_name: str
    database_username: str
    secret_key: str
    algorithm: str
    access_token_expire_minutes: int

    class Config:
        env_file = f"{os.path.dirname(os.path.abspath(__file__))}/../.env"
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

if .env file is the same folder as your main app folder.

class Settings(BaseSettings):
    database_hostname: str
    database_port: str
    database_password: str
    database_name: str
    database_username: str
    secret_key: str
    algorithm: str
    access_token_expire_minutes: int

    class Config:
        env_file = '.env'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.