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
相关推荐
毕设源码-钟学长8 分钟前
【开题答辩全过程】以 基于Python的健康食谱规划系统的设计与实现为例,包含答辩的问题和答案
开发语言·python
百***787540 分钟前
Grok-4.1技术深度解析:双版本架构突破与Python API快速集成指南
大数据·python·架构
2501_942191772 小时前
基于YOLO11-HSFPN的数字检测与识别模型实现详解
python
没有bug.的程序员2 小时前
Java 序列化:Serializable vs. Protobuf 的性能与兼容性深度对比
java·开发语言·后端·反射·序列化·serializable·protobuf
忧郁的橙子.2 小时前
26期_01_Pyhton基本语法
python
sunfove3 小时前
实战篇:用 Python 徒手实现模拟退火算法解决 TSP 问题
开发语言·python·模拟退火算法
我爱娃哈哈3 小时前
SpringBoot + Spring Security + RBAC:企业级权限模型设计与动态菜单渲染实战
spring boot·后端·spring
我是菜鸟0713号3 小时前
Qt + Python 算法集成的一种低耦合实践:FastAPI 服务化方案
python·qt·fastapi
我是一只小青蛙8883 小时前
TraeCNIDE Python开发全流程指南
python
欣然~4 小时前
法律案例 PDF 批量转 TXT 工具代码
linux·前端·python