Reputation: 19035
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)
Upvotes: 25
Views: 10072
Reputation: 222852
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.
Upvotes: 31
Reputation: 562270
SqlSoup can perform introspective mapping of an existing SQL schema.
Upvotes: 5
Reputation: 44730
Now (in 2015) you probably would want to use https://pypi.python.org/pypi/sqlacodegen instead!
Upvotes: 12
Reputation: 75127
Keep in mind declarative can be used with reflected tables. So if startup time weren't a huge issue you could do this:
engine = create_engine('mysql://...')
meta = MetaData()
meta.reflect(bind=engine)
for table in meta.tables.values():
print """
class %s(Base):
__table__ = Table(%r, Base.metadata, autoload=True)
""" % (table.name, table.name)
other than that autocode is probably the way to go.
Upvotes: 8