0

I'm trying to initialize a Dash app inside a Flask built website only whe the user presses a button in one of my html templates. All the solutions and workaround, sticking it inside a function or not, etc, I've seen so far starts the Dash app in the general Falsk app init.py file. But I want the Dash app to take resources and run only when the user presses a button in my site, and not just be hangin' there the whole time since when the user enters the site.

I've tried many aproaches, like:

Run a dash app inside a flask

Running a Dash app within a Flask app

https://github.com/toddbirchard/plotlydash-flask-tutorial/blob/master/plotly_flask_tutorial

https://hackersandslackers.com/plotly-dash-with-flask/

But none of those gets me where I want to go. Trying some original thinking, I've tried to create a route for my button that would start the Dash app and then redirect to de url_base_pathname. So far, failed. My files structure:

files structure

main.py:

from portfolio_felipe import app

if __name__ == '__main__':
    app.run(debug= True)

portfolio_felipe.init.py (that's where all the solutions I've came across would start the Dash app, and that's what I'm trying to avoid as it takes unecessary resources for a lot of other parts of my site):

from flask import Flask

app = Flask(__name__)
from portfolio_felipe import routes

dash_nba.init.py:

from dash import Dash, dcc, html, callback, Output, Input
import pandas as pd
import plotly.express as px

def create_dash_nba(flask_app):
    dash_app= Dash(server= flask_app, name='dashnba', url_base_pathname='/dashnba/')
    
    df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
    
    dash_app.layout = html.Div([
    html.H1(children='Title of Dash App', style={'textAlign':'center'}),
    dcc.Dropdown(df.country.unique(), 'Canada', id='dropdown-selection'),
    dcc.Graph(id='graph-content')
    ])
    
    return dash_app.server

And on my portfolio_felipe.routes.py file I'm trying something like:

@app.route('/button_use')
def button_use():
    dash_app= create_dash_nba(app)
    return redirect('/dashnba/')

I would really apreciate an explanation on why my logic is flawed, as it seems I am really failing to understand the documentaed Flask and Dash objects and their methods. and if it's not exactly flawed, where am I loosing my step, and what should I do to make it work. But I would also welcom a complete workaround a full remake of my codes and files structure. Thank you in advance for helping!

felipedmc
  • 19
  • 5

0 Answers0