JBON_DATA

Building Real-Time Dashboards with Streamlit

Streamlit turns Python scripts into shareable web apps in minutes. For operational dashboards that need real-time updates, it's hard to beat the development speed.

Basic Structure

import streamlit as st
import pandas as pd
import plotly.express as px

st.set_page_config(
    page_title="Operations Dashboard",
    page_icon="📊",
    layout="wide"
)

st.title("📊 Real-Time Operations Dashboard")

# Sidebar filters
with st.sidebar:
    selected_date = st.date_input("Select Date")
    refresh_rate = st.slider("Refresh (sec)", 5, 60, 30)

# Auto-refresh
st_autorefresh = st.empty()

# Load data
@st.cache_data(ttl=30)
def load_data():
    return pd.read_sql("SELECT * FROM metrics", conn)

data = load_data()

Real-Time Updates

import time

# Method 1: Using st.rerun (Streamlit 1.27+)
if st.button("Refresh Now"):
    st.rerun()

# Method 2: Auto-refresh with placeholder
placeholder = st.empty()

while True:
    with placeholder.container():
        data = fetch_latest_data()
        
        col1, col2, col3 = st.columns(3)
        col1.metric("Orders Today", data['orders'], 
                   delta=data['orders_delta'])
        col2.metric("Revenue", f"${data['revenue']:,.0f}")
        col3.metric("Fill Rate", f"{data['fill_rate']:.1%}")
        
        st.plotly_chart(create_trend_chart(data))
    
    time.sleep(30)
    st.rerun()

Interactive Filtering

# Multi-select filters
warehouses = st.multiselect(
    "Select Warehouses",
    options=data['warehouse'].unique(),
    default=data['warehouse'].unique()
)

# Date range
date_range = st.date_input(
    "Date Range",
    value=(datetime.now() - timedelta(days=7), datetime.now())
)

# Apply filters
filtered = data[
    (data['warehouse'].isin(warehouses)) &
    (data['date'].between(date_range[0], date_range[1]))
]

Performance Optimization

# Cache expensive operations
@st.cache_data(ttl=300)  # Cache for 5 minutes
def expensive_computation(data):
    # Heavy processing
    return result

# Cache database connections
@st.cache_resource
def init_connection():
    return create_engine(DATABASE_URL)

# Use session state for persistence
if 'history' not in st.session_state:
    st.session_state.history = []

Deployment Options

# Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8501
CMD ["streamlit", "run", "dashboard.py", 
     "--server.port=8501", 
     "--server.address=0.0.0.0"]

Common Patterns

  • Multi-page apps: Use pages/ folder structure
  • Authentication: streamlit-authenticator package
  • Embedded charts: Plotly, Altair, or native st.line_chart
  • Data export: st.download_button for CSV/Excel

Streamlit's simplicity means analysts can build and iterate without frontend expertise.

← Back to Blog