Black Lives Matter. Please consider donating to Black Girls Code today.
Dash HoloViews is now available! Check out the docs.

How to simulate data and change the dcc.Interval component without using global variables?

I’m building a dash app that displays real time data in a table. Since the real time data is not yet available I want to simulate the data myself, using the dcc.Interval component. Please consider the following code:

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dte
import pandas as pd
from random import randint, uniform

app = dash.Dash()
interval_state = 1000

live_data = pd.DataFrame({
    'Column 1': ['start'],
    'Column 2': ['start']

app.layout = html.Div(
            id = 'pause-button',
            id = 'data-table',
            rows = [{}],
            sortable = True,
            filterable = True,
            editable = True,
            id = 'interval-component',
            interval = 3*interval_state

    events = [dash.dependencies.Event('interval-component', 'interval')]
def update_table():
    global live_data
    new_data = pd.DataFrame({
        'Column 1': [randint(0,10)],
        'Column 2': [uniform(0,1)]
    live_data = pd.concat([new_data, live_data])
    return live_data.to_dict('Records')

def update_interval_length(n_clicks):
    global interval_state
    if interval_state == 1000:
        interval_state = 1000*60
        return interval_state
        interval_state = 1000
        return interval_state

if __name__ == '__main__':

I think this script works fine. I’ve written the update_interval_length function so that I can pause the input to filter the data. The dash guide warns that global variables will break you app though and I would like to know if there’s a way to simulate data and pause the Interval component without using global variables. Is there for instance a way to run another python script that can be used as an external source for the app?

Thanks for writing in. You’re right to be leery of global variables, but since this is meant to be a POC for your actual live app, you should be ok.

To really avoid using global variables I would create a toy front end that mimics what your live data will ultimately look like. A few examples could include a lightweight flask server that calculates time-based data, or a python script tied to a cron job that updates a lightweight database. If you know what your live data backend is going to look like, you could design a toy version that mimics its architecture.

I used a flask app, thanks for the tip!