Streamlit App

Streamlit turns a plain Python script into an interactive web app with no HTML, routes, or callbacks. The example above takes a name and an age from widgets, prints a greeting, and draws a line chart of random data. The mock-up at the top shows roughly what the browser renders; the sections below explain how the app works and how to extend it.

Hello, Kevin! You are 25 years old.

Line Chart

A B C
0.17-0.571.22
-0.471.11-0.34
0.33-0.880.45
-1.121.34-0.76
1.020.660.99


#!/usr/bin/env python

import streamlit as st
import pandas as pd
import numpy as np

# Title of the app
st.title("Streamlit App")

# Text input box
user_name = st.text_input("Enter your name", "Kevin")

# Slider input
age = st.slider("Select your age", 1, 100, 25)

# Display user input
st.write(f"Hello, {user_name}! You are {age} years old.")

# Generate sample data
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["A", "B", "C"]
)

# Display a line chart
st.line_chart(chart_data)

1. What the App Does

The script builds a single page with four elements: a title, a text box pre-filled with "Kevin", a slider from 1 to 100 defaulting to 25, and a greeting that combines both values. Below that it generates a 20-row, three-column DataFrame of standard normal random numbers and renders it as a line chart with one line per column. It is a starting template for internal tools, data exploration front-ends, and demos for machine learning models, which is why it sits alongside the document-ingestion scripts on this site.

Everything in the app is driven by ordinary Python values. There is no template language, no JavaScript, and no request handler: the script itself describes the page, in order, and Streamlit decides how to render each element. That makes it easy to turn an existing analysis notebook into a shareable tool by replacing hard-coded parameters with widgets. The trade-off, covered below, is that the framework controls the execution model, so performance depends on understanding when and why the script reruns and how caching interacts with it.

2. How Streamlit Works

Streamlit Execution Model Browser widget change Tornado server websocket Script rerun top to bottom Widgets return current values st.write / chart emit delta messages Browser patch the page Every interaction re-executes the whole script; widget state is preserved between runs.

Running streamlit run app.py starts a Tornado web server and opens a websocket to the browser. When a user changes a widget, the browser sends the new value and the server re-executes the script from the first line to the last. Each widget call such as st.slider returns its current value instead of registering a callback, so the code reads top to bottom like a batch script. As the script runs, each st.* call sends a small delta message, and the front-end patches only the elements that changed.

This rerun model is what makes Streamlit simple, and it is also its main cost: anything expensive at the top level, such as loading a model or reading a large file, runs again on every interaction unless it is cached.

3. The Code Explained

Data Flow in This App text_input user_name slider age 1..100 st.write greeting np.random.randn 20 x 3 array DataFrame columns A, B, C st.line_chart three series

st.title renders the page heading. st.text_input(label, default) returns a string, and st.slider(label, min, max, default) returns an integer because all three bounds are integers. st.write is a generic renderer: given an f-string it emits Markdown, given a DataFrame it renders an interactive table. np.random.randn(20, 3) draws a new random array on every rerun, which is why the chart changes each time you move the slider. st.line_chart plots the DataFrame index on the x axis and each column as a series.

A slightly extended version that keeps the chart stable and adds layout:

import streamlit as st
import pandas as pd
import numpy as np

st.set_page_config(page_title="Demo", layout="wide")

@st.cache_data
def load_data(rows: int, seed: int = 0) -> pd.DataFrame:
    rng = np.random.default_rng(seed)
    return pd.DataFrame(rng.standard_normal((rows, 3)).cumsum(axis=0), columns=list("ABC"))

with st.sidebar:
    name = st.text_input("Enter your name", "Kevin")
    age = st.slider("Select your age", 1, 100, 25)
    rows = st.number_input("Rows", 10, 1000, 20)

st.write(f"Hello, {name}! You are {age} years old.")
left, right = st.columns(2)
df = load_data(int(rows))
left.line_chart(df)
right.dataframe(df.describe())

4. Installation and Usage

python3 -m venv .venv && source .venv/bin/activate
pip install streamlit pandas numpy
streamlit run app.py                 # opens http://localhost:8501
streamlit run app.py --server.port 8080 --server.address 0.0.0.0

Streamlit watches the source file and offers to rerun when it changes, so editing and saving gives a fast feedback loop. For deployment behind Apache or Nginx, proxy both HTTP and the websocket path, and set server.headless = true in .streamlit/config.toml.

5. When to Use Streamlit

ToolStrengthWeakness
StreamlitFastest path from script to appWhole-script reruns, limited layout control
GradioModel demos with input/output componentsLess suited to dashboards
DashExplicit callbacks, fine-grained updatesMore boilerplate
Flask + JSFull control, any UIYou write the front-end

6. Pitfalls