Mini Article: Streamlit or Dash? Why not Both?
Streamlit and Dash are two of the most popular dashboarding libraries in Python. Both are touted for their ease of use, high interactability, and widespread community adoption. My personal experience is mostly in Dash, but recently I have been using Streamlit for its simple and customizable chat interface.
Building with Streamlit but primarily being a Dash user made me think: what if we could harness the power of both libraries at the same time? Luckily, we can and it’s very simple.
Set Up
First, you will want to install the necessary packages:
pip install streamlit dash
Then, create a file for your Streamlit app, I cleverly named mine streamlit_app.py.
import streamlit as st
st.title('Streamlit App')
st.write('This is a streamlit app inside a dash app!')
Next, you will create a Dash app. This is where the magic happens. Within this file, you will launch your Streamlit app on a specific port and embed the application into Dash using an iframe. An iframe (short for inline frame) is an HTML component that can reference and render other HTML pages. My (also cleverly named) dash_app.py looks like this:
import streamlit as st
import threading
import subprocess
from dash import Dash, html
def run_streamlit_app(file_name):
subprocess.run(['streamlit', 'run', file_name, '--server.port=8501'])
app = Dash()
app.layout = [
html.Div('This is the dash app.'),
html.Iframe(
src = 'http://localhost:8501',
style = {
'width': '100%',
'height': '400px',
'border': 'none'
}
)
]
if __name__ == '__main__':
threading.Thread(target = run_streamlit_app, daemon=True, kwargs = dict(file_name = 'streamlit_app.py')).start()
app.run(debug = True)
The threading module allows us to run the Streamlit and Dash apps concurrently, while the iframe creates a window from the Dash app into the Streamlit app.
The Final Product
You can launch the application by running:
python3 dash_app.py
And voila! You have created an application that combines both Dash and Streamlit. Future work on this project could involve creating an application that allows a user to interact with the same dataset using both applications. This may involve a separate backend server where each app would instantiate its own connection. By using this design pattern, you can combine the best of two of the top dashboarding libraries in the Python ecosystem. To explore this project further, play around with the code, or contribute, visit the GitHub repository set up for this project: streamlit_in_dash.
For more projects and updates, check out my website: derekmeegan.com