Flask Blueprints: RuntimeError Application not registered on db -
ive been going @ several hours im afraid still don't gronk flask app context , how app should implemented blueprints.
ive taken @ this , this , have tried few different recommendations there must wrong basic approach.
i have 1 'main' design setup under next pj structure:
project/ app/ main/ __init__.py routes.py forms.py helper.py admin/ static/ templates/ __init__.py models.py
app/init.py:
from flask import flask config import config flask.ext.sqlalchemy import sqlalchemy flask.ext.bootstrap import bootstrap db = sqlalchemy() bootstrap = bootstrap() def create_app(config_version='default'): app = flask(__name__) app.config.from_object(config[config_version]) bootstrap.init_app(app) .main import main main_blueprint app.register_blueprint(main_blueprint) db.init_app(app) homecoming app
app/main/init.py
from flask import design main = blueprint('main',__name__) . import routes, helper
app/main/helper.py
#!/usr/bin/env python . import main ..models import sku, category, db flask import current_app def get_categories(): cat_list = [] cat in db.session.query(category).all(): cat_list.append((cat.id,cat.category)) homecoming cat_list
everything worked fine until created get_categories
function in helpers.py
pull dynamic list select form in app/main/forms.py. when fireup wsgi, however, error:
runtimeerror: application not registered on db instance , no application bound current context
it appear db
referenced in helper not associated app context when seek create 1 within function, has not worked.
what doing wrong , there improve way organize helper functions when using blueprints?
documentation on database contexts here here.
my first thought weren't calling db.init_app(app)
, corrected in comments.
in app/main/helper.py
, you're importing database via from ..models import sku, category, db
. database object not have been initialized app you've created.
the way i've gotten around having file, shared.py
in root directory. in file, create database object,
from flask.ext.sqlalchemy import sqlalchemy db = sqlalchemy()
in app/init.py
, don't create new db
object. instead, do
from shared import db db.init_app(app)
in place want utilize db
object, import shared.py
. way, object in shared file have been initialized app context, , there's no chance of circular imports (which 1 of problems can run having db
object outside of app-creating file).
flask-sqlalchemy flask
No comments:
Post a Comment