python flask-SQLAlchemy通过数据库表反向生成model模型

1.安装 pip install flask-sqlacodegen 模块
2.创建create_db.py文件
# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
pip install flask-sqlacodegen
"""

import os


def create_models():
    db_url = "mysql+pymysql://root:123456@localhost:3306/data_name?charset=utf8"
    plants_path = os.getcwd()
    print(plants_path)
    model_path = os.path.join(plants_path, 'model.py')
    cmd = 'flask-sqlacodegen --flask {}'.format(db_url)
    try:
        output = os.popen(cmd)
        content = str(output.read())
        with open(model_path, 'w+') as f:
            f.write(content)
        print('create  models successfully!')
    except Exception as e:
        print(e)


if __name__ == '__main__':
    create_models()
方式二(通过 sqlacodegen方式):
1.pip install sqlacodegen
2.cd前往要生成models.py的项目目录下
3.sqlacodegen --outfile models.py "mysql+pymysql://用户:密码@localhost:3306/数据库名字?charset=utf8mb4"
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐