Alembic使用
Posted zzy0306
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Alembic使用相关的知识,希望对你有一定的参考价值。
生成目录
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:[email protected]/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使用的主要内容,如果未能解决你的问题,请参考以下文章