Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

python - Reverse engineer SQLAlchemy declarative class definition from existing MySQL database?

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

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?

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use sqlautocode:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...