Env set-up (linux/mac)

  • Ensure you have Python Installed ( version 3.7 + )
    • Ensure you have an IDE that you are familiar with (preferably VScode)
    • Create a new folder for this tutorial and cd into it
    • Create a virtual environment using venv or virtualenv
      python -m venv venv
    
    • Activate the virtual environment
      source venv/bin/activate
    
    • pip install the requirements
      pip install -r requirements.txt
    


What is Dash?

  • low-code framework for building data apps
  • “Dash is React for Python”
  • Built using React.js (front-end) and Flask (backend)
  • Built by Plotly - A very popular graphing library (Best imo)
    • Most dash apps use a lot of Plotly graphs, so we will be touching on that a bit
  • I am a data scientist, why do I need to bother with Dash?
    • Most data scientist do not bother with software development roles like building web-apps
    • However, having the ability to do so makes you stand out and also makes you more complete as an engineer who can take charge of the entire life cycle of the Data
      • It helps to communicate with clients/software team what the dashboard should look like
  • What kind of apps can you build?
    • Simple forms to send and receive data from a Database
    • Perform inference for Data Science Apps - image classification, text classification…
    • Real time updates for covid-19 data
    • Personal stock or crypto watchlist dashboard

Dash app layout (single page)

# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd

app = dash.Dash(__name__)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
"Amount": [4, 1, 2, 2, 4, 5],
"City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

app.layout = html.Div(children=[
html.H1(children='Hello Dash'),

html.Div(children='''
    Dash: A web application framework for your data.
'''),

dcc.Graph(
    id='example-graph',
    figure=fig
)
])

if __name__ == '__main__':
app.run_server(debug=True)


  • app = dash.Dash(name)
  • This is where the Dash app is initialized.
    • It is exactly the same as how you would initialise a Flask app
    • This starts up a Flask server (locally) for the Dash app to work
    • You could pass your own Flask server to Dash if you want…
  • app.layout = html.Div(……….)
  • The layout is where all the components of your app lives (inside a HTML.div)
  • TIP: Try to keep the layout as lean as possible
    • Keep all dataframes, plots, large texts, colours outside of the layout
    • Notice the bracketing convention
      • There will be many nested brackets as your app gets more complex
      • Try not to put all your code in one long line
      • Put each new parameter on a new line after each comma
      • Put nested brackets on new lines
  • What are components?
    • Components are like widgets that you can position on your webpage and can add custom functionality to.
    • Dash has a large range of components
      • Dash Core Components (dcc)
      • Dash HTML Components
      • Dash Bootstrap Components (dbc)
  • if name == ‘main’: app.run_server(debug=True)
  • The “if name == ‘main’:” guard…
  • app.run_server(debug=True)
    • this starts the server with your Dash app.
    • you can view it in a browser of your choice.
    • This is also how you start a Flask server
    • debug=True is optional, but very handy when you are building and testing your app.




Commonly used components

  • HTML components
    • Headers (H1, H2, …, H6)
    • Div
    • Break
  • Core components
    • Sliders
    • Dropdown
    • Graph
    • Buttons
    • Link
  • Dash Bootstrap Components


At this point we are able to create our own simple webpages using only Python. But the webpage does not have much functionality. It is considered to be “static”.

  • Callbacks
    • Callbacks give your application “life”! Callbacks enable “communication” between different components of your app.
      • Eg. if you use carousell or any shopping app and you are looking for some shoes (and are on a budget), you would click on the filter button or sort button to look for cheaper products. Then the app would refresh momentarily and return you the appropriate results. This is what callbacks allow us to do.
      import dash
      import dash_core_components as dcc
      import dash_html_components as html
      from dash.dependencies import Input, Output
        
      app = dash.Dash(__name__)
        
      app.layout = html.Div([
          html.H6("Change the value in the text box to see callbacks in action!"),
          html.Div([
              "Input: ",
              dcc.Input(id='my-input', value='initial value', type='text')
          ]),
          html.Br(),
          html.Div(id='my-output'),
        
      ])
        
      @app.callback(
          Output(component_id='my-output', component_property='children'),
          Input(component_id='my-input', component_property='value')
      )
      def update_output_div(input_value):
          return 'Output: {}'.format(input_value)
        
      if __name__ == '__main__':
          app.run_server(debug=True)
    
    • @app.callback
      • @ - decorator
        • it is a function that takes in another function as an argument and does some changes to it, then returns another function
      • Output(component_id=’my-output’, component_property=’children’)
        • The output of the function affects the ‘my-output’ component

        • Specifically, it updates the ‘children’ property of the ‘component’

      • Outputs must come first, followed by Inputs (and then States)
    • [Multi-output/input]
      • If your callback function affects multiple components, put them all in a list
    • Caveat
      • You cannot create two (or more) callback functions that have a common output!
      • The workaround is to combine the functions that want to affect a common output component and differentiate how it should be updated based on the inputs using callback_context

Deploying your Dash app for free!

  • Install Git
  • Create an account on Heroku
  • git init or use any other methods you are familiar with to initialise a git repository
  • Create a .gitignore file (just a text file)
    • add the following
      venv
      *.pyc
      .DS_Store
      .env
    
  • Create a Procfile file (just a text file)
    • add the following line
      • web: gunicorn app:server
    • web - type of heroku service
    • gunicorn - The Gunicorn “Green Unicorn” is a Python Web Server Gateway Interface HTTP server
      • Gunicorn is a pure-Python HTTP server for WSGI applications. It allows you to run any Python application concurrently by running multiple Python processes within a single dyno.
    • app (before the “:” )
      • the name of the dash app file - app.py
      • alternatively any {filename}.py
    • app (after the “:”)
      • The Dash app variable inside the the app.py file
  • Create the heroku app
    • heroku create dash-app (use any name you like for the dash app)
    • git add . - add all the files in the current working directory to git
    • git commit -m 'First deployment commit!' - commit the changes (use any message you like)
    • git push heroku master - deploy to heroku
    • wait for about 2-3 minutes

Miscellaneous