我正在使用 Alembic 在
Flask
项目中实现迁移。有一个 alembic.ini
文件,必须在其中指定数据库配置:
sqlalchemy.url = driver://user:password@host/dbname
有没有办法从环境变量中指定参数?我尝试以这种方式加载它们
$(env_var)
但没有成功。谢谢!
我已经按照@dirn的建议通过在
sqlalchemy.url
中设置env.py
解决了这个问题。
config.set_main_option('sqlalchemy.url', <db_uri>)
成功了,可以从环境或配置文件加载 <db_uri>
。
我一直在寻找如何管理多数据库的方法
这就是我所做的。我有两个数据库:logs和ohlc
根据doc, 我已经像这样设置了蒸馏器
alembic init --template multidb
databases = logs, ohlc
[logs]
sqlalchemy.url = postgresql://botcrypto:botcrypto@localhost/logs
[ohlc]
sqlalchemy.url = postgresql://botcrypto:botcrypto@localhost/ohlc
[...]
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
# overwrite alembic.ini db urls from the config file
settings_path = os.environ.get('SETTINGS')
if settings_path:
with open(settings_path) as fd:
settings = conf.load(fd, context=os.environ) # loads the config.yml
config.set_section_option("ohlc", "sqlalchemy.url", settings["databases"]["ohlc"])
config.set_section_option("logs", "sqlalchemy.url", settings["databases"]["logs"])
else:
logger.warning('Environment variable SETTINGS missing - use default alembic.ini configuration')
[...]
databases:
logs: postgresql://botcrypto:[email protected]:5432/logs
ohlc: postgresql://botcrypto:[email protected]:5432/ohlc
用法
SETTINGS=config.yml alembic upgrade head
希望能帮到你!
建立在@dimmg的答案之上:
您可以覆盖
sqlalchemy.url
文件中alembic.ini
中指定的env.py
。
env.py
插入
config.set_main_option('sqlalchemy.url', <db_uri>)
其中
env.py
假设您有多个数据库设置,其中包含数据库
db_a
和 db_b
,请插入
config.set_section_option('db_a', 'sqlalchemy.url', <db_uri_a>)
config.set_section_option('db_b', 'sqlalchemy.url', <db_uri_b>)
其中
db_a
和 db_b
的数据库 URI,可以从环境或配置文件中加载。
确保还在
alembic.ini
文件中指出,其中指定的参数已被覆盖在 env.py
文件中。对于在 sqlalchemy.url
中覆盖 URI 的所有数据库,甚至可以完全删除指定 env.py
的部分。
只是为了添加现有的答案,alembic 教程 有这样的说法:
- 通过 SQLAlchemy 连接到数据库的 URL。仅当 env.py 文件调用它们时,才会使用此配置值;在“通用”模板中,sqlalchemy.url
函数中对config.get_main_option("sqlalchemy.url")
的调用以及run_migrations_offline()
函数中对engine_from_config(prefix="sqlalchemy.")
的调用就是引用该键的地方。如果 SQLAlchemy URL 应来自其他来源,例如来自环境变量或全局注册表,或者迁移环境使用多个数据库 URL,则鼓励开发人员更改 env.py 文件以使用任何合适的方法为了获取数据库 URL 或 URL。run_migrations_online()
.env
的文件并将 url 存储在其中:DB_URL = <your_database_url>
sqlalchemy.url
文件中的alembic.ini
如下:sqlalchemy.url = %(DB_URL)s
DB_URL
加载到由 alembic 生成的 env.py
中:from dotenv import load_dotenv
load_dotenv()
config = context.config
config.set_main_option("DB_URL", os.environ["DB_URL"])
alembic revision --autogenerate -m "Baseline"
)从 dotenv 导入 load_dotenv load_dotenv()
env.py(文件名)
def get_url():
return os.getenv("PERSISTENCE_DSN")
def run_migrations_online():
connectable = create_engine(get_url())
with connectable.connect() as connection:
"""
Configure migration context
1. Pass our models metadata
2. Set schema for alembic_version table
3. Load all available schemas
"""
context.configure(
connection=connection,
target_metadata=target_metadata,
version_table_schema=target_metadata.schema,
include_schemas=True,
include_name=include_name,
)
with context.begin_transaction():
"""
By default search_path is setted to "$user",public
that why alembic can't create foreign keys correctly
"""
context.execute('SET search_path TO public')
context.run_migrations()
.env(文件名)
PERSISTENCE_DSN='postgresql://test:[email protected]:5432/test'