Flask-sqlalchemy使用alembic迁移模型_示例2

Flask-sqlalchemy使用alembic迁移模型示例2

与示例1略有区别

区别在两个文件models.py和env.py

示例1里的models.py里的内容:

from sqlalchemy import Column,Integer,String,create_engine,Text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
class User(Base):
    __tablename__ = 'tbUser'

    id = Column(Integer,primary_key=True)
    username = Column(String(20),nullable=False)
    password = Column(String(100),nullable=False)
    sex = Column(String(2),nullable=False)

class Article(Base):
    __tablename__ = 'tbArticle'

    id = Column(Integer,primary_key=True)
    title = Column(String(100),nullable=False)
    content = Column(Text, nullable=False)

示例2models.py里的内容:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer
from apps import config
from apps.exts import db

class User(db.Model):
    __tablename__ = "tbuser"
    uid = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(50), nullable=False)
    _password = db.Column(db.String(100),nullable=False)
    addr = db.Column(db.String(30),nullable=False)

区别在于类名后括号里一个是Base,一个是db.Model

初始项目文件结构

 

 

1.从命令行进入项目文件夹,进入虚拟环境,输入指令:alembic init alembic

2.编辑alembic.ini

找到sqlalchemy.url = driver://user:pass@localhost/dbname

修改为:sqlalchemy.url = mysql+pymysql://root:123456@localhost/db_mytest

3.编辑alembic\env.py

增加下面语句

import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")

...

在下面找到target_metadata = None,在这句话前增加import apps.models,把target_metadata=None改为target_metadata=apps.models.db.Model.metadata

如下:

import apps.models
target_metadata = apps.models.db.Model.metadata

4.执行指令:alembic revision --autogenerate -m "first commit"

 正常情况下会在alembic\version文件夹下生成迁移文件

5.执行指令:alembic upgrade head

则把models.py里定义的表生成到数据库db_mytest里

 

6.注意事项,如果反复生成进行测试,请先把db_mytest里的表给清理掉

7.项目文件参考,如下:

链接:https://pan.baidu.com/s/12sk5jDo7R7uVnfLYSnE3qQ
提取码:2srb

 

 

 

 

posted on 2020-06-05 22:41  天道酬勤2016  阅读(221)  评论(0编辑  收藏  举报