0
votes

I’m somewhat new to dash and python so forgive me and let me know if there’s something that could be simplified or needs to be changed.

Problem

I want to display a number in text and update that number every 10 minutes. I have successfully done this, but the problem is that I want it to load immediately and then update every ten minutes... but then it takes 10 minutes to load this text when the application is first started.

I have a feeling that I need to add a while/if logic for the callback but I’m not sure. Here is a link to the result

See below for the code

If you want it to be reproducible, you can set any number to the data variable within get_data()

#Imports for dash
import dash
from dash.dependencies import Output, Event
import dash_core_components as dcc
import dash_html_components as html

#imports for database connection and data processing
from sshtunnel import SSHTunnelForwarder
import pymysql as db
import pandas as pd


# ssh variables go here
host = 
localhost = 
ssh_username = 
private_key = 
# database variables go here
user=
password=
database=

#This is the function for processing a query
def query(q):
    
    #function for getting data from database

def get_data():
    df_test = query('call example') #calls a procedure which returns a number
    data = df_test['test'].loc[0] # selects the result from the dataframe
    data_insert = 'This month we have {} new clients!!!'.format(data) #inserts the result into the string
    return data_insert

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        html.Div(id='my-div', children='''
        '''.format(get_data())),
        dcc.Interval(
            id='update',
            interval=10* 60000 # I would like for this to be 10 minutes
        )
    ]
)
@app.callback(Output('my-div', 'children'),
              events=[Event('update', 'interval')])
def update_data(): # function for returning the new data
    return get_data()

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

1 Answers

1
votes

The Dash community got back to me with a good solution. See below:

from datetime import datetime

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output


def serve_layout():
    return html.Div(
        [dcc.Interval(id="interval", interval=10000), html.P(id="output")]
    )


app = dash.Dash()

app.layout = serve_layout


@app.callback(Output("output", "children"), [Input("interval", "n_intervals")])
def display_time(n):
    return datetime.now().strftime("The time is: %H:%M:%S")


if __name__ == "__main__":
    app.run_server()