python-3.x - Alembic 在线模式 FATAL : database does not exist

标签 python-3.x amazon-redshift alembic

我正在使用alembic,当我运行alembic升级头

它返回:sqlalchemy.exc.OperationalError:(psycopg2.OperationalError)致命:数据库“my_db”不存在

我的配置文件具有以下网址:

sqlalchemy.url = redshift+psycopg2://user:pwd@MY_REDSHIFT_HOSTNAME:5439/my_db'

我修改了 run_migrations_online 函数以允许 ssl:

def run_migrations_online():
"""Run migrations in 'online' mode.

In this scenario we need to create an Engine
and associate a connection with the context.

"""
connectable = engine_from_config(
    config.get_section(config.config_ini_section),
    prefix="sqlalchemy.",
    poolclass=pool.NullPool,
    connect_args={'sslmode': 'prefer'}
)

with connectable.connect() as connection:
    context.configure(
        connection=connection, target_metadata=target_metadata
    )

    with context.begin_transaction():
        context.run_migrations()

最佳答案

正如 @zzzeek 所解释的在 this issue ,alembic 不处理数据库的创建。但是,由于不知道您的项目结构,我想说解决您的问题的最简单方法是:

将以下代码添加到您的 base.py 文件(您在其中定义了 SQLAlchemy enginedeclarative_base):

from sqlalchemy_utils import create_database, database_exists

def validate_database():
    if not database_exists(engine.url):
        create_database(engine.url)

请注意,您需要使用以下命令安装 sqlalchemy_utils 软件包:

pip install sqlalchemy-utils

现在,在您的 env.py 模块中,导入新创建的 validate_database 函数并调用它:

from my_app.db_models.base import validate_database

validate_database()

希望这能解决您的问题!

附注我借用了this answer也是如此。

关于python-3.x - Alembic 在线模式 FATAL : database does not exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62832560/

相关文章:

python - 在Python中更改Widget Window的样式和背景颜色

python - 尝试函数调用的变体,直到完成且不引发异常

python - Numpy 中的 3-D 矩阵乘法

SQL查询删除表中连续的重复项

python - 使用 SqlAlchemy 和 Alembic 创建部分索引

python - 更改蒸馏器记录器

python - 将列表列表内的字符串拆分为保留在同一列表中的两个元素

java - Redshift 和 Postgres JDBC 驱动程序都拦截 jdbc ://postgresql connection string

amazon-web-services - 如何让现有用户成为 AWS Redshift 中的 super 用户

python - 属性错误 : module 'alembic.context' has no attribute 'config'