Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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://root@127.0.0.1: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
You can’t perform that action at this time.