Reverse engineer SQLAlchemy declarative class definition from existing MySQL database?

Viewed 9538

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)
4 Answers
Related