Dash integrate Flask App

from flask import Flask, render_template, request, redirect, url_for
import fetchdata
from dash import Dash, html, dcc
from dash.dependencies import Input, Output
import plotly.graph_objects as go

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'adin' or request.form['password'] != 'adin':
            error = 'Geçersiz kullanıcı adı veya şifre. Lütfen tekrar deneyin.'
        else:
            return redirect(url_for('main_page'))
    return render_template('login.html', error=error)

@app.route('/main_page')
def main_page():
    return render_template('choose_fabric.html')

@app.route('/adin_analizi')
def adin_page():
    return render_template('adin_analizi.html')

dash_app = Dash(__name__, server=app, url_base_pathname='/dashboard/')
dash_app.layout = html.Div()

@app.route('/hata_bolgeleri_detayli_tablolar', methods=['GET', 'POST'])
def hata_bolgesi_page():
    if request.method == 'POST':
        baslangic_tarihi = request.form.get('baslangic_tarihi')
        bitis_tarihi = request.form.get('bitis_tarihi')
        tablo_turu = request.form.get('tablo_turu')

        if tablo_turu == 'tablo1':
            update_dash_content(baslangic_tarihi, bitis_tarihi)

        return redirect('/dashboard/')
    return render_template('hata_bolgeleri_detayli_tablolar.html')


def update_dash_content(baslangic_tarihi, bitis_tarihi):
    df = fetchdata.veri_cekme(baslangic_tarihi, bitis_tarihi)
    veri = df.copy()

    veri['Müşteri'] = veri['Müşteri'].replace('', 'AUDI')
    grup = veri.groupby(['Müşteri', 'Hata Bölgesi'])['Adet'].sum().reset_index()
    most_hata = grup.sort_values(by=['Müşteri', 'Adet'], ascending=[True, False])
    top10_adet_per_musteri = most_hata.groupby('Müşteri', group_keys=False).apply(lambda x: x.nlargest(10, 'Adet'))
    filtered_df = top10_adet_per_musteri[~top10_adet_per_musteri['Müşteri'].isin(['BJA\xa0\xa0\xa0', 'OPEL'])].copy()
    filtered_df.rename(columns={'Müşteri': 'Proje'}, inplace=True)

    dash_app.layout = html.Div([
        html.H1("Projelerin Hata Bölgelerinde Çıkan Hatalı Üretim Sayısı"),
        dcc.Dropdown(
            id='proje-dropdown',
            options=[{'label': proje, 'value': proje} for proje in filtered_df['Proje'].unique()],
            value=filtered_df['Proje'].unique()[0]
        ),
        dcc.Graph(id='table-graph')
    ])

    @dash_app.callback(
        Output('table-graph', 'figure'),
        [Input('proje-dropdown', 'value')]
    )
    def update_output(selected_proje):
        filtered_values = filtered_df[filtered_df['Proje'] == selected_proje]
        return go.Figure(data=[go.Table(
            header=dict(values=list(filtered_values.columns), fill_color='paleturquoise', align='left'),
            cells=dict(values=[filtered_values[col].tolist() for col in filtered_values.columns],
                       fill_color='lavender', align='left')
        )])

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

Hello everyone. I’m trying to create a multi-page website with Flask. Here I am trying to create dashboards with the Dash library on some pages, and the process is as follows: In my code, first of all, on the hata_regions_detailed_tables.html page, I receive the inputs named start, end date and table type from the user and when I click on the button, I run this function update_dash_content and show the dashboard at the url named /dashboard/. There is no problem so far, but the problem starts from here. error_regions_detailed_tables When I go back to this html page, get input data from the user for the second or more times and click on the button, the dashboard does not open at the relevant url. I don’t get any error messages either. The dashboard is half formed, only the X and Y axes are visible graphically. I want to click on the button after each data I receive from the user and it will create a new dashboard for me with new parameters and data pulled from the database. How can I do that ?

Hello @berkakyildiz,

Welcome to the community!

You should check out here:

I think you need to create your layout as a function, and not worry about trying to set up the data on the flask side.

I created the layout as a function, but this was not a useful solution for me. Can you give a more descriptive comment for a beginner like me?

Give this a shot, I’m not sure it will work, because I cant access any of your data or layouts:

from flask import Flask, render_template, request, redirect, url_for
import fetchdata
from dash import Dash, html, dcc, State, Input, Output
import plotly.graph_objects as go
import pandas as pd

app = Flask(__name__)

df = fetchdata.veri_cekme(baslangic_tarihi, bitis_tarihi) #setup your default here

@app.route('/', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'adin' or request.form['password'] != 'adin':
            error = 'Geçersiz kullanıcı adı veya şifre. Lütfen tekrar deneyin.'
        else:
            return redirect(url_for('main_page'))
    return render_template('login.html', error=error)

@app.route('/main_page')
def main_page():
    return render_template('choose_fabric.html')

@app.route('/adin_analizi')
def adin_page():
    return render_template('adin_analizi.html')

dash_app = Dash(__name__, server=app, url_base_pathname='/dashboard/')

@app.route('/hata_bolgeleri_detayli_tablolar', methods=['GET', 'POST'])
def hata_bolgesi_page():
    if request.method == 'POST':
        return redirect('/dashboard/')
    return render_template('hata_bolgeleri_detayli_tablolar.html')

def layout():
    baslangic_tarihi = request.form.get('baslangic_tarihi')
    bitis_tarihi = request.form.get('bitis_tarihi')
    tablo_turu = request.form.get('tablo_turu')

    if tablo_turu == 'tablo1':
        dff = fetchdata.veri_cekme(baslangic_tarihi, bitis_tarihi)
    else:
        dff = df
    veri = dff.copy()

    veri['Müşteri'] = veri['Müşteri'].replace('', 'AUDI')
    grup = veri.groupby(['Müşteri', 'Hata Bölgesi'])['Adet'].sum().reset_index()
    most_hata = grup.sort_values(by=['Müşteri', 'Adet'], ascending=[True, False])
    top10_adet_per_musteri = most_hata.groupby('Müşteri', group_keys=False).apply(lambda x: x.nlargest(10, 'Adet'))
    filtered_df = top10_adet_per_musteri[~top10_adet_per_musteri['Müşteri'].isin(['BJA\xa0\xa0\xa0', 'OPEL'])].copy()
    filtered_df.rename(columns={'Müşteri': 'Proje'}, inplace=True)
    
    return html.Div([
        html.H1("Projelerin Hata Bölgelerinde Çıkan Hatalı Üretim Sayısı"),
        dcc.Dropdown(
            id='proje-dropdown',
            options=[{'label': proje, 'value': proje} for proje in filtered_df['Proje'].unique()],
            value=filtered_df['Proje'].unique()[0]
        ),
        dcc.Graph(id='table-graph'),
        dcc.Store(id='filtered_df', data=filtered_df.to_dict('records'))
    ])

dash_app.layout = layout

@dash_app.callback(
    Output('table-graph', 'figure'),
    [Input('proje-dropdown', 'value'), State('filtered_df', 'data')]
)
def update_output(selected_proje, filtered_data):
    filtered_df = pd.DataFrame(filtered_data)
    filtered_values = filtered_df[filtered_df['Proje'] == selected_proje]
    return go.Figure(data=[go.Table(
        header=dict(values=list(filtered_values.columns), fill_color='paleturquoise', align='left'),
        cells=dict(values=[filtered_values[col].tolist() for col in filtered_values.columns],
                   fill_color='lavender', align='left')
    )])

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

Now… I will say that this has some issues, it manipulates a global variable which is not good, especially if you plan to have multiple people using the app.