Skip to content

Instantly share code, notes, and snippets.

@tashrifbillah
Created June 17, 2020 15:08
Show Gist options
  • Save tashrifbillah/e6d7a3626e51cb1d77f70764633ffa4b to your computer and use it in GitHub Desktop.
Save tashrifbillah/e6d7a3626e51cb1d77f70764633ffa4b to your computer and use it in GitHub Desktop.
Sharing data between callbacks in Dash
# See my issue at https://community.plotly.com/t/using-dcc-interval-for-continuous-update/41071/12
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import logging
# from time import sleep
from tempfile import gettempdir
from os import getpid, remove
from os.path import join as pjoin, isfile
from dash.exceptions import PreventUpdate
tmpfile= pjoin(gettempdir(), f'time-{getpid()}')
if isfile(tmpfile):
remove(tmpfile)
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
log= logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
app.layout = html.Div([
dcc.Input(id='total', value=0, type='number'),
html.Div(id='page-content'),
# the layout should update every 500 mili seconds
dcc.Interval(id= 'interval', n_intervals=0, interval=1000)
])
@app.callback(Output('page-content', 'children'),
[Input('total', 'value'), Input('interval', 'n_intervals')])
def display_page(value, n_intervals):
if isfile(tmpfile):
# read value from file
with open(tmpfile) as f:
value = f.read()
else:
# value is obtained from Input
pass
if not value or int(value)<1:
if isfile(tmpfile):
remove(tmpfile)
raise PreventUpdate
value= int(value)
value-= 1
# write value back
with open(tmpfile, 'w') as f:
f.write(str(value))
# return value
return html.Div([
html.Plaintext(f'Value: {value}')
])
if __name__ == '__main__':
app.run_server(debug=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment