0

In this FastAPI projet I'm trying to load an environment variable called DATABASE_URL inside Alembic env.py file and use it as follows:

env.py

from alembic import context
import os
from dotenv import load_dotenv

config = context.config
load_dotenv('./../.env')
DATABASE_URL = os.environ.get("DATABASE_URL")
config.set_main_option('sqlalchemy.url', DATABASE_URL)

.env

DATABASE_URL=mysql+mysqldb://root:123321@localhost/MyDatabase

My .env file location relative to env.py:

alembic/
    env.py
app/
.env

...

I tried using the python shell to check whether DATABASE_URL is being loaded and it did. Wrapping the DATABASE_UR in str() did not help.

Could you show me a way to resolve this? Thank you!

William Le
  • 825
  • 1
  • 9
  • 16

1 Answers1

0

I found out after a while that load_env() must be supplied with a full .env path in order to properly load the environment variables from .env file, not just a relative path, or else the environment variables will be None, hence the TypeError.

Therefore, I changed my env.py file as follows:

from alembic import context
import os
from dotenv import load_dotenv

config = context.config

BASE_DIR = os.path.abspath(os.path.dirname(__file__)) # get current env.py path
load_dotenv(os.path.join(BASE_DIR, '../', '.env')) # full path to .env
DATABASE_URL = os.environ.get("DATABASE_URL")
config.set_main_option('sqlalchemy.url', DATABASE_URL)

William Le
  • 825
  • 1
  • 9
  • 16