码迷,mamicode.com
首页 > 其他好文 > 详细

Alembic使用

时间:2019-04-09 00:38:06      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:data   ase   file   upgrade   ISE   pre   bic   sys.path   class   

生成目录

alembic init [project_name]


# 目录如下
_sqlalchemy
    -alembic
        -versions
            1241241fheuwyb_initial.py
        env.py
        README
        script.py.mako
    alembic.ini
    models.py

修改alembic.ini

# 使用的是mysql
sqlalchemy.url = mysql+pymysql://root:@localhost/demo
# sqlalchemy.url = driver://user:pass@localhost/dbname

修改env.py

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata

project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

from models import Base

target_metadata = Base.metadata

自动生成基本表

alembic revision --autogenerate -m "intial"
"""initial table Person

Revision ID: 0249ed6eaeb3
Revises: 
Create Date: 2019-04-08 23:14:06.113172

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '0249ed6eaeb3'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('person',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('nickname', sa.String(length=32), nullable=True),
    sa.Column('first_name', sa.String(length=32), nullable=True),
    sa.Column('last_name', sa.String(length=32), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('person')
    # ### end Alembic commands ###

更新数据库到最新版本

alembic upgrade head

数据库回滚一个版本

alembic downgrade -1

models.py

# -*- coding: utf-8 -*-

from sqlalchemy import Column, Integer, String, Date
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()


class Person(Base):

    __tablename__ = 'person'

    id = Column(Integer, primary_key=True)

    nickname = Column(String(32), nullable=True)
    first_name = Column(String(32), nullable=True)
    last_name = Column(String(32), nullable=True)

Alembic使用

标签:data   ase   file   upgrade   ISE   pre   bic   sys.path   class   

原文地址:https://www.cnblogs.com/zzy0306/p/10674307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!