How to access Flask app's context from within embedded Dash app when using app factory pattern? How to access Flask app's context from within embedded Dash app when using app factory pattern? flask flask

How to access Flask app's context from within embedded Dash app when using app factory pattern?


I managed to solve my issue. I was struggling to understand where in the Dash side of the app it was possible to access the main Flask app's context, so that I could provide Dash with access to the database. It turns out that this can be done within the register_callbacks() function and the actual callback functions defined within there like so:

def register_callbacks(app):    from app import db    from app.models import Transaction    ...    @app.callback(        Output("main", "children"),        [Input("transaction_table", "data_previous")],        [            State("transaction_table", "data"),            State("transaction_table", "page_current"),        ],    )    def update_database_and_generate_table(old_table_data, table_data, page_current):        with app.server.app_context():            if old_table_data is not None:                update_changed_data(old_table_data, table_data)            transactions = db.session.query(Transaction)            df = pd.read_sql(transactions.statement, transactions.session.bind)

For this to work, another change has to be made to the code of my original question. In the create_app() function, you need to register the Dash app after the database has been initialised:

def create_app(config_class=Config):    app = Flask(__name__)    app.config.from_object(config_class)    db.init_app(app)    migrate.init_app(app, db)    login.init_app(app)    mail.init_app(app)    bootstrap.init_app(app)    app = dashapp.add_dash(app)    ...

The full working example is located here: https://github.com/danielcopelin/dacy-budget


Your answer is here Project Layout.I had similar problem and couldn't do 'normal' python imports within the flask app.

Name your app flaskr as suggested, and move app.py and templates there ... just like in the tutorial. It worked for me.