I thought this would update on page refresh

I’ve made a fairly simple app and would like the graph and data to update on each page load or page refresh. It seems that the tables and graph are only computed once and never change. Any help would be greatly appreciated.

import golf
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

def generate_table(dataframe, max_rows=10):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

        # Body
        [html.Tr([
            html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )

app = dash.Dash()

def serve_layout():
    dfAlecPlayers = golf.getPlayers('alecPlayers.csv')
    dfBillyPlayers = golf.getPlayers('billyPlayers.csv')
    dfBrandonPlayers = golf.getPlayers('brandonPlayers.csv')
    dfDustinPlayers = golf.getPlayers('dustinPlayers.csv')
    dfJeffPlayers = golf.getPlayers('jeffPlayers.csv')
    dfPatPlayers = golf.getPlayers('patPlayers.csv')
    dfSmittyPlayers = golf.getPlayers('smittyPlayers.csv')

    alecScore = golf.getScore(dfAlecPlayers)
    billyScore = golf.getScore(dfBillyPlayers)
    brandonScore = golf.getScore(dfBrandonPlayers)
    dustinScore = golf.getScore(dfDustinPlayers)
    jeffScore = golf.getScore(dfJeffPlayers)
    patScore = golf.getScore(dfPatPlayers)
    smittyScore = golf.getScore(dfSmittyPlayers)

    dScores = {'Name': ['Alec', 'Billy', 'Brandon', 'Dustin', 'Jeff', 'Pat', 'Smitty'],
               'Score': [alecScore, billyScore, brandonScore, dustinScore, jeffScore, patScore, smittyScore]}
    dfScores = pd.DataFrame(data=dScores)

    dfScores.sort_values('Score', inplace=True)

    tournamentName = golf.getTournamentName()

    app.layout =html.Div([
    
    dcc.Graph(id='scores',
                figure={
                    'data': [
                        {'x': dfScores.Name, 'y': dfScores.Score, 'type': 'bar', 'name': 'SCORE'}],
                    'layout': {'title': tournamentName}
                    }),
    
    html.Div([
        html.Table(
            html.Tr([
                html.Td(
                    html.Div([
                        html.H6('ALEC PLAYERS'),
                        html.B('SCORE: '),
                        html.B(alecScore),
                        generate_table(dfAlecPlayers)])),
                html.Td(
                    html.Div([        
                        html.H6('BILLY PLAYERS'),
                        html.B('SCORE: '),
                        html.B(billyScore),
                        generate_table(dfBillyPlayers)])),
                html.Td(
                    html.Div([
                        html.H6('BRANDON PLAYERS'),
                        html.B('SCORE: '),
                        html.B(brandonScore),
                        generate_table(dfBrandonPlayers)])),
                html.Td(
                    html.Div([
                        html.H6('DUSTIN PLAYERS'),
                        html.B('SCORE: '),
                        html.B(dustinScore),
                        generate_table(dfDustinPlayers)])),
                    ]),
            style={'white-space':'nowrap'})
        ]),

        html.Div([
            html.Table(
                html.Tr([
                    html.Td(
                        html.Div([
                            html.H6('JEFF PLAYERS'),
                            html.B('SCORE: '),
                            html.B(jeffScore),
                            generate_table(dfJeffPlayers)])),
                    html.Td(
                        html.Div([
                            html.H6('PAT PLAYERS'),
                            html.B('SCORE: '),
                            html.B(patScore),
                            generate_table(dfPatPlayers)])),
                    html.Td(
                        html.Div([
                            html.H6('SMITTY PLAYERS'),
                            html.B('SCORE: '),
                            html.B(smittyScore),
                            generate_table(dfSmittyPlayers)])),
        
                    ]),      
                style={'white-space':'nowrap'})
        ])
    ])
    return app.layout

app.title='HIGH ROLLERS GOLF'

app.layout = serve_layout()

app.css.append_css({'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'})

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

If you change this:

app.layout = serve_layout()

to this:

app.layout = serve_layout

That should do what you want. When Dash sees a function for the layout property, it will evaluate the function on each page load (as opposed to only evaluating it only once on the initial app load)

1 Like

Thanks for the response @nedned

I made your recommended change after some research last night but it seems that none of the score variables are updating on page load/refresh and remain the values at initial app start. Any other ideas?

Edit for clarity: if I stop and restart the app, the values update on restart, but will not update on page refresh.

Ah, I see. You’re setting app.layout inside of serve_layout, which overrides the value of the function, setting it to a static layout. Just assign to a variable ‘layout’ (instead of ‘app.layout’) and return that.

1 Like

Thanks for your help. Also turned out to be an error in my “golf” module. Appreciate your time and effort @nedned

1 Like

Hi,

I am also looking for the same solution. So I followed the above solutions but did not worked out.
Could anyone please help.

Below is my piece of code:

    def dynamic_layout():

    return html.Div(
        [
            header,
            html.Div([
                html.Div(
                    html.Div(id='page-content', className='content'),
                    className='content-container',
                ),
            ], className='container-width-body', style={'height': '100%', 'width': '97%', 'margin-left':'auto', 'margin-right':'auto'},), 
            dcc.Location(id='url', refresh=False)
        ]
    )

app.layout = dynamic_layout
app.config.supress_callback_exceptions = True

I have the same problem, if I enter the page the first time live read from SQLite displays the sensor readings, if I refresh the page no update starts and the graphs remains empty.