sqlalchemy Alembic 学习笔记

前一段时间 一直用sqlalchemy-migrate 这个工具来做migrate,不过感觉不太好用。

今天开始学习Alembic 这个工具,由sqlalchemy 的作者一手开发的。

官方Tutorial:http://alembic.readthedocs.org/en/latest/tutorial.html

一: 安装 

ubuntu@yee:~$ sudo pip install alembic

二、初始化:

ubuntu@yee:~/project$ alembic init alembic
回到project 主目录 :
vim alembic.ini

# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

#sqlalchemy.url = driver://user:pass@localhost/dbname
sqlalchemy.url = mysql://root:*********@localhost:3306/dbname

三、使用

alembic revision -m "create friendship table"
vim alembic/versions/96274508199_create_friendship_table.py
import datetime
def
upgrade(): op.create_table( 'friendship',

          sa.Column('id',sa.Integer,primary_key=True),
          sa.Column('me',sa.Integer,sa.ForeignKey('users.id')),
          sa.Column('friend',sa.Integer,sa.ForeignKey('users.id')),
          sa.Column('created', sa.DateTime, nullable=False,default=datetime.datetime.now()),

          )

def downgrade():
    op.drop_table('friendship')

四、生成表:

alembic upgrade head

 

例二:添加字段:

def upgrade():
    op.add_column('users', sa.Column('created',sa.DateTime,default=datetime.datetime.now(),nullable=False))
    op.add_column( 'users', sa.Column('last_login' ,sa.String(250),nullable=False))
    op.add_column('users', sa.Column('registration_ip' ,sa.String(250),nullable=False))
    op.add_column( 'users', sa.Column('last_login_ip' ,sa.String(250),nullable=False))

def downgrade():
    op.drop_column('users', 'created' )
    op.drop_column('users', 'last_login')
    op.drop_column('users', 'registration_ip')
    op.drop_column('users', 'last_login_ip')
alembic upgrade +1

 

 

转载于:https://www.cnblogs.com/yeelone/archive/2012/12/05/2802708.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值