Thanks for you suggestion. I tried your suggestion, but it seems like cached callback does not work properly the second time. It gives TypeError: Object of type DataFrame is not JSON serializable
error, which is an error when using normal callbacks. I modified your example to simulate this.
import dash
import dash_core_components as dcc
import dash_html_components as html
import time
import plotly
import pandas as pd
from dash.dependencies import Output, Input
from dash_extensions.callback import CallbackCache, DiskCache
data_sets = ["gapminder", "tips", "iris", "wind", "election"]
# Create app.
app = dash.Dash(prevent_initial_callbacks=True)
app.layout = html.Div([
dcc.Dropdown(options=[{"label": ds, "value": ds} for ds in data_sets], id="data_set"),
html.Div(id="output"),
html.Div(id="output2"),
dcc.Loading(dcc.Store(id="store"), fullscreen=True),
dcc.Store(id="filtered_store"),
html.Div([
dcc.Slider(
id='filter-slider',
min=0,
max=100,
value=100,
marks={str(num): str(num) + '%' for num in range(10, 100, 10)},
step=1,
updatemode='drag'
),
]
)
])
# Create (server side) disk cache.
cc = CallbackCache(cache=DiskCache(cache_dir="cache_dir"))
@cc.cached_callback(Output("store", "data"), [Input("data_set", "value")])
def fetch_data(key):
df = plotly.data._get_dataset(key) if key is not None else None
time.sleep(1) # sleep to emulate a database call / a long calculation
return df
@cc.callback(Output("output", "children"), [Input("store", "data")])
def print_head(df):
return df.iloc[:5].to_json()
@cc.cached_callback(Output("filtered_store", "data"), [Input("store", "data"), Input("filter-slider", 'value')])
def filter_data(store, filter):
# simulating updating data, my original code uses raw data and filter, here just use new data for simplicity
data = {'Name': ['Tom', 'nick', 'krish', 'jack'], 'Age': [20, 21, 19, 18]}
df = pd.DataFrame(data)
time.sleep(1) # sleep to emulate a database call / a long calculation
return df
@cc.callback(Output("output2", "children"), [Input("filtered_store", "data")])
def print_head2(df):
return df.to_json()
cc.register(app)
if __name__ == '__main__':
app.run_server(debug=True)