Flask 根据数据表生成模型类(逆向工程)

Flask-sqlacodegen

数据库脚本参考

MySQL版 emp 数据库

安装依赖

shell 复制代码
pip install flask-sqlacodegen

运行命令

shell 复制代码
flask-sqlacodegen "mysql+pymysql://用户名:密码@127.0.0.1/数据库名" --tables 表1,表2 --outfile "自定义文件名.py" --flask  

使用emp 作为案例
flask-sqlacodegen "mysql+pymysql://root:root@127.0.0.1/emp" --tables emp,dept,salgrade --outfile "models.py" --flask  

使用Python代码操作shell 命令

新建test.py

python 复制代码
import os
def create_models():
    db_url = "mysql+pymysql://root:root@localhost:3306/emp?charset=utf8mb4"
    project_path = os.getcwd()
    print(project_path)
    model_path = os.path.join(project_path, 'models.py')
    cmd = 'flask-sqlacodegen --flask {}'.format(db_url)
    try:
        output = os.popen(cmd)
        resp = output.buffer.read().decode(encoding='utf-8')
        content = str(resp)
        output.close()
        # w+ 读写权限
        with open(model_path, 'w+', encoding='utf-8') as f:
            f.write(content)
        print('create models successfully!')
    except Exception as e:
        print(e)


if __name__ == '__main__':
    create_models()

不使用 Flask

sqlacodegen

shell 复制代码
pip install sqlacodegen

运行shell 命令

shell 复制代码
# sqlacodegen --tables third_api "mysql+pymysql://username:password@host/db_name" >tmp.py
sqlacodegen --tables emp,dept "mysql+pymysql://root:root@localhost/emp" >test.py
相关推荐
BD_Marathon26 分钟前
【Python】初识迭代器
python
gz927cool1 小时前
Python 全栈应用最佳实践完整指南
开发语言·python·ai
智购科技智能售货柜1 小时前
顾客已经关门,视觉售货柜还在处理旧画面:延迟积压怎么查?~YH
python·单片机·嵌入式硬件·物联网·eclipse
梯度下降者1 小时前
Python从0到100(三):Python中的变量介绍
python·作用域·变量·数据类型·计算机常识
AIFQuant1 小时前
Python期货行情API接入:股指、黄金、原油多品种数据管道实战
开发语言·python·金融·区块链·量化开发
Thneonl1 小时前
Claude Code 频繁 Compacting?发布次日我根治了 2 个痛点
后端·rust
威哥爱编程2 小时前
Python 智能体开发实战 07:让它查课表它张口就编?给 Agent 接上真正能动手的工具
python·agent
Wang's Blog2 小时前
Java 项目实战:交友项目 - 即时通信总结:全链路复盘、可复用清单与自检
java·python·交友
2601_962885722 小时前
按主板/科创/创业/北交分板扫描选股
python
威哥爱编程2 小时前
Python 智能体开发实战 08:上线第一天就挂?给 Agent 装上重试、超时和降级三条保险丝
python·agent