Skip to main content
Skip table of contents

How To: Setup Shiny or Dash App in Data Lab

Overview

This document provides a step-by-step guide on how to set up and run Dash or Shiny apps within Data Lab, our Jupyter offering. These steps will enable users to seamlessly integrate and run their Dash/Shiny applications within the Data Lab environment.

Steps to Setup Dash or Shiny App

Ensure jupyter_server_proxy package is installed

  1. Open a Data Lab Project.

  2. Open a new terminal/command line interface.

  3. Confirm jupyter_server_proxy Python package is installed by executing the following command

    CODE
    pip show jupyter_server_proxy
  4. If the terminal displays WARNING: Package(s) not found: jupyter_server_proxy then install the jupyter_server_proxy Python package by executing the following command

    CODE
    pip install jupyter_server_proxy
  5. If you installed the jupyter_server_proxy Python package, then shutdown (by clicking the power icon at top right) the Data Lab project and reopen it. This step ensures that the jupyter_server_proxy extension is linked and loaded to the Jupyter server upon the next startup. If it was already installed, you do not need to shutdown the project.

If you installed the jupyter_server_proxy Python package and you are using a Pyhton 3.11 notebook, you must also install it in Python 3.8 environment.

Global installation of the jupyter_server_proxy package is not supported.

Dash App Example

  1. Open a new terminal/command line interface.

  2. Install all the required packages. (e.g., dash using pip)

    PY
    pip install dash
  3. Write your code for creating the Dash app within your Jupyter Notebook.

  4. Utilize the following example to configure the app:

    PY
    from dash import Dash, html, dcc, callback, Output, Input
    
    # Load the dataset from Example >> Cooling Tower 1 >> Area A
    results = spy.search({"Path": "Example >> Cooling Tower 1 >> Area A"}, quiet=True)
    df = spy.pull(results, start='2019-01-01', end='2019-01-15', grid='30min', header='Name', quiet=True)
    
    project_id = spy.utils.get_data_lab_project_id()
    port = spy.utils.get_open_port()
    
    # Set the requests_pathname_prefix
    requests_pathname_prefix = f"/data-lab/{project_id}/proxy/{port}/"
    
    app = Dash("Cooling Tower 1", requests_pathname_prefix=requests_pathname_prefix)
    
    # Define the layout of the app
    app.layout = html.Div([
        html.H1("Cooling Tower 1 >> Area A",style={'text-align': 'center'}),
        html.Label("Select a signal to display:"),
        dcc.Dropdown(
            id='dropdown',
            options=[{'label': col, 'value': col} for col in df.columns],
            value=df.columns[0]
        ),
        html.Div(id='output-graph')
    ])
    
    # Define callback to update the output
    @app.callback(
        Output('output-graph', 'children'),
        [Input('dropdown', 'value')]
    )
    def update_graph(selected_column):
        return dcc.Graph(
            figure={
                'data': [
                    {'x': df.index, 'y': df[selected_column], 'type': 'line', 'name': selected_column}
                ],
                'layout': {
                    'title': selected_column + ' over time',
                    'xaxis': {'title': 'Timestamp'},
                    'yaxis': {'title': selected_column}
                }
            }
        )
    
    # Run the app
    app.run(port=port, jupyter_server_url=spy.session.public_url)
  5. Run the App

    1. Execute the code within your Jupyter notebook.

    2. Once the code is executed, the Dash app should run inline within your Jupyter Notebook.

Shiny App Example

  1. Open a new terminal/command line interface.

  2. Install all the required packages. (e.g., dash using pip)

    PY
    pip install shiny
  3. Write your code for creating the Shiny app within your Jupyter Notebook.

  4. Utilize the following example to configure the app:

    CODE
    import asyncio
    import threading
    import matplotlib.pyplot as plt
    import numpy as np
    from shiny import App, ui, render, run_app
    from IPython.display import IFrame
    
    port = spy.utils.get_open_port()
    
    app_ui = ui.page_fluid(
        ui.input_slider("n", "Number of bins", min=5, max=50, value=20),
        ui.output_plot("hist")
    )
    
    def server(input, output, session):
        @output()
        @render.plot
        def hist():
            x = np.random.randn(1000)
            plt.hist(x, bins=input.n())
    
    def start_shiny():
        run_app(app, host="0.0.0.0", port=port, launch_browser=False)
    
    app = App(app_ui, server)
    thread = threading.Thread(target=start_shiny)
    thread.start()
    
    # Generate the Data Lab project's url for displaying Shiny app in a browser
    url = f"{spy.utils.get_data_lab_project_url(use_private_url=False)}/proxy/{port}/"
    print(url)
    
    # Render the Shiny app within the notebook
    display(IFrame(url, width='100%', height='500'))
  5. Run the App

    1. Execute the code within your Jupyter notebook.

    2. Once the code is executed, the Shiny app should run inline within your Jupyter Notebook. It will also print a url that when clicked will allow you access the Shiny app in a browser tab.

Compatibility Notes

The spy.utils.get_open_port() utility function used in both the previous examples is available from Spy version 192.16 and above. If your Spy version is lower, utilize the helper function provided below.

CODE
def get_open_port() -> int:
    import socket
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(('', 0))
        return s.getsockname()[1]

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.