Redis App
Deployment Mode

# 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)
		
# 2. Create requirements.txt
pip freeze > requirements.txt
		
# 3. Create Dockerfile
FROM python:3.8

WORKDIR /usr/src/app

COPY . .

RUN pip install --no-cache-dir -r requirements.txt

EXPOSE 8080

CMD ["python", "./app.py"]
		
# 4. Build Image
docker build -t redis_app .
        
# 5. Start Containers

# Create Network
docker network create asgard

# Start Redis Container
docker run --name myredis --network asgard -d redis

# Start App Container
docker run --network asgard -e MYREDIS_HOST=myredis -d -p 8080:8080 redis_app
        
# 6. Start App
http://localhost:8080/