3

I'm using Alembic in a Flask project in PyCharm IDE and I would like to use environment variables instead of storing database configurations in the alembic.ini file.

So this is my modified env.py

import os
...

def get_url():
    return f'mysql+pymysql://{os.getenv("DB_UID", "username")}:{os.getenv("DB_PWD", "password")}@{os.getenv("DB_SERVER", "host")}/{os.getenv("DB_NAME", "db")}'


def run_migrations_offline():
    ...

    #url = config.get_main_option("sqlalchemy.url")
    url = get_url()
    print(url)

    ...

def run_migrations_online():

    # connectable = engine_from_config(
    #     config.get_section(config.config_ini_section),
    #     prefix="sqlalchemy.",
    #     poolclass=pool.NullPool,
    # )

    url = get_url()
    print(url)
    connectable = create_engine(url)

    ...

And this is what it prints:

mysql+pymysql://username:password@host/db

but it works fine while reading environment variables in the config.py of my project. This is the structure:

project/
    alembic/
        versions/
        env.py
        README
        script.py.mako
    app/
    alembic.ini
    config.py
    run.py

and the config.py:

import os

class Config(object):

    #DB CONFIG
    serverDB = os.getenv('DB_SERVER', None)
    nameDB = os.getenv('DB_NAME', None)
    pwdDB = os.getenv('DB_PWD', None)
    uidDB = os.getenv('DB_UID', None)
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://'+uidDB+':'+pwdDB+'@'+serverDB+'/'+nameDB

I'm new to Flask, can someone explain me why this happens and how can I solve it? Thanks

EDIT: If i set the environment variables using the terminal it works fine. So the problem is reading the environment variables in PyCharm.

dust
  • 31
  • 3
  • Does this answer your question? [cannot get environment variables set in Flask application](https://stackoverflow.com/questions/40643498/cannot-get-environment-variables-set-in-flask-application) – CodeLikeBeaker Dec 31 '20 at 15:35
  • @CodeLikeBeaker no, it prints always mysql+pymysql://username:password@host/db – dust Jan 01 '21 at 13:09

0 Answers0