Question

I'm creating a Web Application with Flask and SQL Alchemy. The package structure looks something like this:

runserver.py

runserver.py
--- skeleton
    --- filters
    --- helpers
    --- models
    --- modules
        --- admin
        --- api
        --- debug
        --- frontend
    --- static
    --- templates
--- tests

I know how to lazy load a scoped session. But how do I do this with a normal session?

I have a create_app function in my __init__ file in the base package of my application.

My __init__ file looks like this:

from sqlalchemy.engine import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import create_session, scoped_session

#some stuff
def create_app(name=__name__, configuration=None):
    from .modules import admin
    from .modules.admin.models import User

    app = Flask(name, static_path='/static', template_folder=template_dir)
    load_config(app, configuration)

    init_engine(app.config['SQLALCHEMY_DATABASE_URI'])

    return app

def init_engine(uri, **kwargs):
    global engine
    engine = create_engine(uri, **kwargs)
    Base.metadata.create_all(engine)
    db.begin()
    return engine

def load_config(app, config=None):
    app.config.from_object(__name__)
    app.config.from_object('default_settings')
    app.config.from_envvar('SKELETON_SETTINGS', silent=True)
    if config:
        app.config.from_object(config)


#some other stuff

engine = None

db = scoped_session(lambda: create_session(bind=engine))

I cannot use FlaskAlchemy because other modules not supporting it and the models would get messsed up a lot.

What is the best practice to init the database and do an import like this when its needed: from skeleton import db

Thanks for sharing your thoughts

Was it helpful?

Solution

Ok. I think I figured this one out by myself too. I am using this snippet now. If you have any better ideas, please let me know

Base = declarative_base()
engine = None
sessionmaker = sessionmaker()
db = scoped_session(sessionmaker)

def configure_engine(url):
    global sessionmaker, engine, db

    engine = create_engine(url)
    db.remove()
    sessionmaker.configure(bind=engine)

def create_app(name=__name__, configuration=None):
    from .modules import admin
    from .modules.admin.models import User

    app = Flask(name, static_path='/static', template_folder=template_dir)
    load_config(app, configuration)
    celery.config_from_object(app.config)
    configure_engine(app.config['SQLALCHEMY_DATABASE_URI'])
    filters.init_app(app)
    register_local_modules(app)
    admin.init_app(app)
    login_manager.init_app(app)
    @login_manager.user_loader
    def load_user(id):
        return db.query(User).get(id)

    # Enable the DebugToolbar
    if app.config['DEBUG_TOOLBAR']:
        toolbar = DebugToolbarExtension(app)

    return app
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top