Summary of "Streamlit Mini Course - Make Websites With ONLY Python"
High-level summary
The video is a compact course on Streamlit — a Python UI library for building web interfaces and simple websites entirely in Python (no HTML/CSS/JS required). It covers installation, basic app creation and running, Streamlit’s reactive data flow (full-script reruns), widgets and forms, session state, callbacks, layout options, charts/data display, caching strategies, fragments (partial reruns), multi-page apps, and practical tips / gotchas.
Emphasis throughout:
- Streamlit’s execution model: every interaction triggers a rerun of the whole script.
- How to manage and persist state with
st.session_state. - When reruns are deferred (forms).
- Patterns to write correct, responsive UIs (callbacks, manual rerun, caching, fragments).
Key concepts and lessons
Streamlit purpose and strengths
- Rapid prototyping, data-science dashboards, and ML/AI frontends using only Python.
- Native support for pandas, NumPy, Matplotlib, charts, maps, data tables, etc.
- Good for prototypes and simple production deployments.
Installation and first app
-
Install with pip:
pip install streamlit pandas numpy matplotlib(orpip3/python -m pipas needed). -
Create a Python file, e.g.
main.py:python import streamlit as st st.write("Hello world") -
Run the app:
streamlit run main.pyThe app opens athttp://localhost:8501by default. -
Hot-reload: Streamlit detects source-file changes and can auto-rerun (there’s an “always rerun” option).
Streamlit’s execution model (critical)
- Every interaction or submit triggers a full rerun of the entire Python script. Design apps with that rerun model in mind.
- Widgets return values on each run; widget states are managed via internal IDs and
st.session_state.
st.write and “Streamlit magic”
st.writeautomatically renders many Python object types (strings, numbers, dicts, DataFrames, plots).- Bare expressions in the script (e.g.,
3 + 4) can be shown without explicitst.write.
Text, images and media
- Text helpers:
st.title,st.header,st.subheader,st.caption,st.markdown,st.code,st.divider. - Images: put images in a
static/folder and render withst.image, for example:python import os st.image(os.path.join(os.getcwd(), "static", "yourfile.jpg"), caption="...", width=600)Options includewidth,caption, and full-screen preview.
Data display components
st.dataframe— interactive DataFrame rendering (sorting, searching).st.data_editor— editable tables (edits update Python values on submit / rerun).st.table— static tables.st.metric— highlighted numeric metrics.st.json— formatted JSON/dict display.
Charts
- Built-in chart helpers:
st.area_chart,st.bar_chart,st.line_chart,st.map. - Render Matplotlib figures with
st.pyplot. - Charts are interactive by default (zoom / save).
Widgets, forms and input handling
Widgets
- Common inputs:
st.button,st.slider,st.text_input,st.number_input,st.date_input,st.time_input,st.radio,st.selectbox,st.checkbox,st.text_area, etc. - Each widget has an internal ID derived from its label and parameters. Duplicate widgets with identical parameters cause a “duplicate element ID” error — use
key=to give unique keys.
Forms (st.form)
-
Use a form when you want to defer reruns until the user submits:
python with st.form("form_key"): name = st.text_input("Enter your name") age = st.number_input("Enter your age") submitted = st.form_submit_button("Submit") -
Inputs inside a form do not cause reruns until the form is submitted.
- Must include
st.form_submit_button; on submit Streamlit collects inputs and reruns the script. - After submit, validate inputs and show feedback with
st.warning,st.success,st.balloons, etc. - If you need dynamic updates between form inputs, either place those inputs outside the form or manage their values via
st.session_state.
Session state and persistent data
- Plain Python variables are reset on each rerun. Use
st.session_stateto persist data per user/browser tab. st.session_statebehaves like a per-session dictionary (resets if the user refreshes the page).- Example patterns: ```python if “counter” not in st.session_state: st.session_state.counter = 0
# increment st.session_state.counter += 1
# reset st.session_state.counter = 0 ```
Callbacks and ordering problems
- Because the script reruns on interaction, updates set inside conditionals may only appear on the next rerun, causing “press twice” or off-by-one behavior.
- Use widget callback arguments (
on_click,on_change) to execute functions that updatest.session_statebefore the rest of the script runs. Callbacks run at the beginning of the rerun so rendering logic sees the new state. - Example use-case: moving between steps in a multi-step form — use callbacks to update navigation state early.
Layout and UI structure
- Sidebar:
st.sidebarfor sidebar content (e.g.,st.sidebar.title,st.sidebar.slider). - Tabs:
st.tabs([...])to separate content. - Columns:
st.columns([...])for side-by-side layout. - Container:
with st.container():groups content (optionally visually). - Placeholder:
st.empty()returns a placeholder you can overwrite dynamically. - Expander:
with st.expander("title"):creates collapsible regions. - Tooltips/help: most widgets accept a
helpparameter for hover text.
Advanced widget behaviors and gotchas
- Duplicate IDs: identical widgets produce identical internal IDs — add
key=to avoid collisions. - Changing widget parameters (label, min/max, default) changes their derived IDs and can reset values. If you need to preserve a value when parameters change, mirror the value in
st.session_stateand setvalue=from it. - Destroyed widgets (removed from render tree) lose their state. To preserve values across hide/show cycles, set
value=fromst.session_stateor manage persistence yourself.
Caching (performance)
- Use Streamlit cache decorators to avoid recomputing slow operations across reruns and users:
@st.cache_data— cache immutable function results; supports TTL.@st.cache_resource— cache shared/mutable resources (e.g., DB connections).
- Cached results are global to the server process and shared across sessions. Cache keys include function arguments.
Manual rerun
- Use
st.rerun()(from the Streamlit rerun API) inside callbacks to force an immediate rerun. This resolves “lagging by one” display when you want updated state to be shown immediately.
Fragments (partial reruns)
- Fragments isolate parts of the UI so only those fragments rerun when their internal widgets change — improving responsiveness.
- Fragment code executes independently and cannot return values to the main script. Use
st.session_stateto share data between fragment and main script. - Fragments default to local reruns, but can trigger global reruns if needed.
Multi-page apps
- Native approach: add scripts inside a
pages/folder (e.g.,01_home.py,02_report.py). Streamlit lists them automatically in the sidebar; filenames determine labels and ordering. - Set page metadata with
st.set_page_config(page_title="...", page_icon=...). - Programmatic navigation:
st.switch_page("Page Name"). - Custom router alternative: map labels to functions and render the chosen function via a sidebar
selectboxfor full control. - Store cross-page state in
st.session_stateto avoid losing important data when switching pages.
Practical step-by-step instructions
Minimal app
- Create a project folder and open an editor (e.g., VS Code).
-
Install packages:
pip install streamlit pandas numpy matplotlib -
Create
main.py:python import streamlit as st st.write("Hello world") -
Run:
streamlit run main.py -
Open the URL shown in the terminal (usually
http://localhost:8501).
Build a simple form
- Use a form context and submit button: ```python with st.form(“form_key”): name = st.text_input(“Enter your name”) age = st.number_input(“Enter your age”) submitted = st.form_submit_button(“Submit”)
if submitted: if not name or not age: st.warning(“Please fill all fields”) else: st.success(f”Submitted: {name}, {age}”) st.balloons() ```
Maintain persistent counters
- Initialize and update
st.session_state: ```python if “counter” not in st.session_state: st.session_state.counter = 0
if st.button(“Increment”): st.session_state.counter += 1 st.rerun() # show change immediately
st.write(st.session_state.counter) ```
Use callbacks
- Define functions that modify
st.session_stateand pass them to widgets: ```python def go_to_step_two(): st.session_state.step = 2
st.button(“Next”, on_click=go_to_step_two) ```
Preserve widget values across parameter changes
- Mirror widget values with
st.session_stateand setvalue=from it so values persist when widgets are hidden/shown or reconfigured.
Use caching for expensive ops
- Example:
python @st.cache_data(ttl=60) def fetch_data(...): ...Use@st.cache_resourcefor shared mutable resources like DB connections.
Create multi-page apps
- Native: create
pages/folder with numbered scripts. - Custom: map labels to functions and render the chosen page from a sidebar selection.
Common gotchas & best practices
- Design around the full-script-rerun model — avoid expensive top-level work on every run (use caching).
- Use
st.session_statefor persistent UI state across reruns. - Provide unique keys for widgets when multiple similar widgets exist (
key=). - Wrap inputs that should not immediately cause reruns inside
st.formand use submit buttons. - Use callbacks to update state before rendering decisions.
- Use
st.cache_datafor immutable results andst.cache_resourcefor shared resources. - Use
st.empty/ placeholders and fragments to manage dynamic areas without rerunning the whole page.
Speakers and sources featured
- Main presenter / instructor (unnamed video narrator).
- HubSpot (sponsor; collaborator for a free guide linked by the presenter).
- ChatGPT (used in one caching demonstration).
- Streamlit documentation (referenced repeatedly as the authoritative reference).
- Demo libraries referenced: pandas, numpy, matplotlib, os, datetime.
Category
Educational
Share this summary
Is the summary off?
If you think the summary is inaccurate, you can reprocess it with the latest model.