Skip to content

Instantly share code, notes, and snippets.

@sp3c73r2038
Created March 26, 2015 06:36
Show Gist options
  • Save sp3c73r2038/e76bf8a78746c95009e4 to your computer and use it in GitHub Desktop.
Save sp3c73r2038/e76bf8a78746c95009e4 to your computer and use it in GitHub Desktop.
reflect and generate models code from database schema :)
# -*- coding: utf-8 -*-
class {{ table.name }}:
__tablename__ = '{{ table.name }}'
{% for col in table.columns %}
{{ col.name }} = Column({{col.type}}{% if col.primary_key %}, primary_key=True{% endif%}{% if not col.nullable %}, nullable=False{% endif %})
{% endfor -%}
# -*- coding: utf-8 -*-
#
# ```
# $ virtualenv .virtualenv
# $ ve pip install Jinja2 SQLAlchemy mysql-connector-python --allow-external mysql-connector-python
# $ mkdir src
# $ ve python reflect.py
# ```
#
from jinja2 import Environment, FileSystemLoader, Template
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.schema import MetaData, Table
engine = create_engine("mysql+mysqlconnector://[email protected]:3306/adv")
meta = MetaData()
Base = declarative_base()
meta.reflect(bind=engine)
loader = FileSystemLoader('templates')
env = Environment(loader=loader)
template = env.get_template('model.py.tpl')
print(template)
for table in reversed(meta.sorted_tables):
_ = template.render(table=table)
with open('src/%s.py' % table.name, 'w') as f:
f.write(_)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment