26 lines
1.1 KiB
Python
26 lines
1.1 KiB
Python
from flask_sqlalchemy import SQLAlchemy
|
|
|
|
db = SQLAlchemy()
|
|
|
|
def init_db(app):
|
|
db.init_app(app)
|
|
with app.app_context():
|
|
# check if database is empty and if so, populate it with fresh tables
|
|
#TODO: does it make sense to try and create all tables by default? Existing tables wouldn't be overwritten but what about DB constraints ?
|
|
if not len(db.metadata.tables):
|
|
# import table classes from code that was generated via `sqlacodegen --generator tables sqlite:///the_works.sqlite > ./the_works/tables.py` in project root
|
|
import the_works.tables
|
|
|
|
# filter the objects just imported for those of type sqlalchemy.Table
|
|
from sqlalchemy import Table
|
|
table_list = list(filter(lambda t: type(t) == Table, vars(the_works.tables).values()))
|
|
|
|
# Table objects imported from sqlacodegen code are associated with a random MetaData() object, so we have to re-associate them with the DB's metadata
|
|
table_list = list(map(lambda t: t.to_metadata(db.metadata), table_list))
|
|
|
|
# create tables in DB )
|
|
db.metadata.create_all(db.engine)
|
|
|
|
# generate declarative table objects by reflecting the DB
|
|
db.reflect()
|