sqlalchemy-db升级和mysql-ssh

cvxl0en2  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(280)

我有一个flask应用程序,我需要使用sshtunnel连接到一个遥远的mysqldb,就像我的config.py文件i init in my init.py文件中的sshtunnel:

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 db upgrade),因为我没有使用sqlalchemy\u database\u uri连接到我的数据库。是否还有一种方法可以使数据库升级与数据库的ssh连接一起工作?

rm5edbpk

rm5edbpk1#

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()

重要的是变量 connectable 是一个 engine alembic调用时的示例 connect() 在上面。
因此,您可以这样做(这不是测试,但我自己也做类似的事情):

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 ,但你明白了。

相关问题