Streamlit 数据应用快速开发指南

Lisa Tan | 2026-09-01T08:57:38 | Python, AI

演示 Streamlit 的组件系统、缓存机制、会话状态、多页面应用架构及部署到 Streamlit Cloud 的完整流程。

# Streamlit 数据应用快速开发指南 ## 快速上手 ```python import streamlit as st import pandas as pd import plotly.express as px st.set_page_config(page_title="Sales Dashboard", layout="wide") st.title("Sales Analytics Dashboard") # 侧边栏筛选器 with st.sidebar: st.header("Filters") date_range = st.date_input("Date Range", value=[]) category = st.multiselect("Category", ["Electronics", "Clothing", "Food"]) min_amount = st.slider("Min Amount", 0, 10000, 0) ``` ## 缓存加速 ```python @st.cache_data(ttl=3600) # 缓存1小时 def load_data(path): df = pd.read_csv(path) df["date"] = pd.to_datetime(df["date"]) return df @st.cache_resource # 缓存数据库连接等资源 def get_db_connection(): return create_engine("postgresql://user:pass@host/db") data = load_data("sales.csv") ``` ## 交互式图表 ```python col1, col2 = st.columns(2) with col1: st.subheader("Revenue by Category") fig1 = px.pie(filtered_data, values="amount", names="category", hole=0.4, color_discrete_sequence=px.colors.qualitative.Set2) st.plotly_chart(fig1, use_container_width=True) with col2: st.subheader("Monthly Trend") monthly = filtered_data.groupby( filtered_data["date"].dt.to_period("M") )["amount"].sum().reset_index() monthly["date"] = monthly["date"].astype(str) fig2 = px.line(monthly, x="date", y="amount", markers=True) st.plotly_chart(fig2, use_container_width=True) ``` ## 会话状态管理 ```python if "messages" not in st.session_state: st.session_state.messages = [] prompt = st.chat_input("Ask about the data") if prompt: st.session_state.messages.append({"role": "user", "content": prompt}) response = query_llm(prompt, context=data.describe().to_string()) st.session_state.messages.append({"role": "assistant", "content": response}) for msg in st.session_state.messages: with st.chat_message(msg["role"]): st.markdown(msg["content"]) ``` ## 多页面架构 ``` my_app/ pages/ 1_Dashboard.py 2_Data_Explorer.py 3_Settings.py Home.py # 入口 ``` Streamlit 让数据科学家无需前端知识即可构建交互式应用。部署到 Streamlit Cloud 只需关联 GitHub 仓库,免费额度足够个人项目使用。

← Back to Blog