Flask snippets
db_session.py.
"""Shared database session instantiation.
SOURCE: http://flask.pocoo.org/snippets/22/
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker as SessionMaker
from sqlalchemy.orm import scoped_session
engine = None
sessionmaker = SessionMaker()
db_session = scoped_session(sessionmaker)
def init_engine(uri, **kwargs):
"""."""
global engine, sessionmaker
engine = create_engine(uri, **kwargs)
db_session.remove()
sessionmaker.configure(bind=engine)
return engine
server.py
from db_models import db # module where Tables are declared
from db_session import db_session, init_session
# ...
# Initialize app with database and other wiring
# ...
def register_database(app):
"""Register the app with the database."""
db.init_app(app)
with app.app_context():
# Extensions like Flask-SQLAlchemy now know what the "current" app
# is while within this block. Thereforse, you can now run........
db.create_all()
init_session(db)