Streamlit reruns a Python script in response to interactions. Understanding that execution model makes it easier to decide which values should be recomputed, cached, or kept in a user’s session.
A repeatable local example
This example uses Python 3.12, streamlit==1.41.1, numpy==2.2.0, and pandas==2.2.3. Save the following as app.py and run streamlit run app.py in the environment containing those packages.
import numpy as np
import pandas as pd
import streamlit as st
st.title("A repeatable data explorer")
@st.cache_data
def make_data():
rng = np.random.default_rng(7)
return pd.DataFrame(rng.normal(size=(100, 2)), columns=["X", "Y"])
if "submissions" not in st.session_state:
st.session_state.submissions = 0
with st.form("controls"):
rows = st.slider("Rows", 10, 100, 50)
submitted = st.form_submit_button("Update chart")
if submitted:
st.session_state.submissions += 1
st.line_chart(make_data().head(rows))
st.write("Submitted updates:", st.session_state.submissions)
The seed keeps values stable; moving the slider changes the selected prefix rather than inventing new observations. The form batches input changes until submission. session_state retains the counter for the current session, while cache_data avoids rebuilding the same data unnecessarily.
Conceptual illustration; labels describe responsibilities, not a deployment specification.
Cache the right thing
Data caching and shared resource caching have different lifecycles. Do not put a user’s private result into a globally reused resource without considering access and cache keys. A database client also needs a lifecycle appropriate to how the app shares it.
Extending to remote data
For a stock-data or API dashboard, validate the symbol, bound the request, handle empty/error results, and display the observation time. Keep credentials in the deployment’s secret mechanism. A successful download does not establish the source’s licensing or suitability for a particular use.
Deployment and verification
Commit a pinned requirements file with the app and select the runtime explicitly. After deployment, test a fresh session, repeated submissions, two simultaneous sessions, and an upstream failure. Confirm that cache behavior matches the freshness requirements.
Primary references: Streamlit execution flow, session state, and caching.