Streamlit simplifies creating web apps with Python scripts, no HTML or CSS required. With just a few lines of Python code, you can create fully functional web applications that include titles, text, data tables, and visualizations. Streamlit handles all the web development complexity behind the scenes, allowing data scientists and developers to focus on their Python logic rather than learning web technologies.
import streamlit as stimport pandas as pdimport numpy as npst.title('My First Streamlit App')st.write('Hello, World!')# Create some sample datadata = pd.DataFrame({'numbers': np.random.randn(20),'letters': np.random.choice(['A', 'B', 'C'], 20)})st.dataframe(data)st.line_chart(data['numbers'])
Widgets are the interactive elements that allow users to provide input to your application. Each widget returns a value that can be used in your Python code, and when users interact with these widgets, Streamlit automatically updates the application with the new values.
# Text input widgetname = st.text_input('What\'s your name?')# Slider widgetage = st.slider('How old are you?', 13, 100, 25)# Selectbox widget (dropdown)genre = st.selectbox('Favorite movie genre:',['Action', 'Comedy', 'Drama', 'Horror', 'Sci-Fi'])# Checkbox widgetwants_popcorn = st.checkbox('Do you like popcorn?')# Button widgetif st.button('Get My Movie Recommendation'):st.write(f"Hello {name}! Based on your preferences...")
Streamlit Rerun BehaviorUnderstanding Streamlit’s execution model is crucial for building effective applications. Every widget interaction triggers a complete script rerun, which means regular Python variables get reset to their initial values. This behavior explains why simple variable assignments don’t persist between user interactions.
# This creates a fresh empty list on every interaction!shopping_list = []# User inputitem = st.text_input('Add item to shopping list:')if st.button('Add Item'):shopping_list.append(item) # Gets reset on next interactionst.write(shopping_list) # Will only show current item
st.session_stateSession state is Streamlit’s solution for maintaining data across script reruns. By storing values in st.session_state, you can build applications that remember user interactions, accumulate data over time, and maintain complex application states that persist throughout the user’s session.
import streamlit as st# Initialize session stateif 'shopping_list' not in st.session_state:st.session_state.shopping_list = []# User inputitem = st.text_input('Add item to shopping list:')if st.button('Add Item'):# This persists across reruns!st.session_state.shopping_list.append(item)# Display persistent listst.write("Your shopping list:", st.session_state.shopping_list)
Streamlit offers versatile methods for showcasing data. Use st.metric() to display vital stats, while st.dataframe() presents interactive tables. Visualize data with built-in chart functions or integrate with libraries like Matplotlib, Seaborn, and Plotly for advanced plotting.
import streamlit as stimport pandas as pdimport matplotlib.pyplot as plt# Display a key performance indicatorst.metric(label="Acquisition Growth Rate", value="7%", delta="1.5%")# Display an interactive tablesample_data = pd.DataFrame({"Metric": ["Visitors", "Conversions", "Revenue"],"2022": [1200, 300, 5000],"2023": [1400, 350, 7500]})st.dataframe(sample_data, use_container_width=True)# Example plot using matplotlibfig, ax = plt.subplots()ax.plot(['Q1', 'Q2', 'Q3', 'Q4'], [100, 200, 300, 400], label='2022')ax.set_title('Quarterly Growth')ax.set_xlabel('Quarter')ax.set_ylabel('Growth')st.pyplot(fig)
st.button()Buttons have unique behavior compared to other widgets - they only return True for the instant they’re clicked, then immediately return False. This makes them perfect for triggering specific actions like form submissions, calculations, or processing steps that should only happen when explicitly requested by the user.
# Button only returns True at the moment of clickingif st.button('Get My Movie Recommendation'):# This code only runs when the button is clickedst.write("Generating recommendation...")# Processing logic here# This runs every time the script rerunsst.write("This text always appears")
As applications grow in complexity, organizing content becomes essential for user experience. Tabs provide a way to group related functionality on a single page, while separate page files create distinct sections with automatic navigation. This organization helps users navigate complex applications without overwhelming them with too much content at once.
# Using tabs for organizationtab1, tab2, tab3 = st.tabs(["📝 Shopping List", "📊 Analytics", "💰 Budget"])with tab1:st.header('Current Shopping List')# Shopping list functionality herewith tab2:st.header('📊 Shopping Analytics')# Analytics functionality herewith tab3:st.header('💰 Budget')# Budget functionality here
st.connectionStreamlit simplifies database integration by providing built-in connection management and smart caching. The ttl (time-to-live) parameter automatically caches query results for specified durations, reducing database load and improving application performance. This makes it easy to build data-driven applications that scale effectively.
import streamlit as st# Establish a cached database connection@st.cache_resourcedef get_database_connection():return st.connection('my_db', type='sql', url='sqlite:///data/coffee_shop.db')# Query with caching (TTL = Time To Live)top_products = conn.query("""SELECTp.name as Drink,SUM(s.quantity) as Sales,p.price as PriceFROM sales sJOIN products p ON s.product_id = p.idGROUP BY p.id, p.name, p.priceORDER BY Sales DESCLIMIT 3""", ttl=300) # Cache for 5 minutesst.table(top_products)
Streamlit ModelsStreamlit applications can incorporate machine learning models saved in different formats depending on the library used to create them. Understanding the appropriate loading method for each model type enables you to integrate predictions and AI capabilities into your web applications seamlessly.
import joblibimport pickleimport streamlit as st# Scikit-learn models (most common)model = joblib.load('sales_forecast_model.pkl')# Alternative for sklearn using picklewith open('sales_forecast_model.pkl', 'rb') as f:model = pickle.load(f)# PyTorch modelsimport torchmodel = torch.load('model.pth')# TensorFlow/Keras modelsimport tensorflow as tfmodel = tf.keras.models.load_model('model.h5')#Write prediction outputst.write(model.predict(data))
Resource caching prevents expensive operations from repeating unnecessarily. While normal variables reset on every script rerun, the @st.cache_resource decorator ensures that costly operations like loading large ML models or establishing database connections happen only once per session, dramatically improving application performance and user experience.
import streamlit as stimport joblib@st.cache_resourcedef load_sales_forecast_model():"""Load and cache the sales forecasting model"""try:# Model loads only once per session!return joblib.load('models/sales_forecast_model.pkl')except Exception as e:st.error(f"Error loading model: {e}")return None# This will only load the model once, then reuse itmodel = load_sales_forecast_model()if model:prediction = model.predict(input_data)st.write(f"Prediction: {prediction}")