I am trying to share data between callbacks using JSON storage. I have a small test example here which isn’t working.
The first piece of code converts to / from JSON within one callback and does not share data. This one works.
The second piece of code uses multiple callbacks, exporting as JSON in the first callback as intermediate-value and then using that in the second callback to read in the JSON data. This one doesn’t output anything when I enter any value.
I’ve tried debugging for a couple hours and reading lots of threads but still can’t figure it out. Can someone help? Thanks!!
Test data:
data = [['Col1',-10],['Col2',-12],['Col3',-13],['Col4',-100]]
temp = pd.DataFrame(data,columns=['ColName','Score'])
data = [['Col101',10],['Col102',12],['Col103',13],['Col104',100]]
temp2 = pd.DataFrame(data,columns=['ColName','Score'])
First piece of code (works):
app = dash.Dash()
app.layout = html.Div([
html.H1('TiVo Acxiom AP Dashboard', style = {'textAlign': 'center', 'color': '#111111'}),
dcc.Input(id = 'title-picker', placeholder = 'Enter a title...', type = 'text', value=''),
html.Button(id = 'submit-button', n_clicks=0, children = 'Submit Title', style = {'fontSize':16}),
html.Div(id='output-table')
])
@app.callback(Output('output-table', 'children'),
[Input('submit-button', 'n_clicks')],
[State('title-picker', 'value')])
def update_table(n_clicks, selected_title):
if selected_title == 'right answer':
jsonified_data = temp.to_json()
else:
jsonified_data = temp2.to_json()
output = pd.read_json(jsonified_data)
return dash_table.DataTable(data = output.to_dict('rows'),
columns = [{"name": i, "id": i,} for i in output.columns])
if __name__ == '__main__':
app.run_server()
Second piece of code (doesn’t work):
app = dash.Dash()
app.layout = html.Div([
html.H1('TiVo Acxiom AP Dashboard', style = {'textAlign': 'center', 'color': '#111111'}),
dcc.Input(id = 'title-picker', placeholder = 'Enter a title...', type = 'text', value=''),
html.Button(id = 'submit-button', n_clicks=0, children = 'Submit Title', style = {'fontSize':16}),
html.Div(id='output-table'),
html.Div(id = 'intermediate-data', style = {'display': 'none'}) # hidden div that stores intermediate value
])
@app.callback(Output('intermediate-value', 'children'),
[Input('submit-button', 'n_clicks')],
[State('title-picker', 'value')])
def get_data_expensive(n_clicks, selected_title):
if selected_title == 'right answer':
jsonified_data = temp.to_json()
else:
jsonified_data = temp2.to_json()
return jsonified_data
@app.callback(Output('output-table', 'children'),
[Input('intermediate-value', 'children')])
def update_table(jsonified_data):
output = pd.read_json(jsonified_data)
return dash_table.DataTable(data = output.to_dict('rows'),
columns = [{"name": i, "id": i,} for i in output.columns])
if __name__ == '__main__':
app.run_server()