关键步骤:
# 创建对象基类
Base = declarative_base()
在创建的env.py里赋值给配置
target_metadata = Base.metadata
代码配置
import argparse
import os
import time
from alembic import command, migration
from alembic.config import Config
from config.config import db_config
from config.db_create import create_db
from config.logger import logger
create_db()
# Load the Alembic configuration
alembic_cfg = Config("migration/alembic.ini", attributes={})
alembic_cfg.set_main_option("sqlalchemy.url", db_config.db_url)
def init_migration():
if not os.path.exists(alembic_cfg.config_file_name):
command.init(alembic_cfg, "migration")
else:
logger.debug("the migration folder already exists!")
def migrate(msg):
command.revision(alembic_cfg, msg, True)
def upgrade():
command.upgrade(alembic_cfg, "head")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Database Migration Tool')
parser.add_argument('-i', '--init', dest="create", action="store_true", help='init migration folder if not exist')
parser.add_argument('-m', '--migrate', dest="message", type=str, help='add a new migration with message')
parser.add_argument('-u', '--upgrade', action="store_true",
help='upgrade db schema to latest version')
args = parser.parse_args()
if args.create:
init_migration()
elif args.message:
migrate(args.message)
elif args.upgrade:
upgrade()
else:
parser.print_help()
网友评论