从现有 MySQL 数据库逆向工程 SQLAlchemy 声明类定义? [英] Reverse engineer SQLAlchemy declarative class definition from existing MySQL database?

查看:39
本文介绍了从现有 MySQL 数据库逆向工程 SQLAlchemy 声明类定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大约 50 个表的预先存在的 mysql 数据库.

I have a pre-existing mysql database containing around 50 tables.

而不是手动编写声明式风格的 SqlAlchemy 类 (如此处所示)对于每个表,是否有一个工具/脚本/命令我可以针对将生成一个 python 类的 mysql 数据库运行在数据库中每个表的声明样式中?

Rather than hand code a declarative style SqlAlchemy class (as shown here) for each table, is there a tool/script/command I can run against the mysql database that will generate a python class in the declarative style for each table in the database?

仅以一张表为例(理想情况下为所有 50 个生成)如下:

To take just one table as an example (would generate for all 50 ideally) as follows:

+---------+--------------------+
| dept_no | dept_name          |
+---------+--------------------+
| d009    | Customer Service   |
| d005    | Development        |
| d002    | Finance            |
| d003    | Human Resources    |
| d001    | Marketing          |
| d004    | Production         |
| d006    | Quality Management |
| d008    | Research           |
| d007    | Sales              |
+---------+--------------------+

是否有工具/脚本/命令可以生成包含以下内容的文本文件:

Is there a tool/script/command that can generate a text file containing something like:

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Department(Base):
   __tablename__ = 'departments'

   dept_no = Column(String(5), primary_key=True)
   dept_name = Column(String(50))

   def __init__(self, dept_no, dept_name):
       self.dept_no = dept_no
       self.dept_name = dept_name

   def __repr__(self):
      return "<Department('%s','%s')>" % (self.dept_no, self.dept_name)

推荐答案

使用 sqlautocode:

它是一种从现有数据库自动生成模型的灵活工具.

It is a flexible tool to autogenerate a model from an existing database.

这是一种与 SqlSoup 略有不同的方法,它允许您使用表而无需明确定义它们.另一方面,sqlalutocode 会生成实际的python 代码.

This is a slightly different approach to SqlSoup, which lets you use tables without explicitly defining them. On the other hand, sqlalutocode will generate actual python code.

这篇关于从现有 MySQL 数据库逆向工程 SQLAlchemy 声明类定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆