From e8bb5ce009f59da72e6b1eb3e5308827bbaceed8 Mon Sep 17 00:00:00 2001 From: hygienic-books Date: Wed, 4 May 2022 01:33:48 +0200 Subject: [PATCH] feat(db): Change default alembic env.py to get connection string from env vars --- db/env.py | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/db/env.py b/db/env.py index edeff1d..7f81986 100644 --- a/db/env.py +++ b/db/env.py @@ -1,6 +1,10 @@ +import os from logging.config import fileConfig -from sqlalchemy import engine_from_config +# #3 Get connection string from env vars instead of a Git-committed env.py +# http://allan-simon.github.io/blog/posts/python-alembic-with-environment-variables/ +# from sqlalchemy import engine_from_config +from sqlalchemy import engine_from_config, create_engine from sqlalchemy import pool from alembic import context @@ -26,6 +30,18 @@ target_metadata = None # ... etc. +def get_url(): + # #3 Get connection string from env vars instead of a Git-committed env.py + # http://allan-simon.github.io/blog/posts/python-alembic-with-environment-variables/ + return "%s://%s:%s@%s/%s" % ( + os.getenv("DB_DIALECTDRIVER", "mysql"), + os.getenv("DB_USER", "kodi-timekeeper"), + os.getenv("DB_PASSWORD", "kodi-timekeeper"), + os.getenv("DB_HOST", "localhost"), + os.getenv("DB_NAME", "kodi-timekeeper"), + ) + + def run_migrations_offline(): """Run migrations in 'offline' mode. @@ -38,7 +54,10 @@ def run_migrations_offline(): script output. """ - url = config.get_main_option("sqlalchemy.url") + # #3 Get connection string from env vars instead of a Git-committed env.py + # http://allan-simon.github.io/blog/posts/python-alembic-with-environment-variables/ + # url = config.get_main_option("sqlalchemy.url") + url = get_url() context.configure( url=url, target_metadata=target_metadata, @@ -57,11 +76,9 @@ def run_migrations_online(): and associate a connection with the context. """ - connectable = engine_from_config( - config.get_section(config.config_ini_section), - prefix="sqlalchemy.", - poolclass=pool.NullPool, - ) + # #3 Get connection string from env vars instead of a Git-committed env.py + # http://allan-simon.github.io/blog/posts/python-alembic-with-environment-variables/ + connectable = create_engine(get_url()) with connectable.connect() as connection: context.configure(