# 1. Create app
import time
import dash
import os
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 flask_caching import Cache
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server
def get_ip():
return os.getenv('MYREDIS_HOST', 'localhost')
cache = Cache(app.server, config={
'CACHE_TYPE': 'RedisCache',
'CACHE_DEFAULT_TIMEOUT': 60, # The default timeout, unit of time is seconds
'CACHE_REDIS_HOST': get_ip(),
'CACHE_REDIS_PORT': 6379
})
cache.clear() # clean up cache files
app.layout = html.Div([
dcc.Input(id = 'input'),
html.Hr(),
dcc.Loading(html.H1(id = 'content')),
html.Button('Click', id = 'button'),
html.Hr(),
dcc.Loading(html.H1(id = 'content_2')),
html.Button('Click 2', id = 'button2')
], className='container')
# for the same parameter value, first call save results to cache
# second and later calls will reuse the results
# chaning the same parameter value, a new cache will be created
@cache.memoize()
def compute_expensive_data(value):
time.sleep(5)
data = {
'apples': [3, 2, 0, 1],
'oranges': [0, 3, 7, 2]
}
df = pd.DataFrame(data)
return df
@app.callback(
Output('content', 'children'),
Input('button', 'n_clicks'),
State('input', 'value')
)
def update_output_1(n_clicks, value):
if not n_clicks:
raise PreventUpdate
data = compute_expensive_data(value)
print(type(data))
return str(value)+', '+data.to_string()
@app.callback(
Output('content_2', 'children'),
Input('button2', 'n_clicks'),
State('input', 'value')
)
def update_output_2(n_clicks, value):
if not n_clicks:
raise PreventUpdate
data = compute_expensive_data(value)
print(type(data))
return str(value)+', '+data.to_string()
if __name__ == '__main__':
app.run_server(host='0.0.0.0', port=8080)