Skip to content

Instantly share code, notes, and snippets.

@levon003
Last active October 14, 2020 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save levon003/f7d3e43851601b478b469415898da5b6 to your computer and use it in GitHub Desktop.
Save levon003/f7d3e43851601b478b469415898da5b6 to your computer and use it in GitHub Desktop.
Attempting to use Dash to produce intermediate output. See associated thread: https://community.plotly.com/t/returning-partial-results/46047
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from datetime import datetime
import time
app = dash.Dash(__name__)
app.layout = html.Div([
html.H6("Partial results demo"),
html.Div(["Input: ", dcc.Input(
id='input',
value='',
placeholder='Enter a query',
type='text')]),
html.Br(),
html.Div(id='output'),
html.Div(id='intermediate', style={'display': 'none'})
])
@app.callback(
Output(component_id='output', component_property='children'),
[Input(component_id='input', component_property='value'), Input(component_id='intermediate', component_property='children')],
[State(component_id='output', component_property='children')]
)
def update_output_div(input_value, intermediate_value, existing_children):
print(dash.callback_context, datetime.now())
if not dash.callback_context.triggered:
raise PreventUpdate
trigger_ids = [triggered['prop_id'].split('.')[0] for triggered in dash.callback_context.triggered]
trigger_str = str(dash.callback_context.triggered)
if existing_children is None:
existing_children = ['Output:', html.Br()]
new_children = []
if 'input' in trigger_ids:
# fast computation, return immediately
new_children.extend([f"Fast result at {datetime.now()} (trigger: {trigger_str})", html.Br()])
if 'intermediate' in trigger_ids:
# the slow computation finished! add it to the output
new_children.extend([intermediate_value, f"(trigger: {trigger_str})", html.Br()])
return existing_children + new_children
@app.callback(
Output('intermediate', 'children'),
Input('input', 'value')
)
def update_intermediate_div(input_value):
if input_value.strip() == '':
raise PreventUpdate
s = datetime.now()
time.sleep(5)
long_running_result = f"Slow result at {datetime.now()} after {datetime.now() - s} "
return long_running_result
if __name__ == '__main__':
app.run_server(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment