python - SQLAlchemy DB 升级和 MySQL SSH

标签 python mysql flask sqlalchemy flask-sqlalchemy

我有一个 Flask 应用程序,需要在我的 config.py 文件中使用像这样的 SSHTunnel 连接到远程 MysqlDB,我在 init.py 文件中初始化:

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

server =  sshtunnel.SSHTunnelForwarder(
    ('ssh.pythonanywhere.com', 22),
    ssh_password="mypassword",
    ssh_username="myusername",
    remote_bind_address=(myname.mysql.pythonanywhere-services.com', 3306))
server.start()

engine = create_engine('mysql+mysqldb://mynameb:dbpassword@127.0.0.1:%s/dbname' % server.local_bind_port)

连接似乎正常工作,但我无法从迁移中升级数据库(flask 数据库升级),因为我没有使用 SQLALCHEMY_DATABASE_URI 连接到我的数据库。还有一种方法可以通过 ssh 连接到数据库来进行数据库升级吗?

最佳答案

Alembic 不必使用数据库 URI 连接到数据库即可运行升级。在您的 alembic\env.py 文件中将有一个如下所示的函数:

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)

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

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

重要的是,当 alembic 调用 connect() 时,变量 connectable 是一个 engine 实例。

因此你可以做这样的事情(这没有经过测试,但我自己做了类似的事情):

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.

    """

    sshtunnel.SSH_TIMEOUT = 5.0
    sshtunnel.TUNNEL_TIMEOUT = 5.0

    server =  sshtunnel.SSHTunnelForwarder(
        ('ssh.pythonanywhere.com', 22),
        ssh_password="mypassword",
        ssh_username="myusername",
        remote_bind_address=\
            (myname.mysql.pythonanywhere-services.com', 3306))
    server.start()

    connectable = create_engine(
        'mysql+mysqldb://mynameb:dbpassword@127.0.0.1:%s/dbname' % 
        server.local_bind_port
    )

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

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

理想情况下,您可以将所有连接逻辑放在可以从 alembic/env.py 和项目中访问的地方,这样您只需定义一次,然后就可以导入engine 直接进入 env.py,但你明白了。

关于python - SQLAlchemy DB 升级和 MySQL SSH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50620531/

相关文章:

python - pandas 0.22,仅重新采样完整的箱子,丢弃部分

python - 有什么方法可以用 Pandas 进行二维插值吗?

mysql - SQL 查询不返回预期值

mysql - MySQL Like搜索字符串中的任何日语字符

python - 如何使用MySQL和Flask创建表和插入数据

python - 在 Python 中使用堆栈求解迷宫 - 我的算法是否正确?

python 工具 Visual Studio - 步入不工作

MySQL Case 什么时候不起作用

javascript - 在 Flask Web 应用程序中使用 JS 地理定位 (Python 3.6.6)

python - 如何在 Flask 中存储 Session 的用户数据?