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
相关推荐
chilavert3181 小时前
技术演进中的开发沉思-357:重排序(下)
java·后端
Boop_wu1 小时前
Spring生态
java·后端·spring
jzheng86101 小时前
Spring Boot(快速上手)
java·spring boot·后端
怒放吧德德2 小时前
Python3基础:基础实战巩固,从“会用”到“活用”
后端·python
aiguangyuan2 小时前
基于BERT的中文命名实体识别实战解析
人工智能·python·nlp
喵手2 小时前
Python爬虫实战:知识挖掘机 - 知乎问答与专栏文章的深度分页采集系统(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集知乎问答与专栏文章·采集知乎数据·采集知乎数据存储sqlite
铉铉这波能秀2 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple
kali-Myon2 小时前
2025春秋杯网络安全联赛冬季赛-day2
python·安全·web安全·ai·php·pwn·ctf
Olamyh2 小时前
【 超越 ReAct:手搓 Plan-and-Execute (Planner) Agent】
python·ai
deepxuan2 小时前
Day7--python
开发语言·python