So, Im trying to setup Alembic with FastAPI and Im having a problem with Pydantic's BaseSettings, I get a validation error (variables not found) because it doesnt find the .env file (?)
It can be solved by changing env_file = ".env"
to env_file = "../.env"
in the BaseSettings
class Config
but that makes the error happen when running main.py, I tried setting it as an absolute path with env_file = os.path.abspath("../../.env")
but that didnt work.
What should I do?
config.py:
import os
from functools import lru_cache
from pydantic_settings import BaseSettings
abs_path_env = os.path.abspath("../../.env")
class Settings(BaseSettings):
APP_NAME: str = "AppName"
SQLALCHEMY_URL: str
ENVIRONMENT: str
class Config:
env_file = ".env" # Works with uvicorn run command from my-app/project/
# env_file = "../.env" Works with alembic command from my-app/alembic
# env_file = abs_path_env
@lru_cache()
def get_settings():
return Settings()
Project folders:
my-app
├── alembic
│ ├── versions
│ ├── alembic.ini
│ ├── env.py
│ ├── README
│ └── script.py.mako
├── project
│ ├── core
│ │ ├── __init__.py
│ │ └── config.py
│ └── __init__.py
├── __init__.py
├── .env
└── main.py