SQLAlchemy Alembic

  1. 安装:pip install alembic
  2. 初始化alembic:
    (venv) F:\Code\AllProject\devInfo\models>alembic init alembic
    Creating directory F:\Code\AllProject\devInfo\models\alembic ... done
     Creating directory F:\Code\AllProject\devInfo\models\alembic\versions ... done
     Generating F:\Code\AllProject\devInfo\models\alembic.ini ... done
     Generating F:\Code\AllProject\devInfo\models\alembic\env.py ... done
     Generating F:\Code\AllProject\devInfo\models\alembic\README ... done
     Generating F:\Code\AllProject\devInfo\models\alembic\script.py.mako ... done
     Please edit configuration/connection/logging settings in 'F:\\Code\\AllProject\\devInfo\\models\\alembic.ini' before proceeding.
  3. 修改配置
  • 修改文件(alembic.ini):
定义sqlalchemy.url,写法和sqlalchemy中定义engine一样
sqlalchemy.url = mysql://root:123.com@127.0.0.1/allproject
  • 修改alembic/env.py文件,修改metadata定义
# target_metadata = None
import os,sys
sys.path.append(os.path.realpath('.'))
from baseobj import Base
target_metadata=Base.metadata
数据库结构修改生成版本文件,在alembic下的version下面生成一个文件,版本号_描述
(venv) F:\models>alembic revision --autogenerate -m "test update db"
INFO  [alembic.runtime.migration] Context impl MySQLImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.autogenerate.compare] Detected removed table 'mib'
INFO  [alembic.autogenerate.compare] Detected removed table 'device'
INFO  [alembic.autogenerate.compare] Detected removed table 'board'
INFO  [alembic.autogenerate.compare] Detected removed table 'ips'
Generating F:\models\alembic\versions\45c578f737cc_test_update_db.py ... done
升级数据库:head表示最新版本文件,也可以直接指定版本号
(venv) F:\models>alembic upgrade head
INFO  [alembic.runtime.migration] Context impl MySQLImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> 45c578f737cc, test update db
降级数据库,alembic downgrade xxxx-1,-1表示上一个版本
(venv) F:\models>alembic downgrade 45c578f737cc
INFO  [alembic.runtime.migration] Context impl MySQLImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running downgrade 45c578f737cc -> , test update db
手动编辑版本文件
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    #添加行,board为表名,test_column为新加字段
    op.add_column('board',sa.Column('test_column',sa.Integer))
    
def downgrade():
    #降级删除指定表指定列
    op.drop_column('board','test_column')



转载于:https://www.cnblogs.com/yaya625202/p/8426997.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值