Python SQLAlchemy数据库升级和MySQL SSH
我有一个Flask应用程序,我需要使用我的config.py文件中的SSHTunnel连接到一个遥远的MysqlDB,我的init.py文件中的I init:Python SQLAlchemy数据库升级和MySQL SSH,python,mysql,flask,sqlalchemy,flask-sqlalchemy,Python,Mysql,Flask,Sqlalchemy,Flask Sqlalchemy,我有一个Flask应用程序,我需要使用我的config.py文件中的SSHTunnel连接到一个遥远的MysqlDB,我的init.py文件中的I init: sshtunnel.SSH_TIMEOUT = 5.0 sshtunnel.TUNNEL_TIMEOUT = 5.0 server = sshtunnel.SSHTunnelForwarder( ('ssh.pythonanywhere.com', 22), ssh_password="mypassword",
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_DATABASE_URI连接到我的数据库。是否仍有办法使db升级通过ssh连接到db?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
是一个引擎
实例
因此,您可以这样做(这没有经过测试,但我自己也做了类似的事情):
理想情况下,您应该将所有连接逻辑放在一个可以从alembic/env.py
和项目中访问的地方,这样您只需定义一次,然后您就可以直接将引擎导入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.
"""
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()