
当数据科学家小王需要将机器学习模型的预测结果可视化时,他面临两个选择:要么花两周时间学习前端框架,要么用三天时间把Python脚本改造成网页应用。最终他选择了Streamlit——这个2019年诞生的Python库,仅用50行代码就实现了实时交互的预测看板。这个真实案例揭示了Streamlit的核心价值:用Python开发者熟悉的语法,消除前端开发门槛。

对比传统Web开发框架,Streamlit的优势体现在三个维度:
st.title()直接生成网页标题st.slider()自动绑定数值变化事件在GitHub上,Streamlit已收获42.3k星标,被微软、亚马逊等企业用于内部工具开发。其设计哲学"Write once, run anywhere"正在重塑数据应用的开发范式。
# 创建虚拟环境(推荐)
python -m venv streamlit_env
source streamlit_env/bin/activate # Linux/Mac
streamlit_env\Scripts\activate # Windows
# 安装核心库
pip install streamlit pandas numpy matplotlib
验证安装成功后,运行官方示例:
streamlit hello
浏览器自动打开的欢迎页面包含8个交互式Demo,展示了数据可视化、机器学习模型部署等场景。
文本展示三件套:
import streamlit as st
st.title("图书价格监控系统") # 一级标题
st.header("当当/京东/亚马逊比价") # 二级标题
st.write("当前监控图书:《Python编程从入门到实践》") # 普通文本
数据可视化组合技:
import pandas as pd
import numpy as np
# 生成模拟数据
data = pd.DataFrame({
'平台': ['当当', '京东', '亚马逊']*10,
'价格': np.random.uniform(30, 100, 30),
'库存': np.random.randint(0, 100, 30)
})
# 交互式表格
st.subheader("原始数据")
st.dataframe(data.style.highlight_min(axis=0, subset=['价格']))
# 多图表布局
col1, col2 = st.columns(2)
with col1:
st.bar_chart(data, x='平台', y='价格', color='#1f77b4')
with col2:
st.line_chart(data.groupby('平台')['价格'].mean())
交互控制三要素:
# 滑块控制
price_threshold = st.slider("价格阈值", 0, 200, 50)
# 下拉框选择
platform_filter = st.selectbox("选择平台", ['全部'] + list(data['平台'].unique()))
# 按钮触发
if st.button("生成报告"):
filtered_data = data[
(data['价格'] < price_threshold) &
((data['平台'] == platform_filter) | (platform_filter == '全部'))
]
st.success(f"找到{len(filtered_data)}条符合条件的记录")
当监控多个电商平台时,需要定时刷新数据:
import time
from datetime import datetime
# 模拟数据获取函数
def fetch_book_prices():
# 实际项目中替换为爬虫代码
return pd.DataFrame({
'平台': ['当当', '京东', '亚马逊'],
'价格': [45.8, 49.9, 52.5],
'更新时间': [datetime.now()]*3
})
# 定时刷新配置
st.set_page_config(page_title="实时价格监控", layout="wide")
refresh_interval = st.sidebar.number_input("刷新间隔(秒)", 5, 300, 10)
# 动态数据展示
last_update = None
while True:
with st.spinner("数据加载中..."):
current_data = fetch_book_prices()
last_update = current_data['更新时间'][0]
st.subheader(f"最后更新时间:{last_update}")
st.table(current_data.style.format({'价格': '¥{:.2f}'}))
time.sleep(refresh_interval)
# Streamlit会自动检测代码变化并刷新页面
当用户需要上传本地图书清单时:
uploaded_file = st.file_uploader("选择图书清单", type=['csv', 'xlsx'])
if uploaded_file is not None:
try:
if uploaded_file.name.endswith('.csv'):
df = pd.read_csv(uploaded_file)
else:
df = pd.read_excel(uploaded_file)
st.subheader("上传文件预览")
st.dataframe(df.head())
# 处理数据逻辑...
st.success(f"成功处理{len(df)}条图书记录")
except Exception as e:
st.error(f"文件处理失败:{str(e)}")
通过st.session_state实现页面导航:
# 初始化页面状态
if 'current_page' not in st.session_state:
st.session_state.current_page = 'home'
# 导航栏
with st.sidebar:
st.title("导航菜单")
if st.button("首页"):
st.session_state.current_page = 'home'
if st.button("价格监控"):
st.session_state.current_page = 'monitor'
if st.button("历史趋势"):
st.session_state.current_page = 'trend'
# 页面渲染
if st.session_state.current_page == 'home':
st.title("欢迎使用图书比价系统")
st.image("https://example.com/book_cover.jpg", use_column_width=True)
elif st.session_state.current_page == 'monitor':
# 价格监控页面代码...
pass
elif st.session_state.current_page == 'trend':
# 历史趋势页面代码...
pass
当频繁调用爬虫接口时:
import requests
from functools import lru_cache
@st.cache_data(ttl=600) # 缓存10分钟
def get_dangdang_price(isbn):
url = f"https://product.dangdang.com/{isbn}.html"
headers = {'User-Agent': 'Mozilla/5.0'}
try:
response = requests.get(url, headers=headers, timeout=10)
# 实际解析逻辑...
return 45.8 # 模拟返回价格
except:
return None
price = get_dangdang_price("9787115546081")
st.write(f"当当价格:¥{price:.2f}")
处理用户输入时必须进行验证:
import re
def validate_isbn(isbn):
pattern = r'^(978|979)?\d{10}$'
return bool(re.match(pattern, str(isbn).strip()))
user_input = st.text_input("输入ISBN编号")
if st.button("查询"):
if not validate_isbn(user_input):
st.error("请输入有效的ISBN编号(10位或13位数字)")
else:
# 查询逻辑...
pass
使用Nginx反向代理部署Streamlit应用:
server {
listen 80;
server_name your-domain.com;
location / {
proxy_pass http://127.0.0.1:8501;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_buffering off;
}
}
启动命令添加SSL支持:
streamlit run app.py --server.sslCertFile=/path/to/cert.pem --server.sslKeyFile=/path/to/key.pem
Q1:被网站封IP怎么办? A:立即启用代理池策略,推荐使用站大爷住宅代理配合随机延迟:
import random
from fake_useragent import UserAgent
proxies = [
{"http": "http://123.123.123.123:8080"},
# 更多代理IP...
]
def fetch_with_proxy(url):
proxy = random.choice(proxies)
headers = {"User-Agent": UserAgent().random}
try:
response = requests.get(url, headers=headers, proxies=proxy, timeout=10)
return response
except:
return fetch_with_proxy(url) # 自动重试
Q2:如何处理大量数据展示? A:使用分页显示和虚拟滚动技术:
import math
# 模拟大数据集
large_data = pd.DataFrame({
'序号': range(1, 10001),
'价格': np.random.uniform(10, 200, 10000)
})
# 分页控制
items_per_page = 50
page_number = st.number_input("页码", 1, math.ceil(len(large_data)/items_per_page), 1)
start_idx = (page_number-1)*items_per_page
end_idx = start_idx + items_per_page
# 显示当前页数据
st.dataframe(large_data.iloc[start_idx:end_idx])
st.write(f"显示 {start_idx+1}-{min(end_idx, len(large_data)))} 条,共 {len(large_data)} 条记录")
Q3:如何实现用户认证?
A:使用Streamlit的st.experimental_user(需1.25+版本)或集成OAuth2:
# 简单密码保护
PASSWORD = "your_password"
if 'authenticated' not in st.session_state:
st.session_state.authenticated = False
if not st.session_state.authenticated:
input_pwd = st.text_input("请输入密码", type="password")
if st.button("登录"):
if input_pwd == PASSWORD:
st.session_state.authenticated = True
st.success("登录成功")
else:
st.error("密码错误")
else:
# 主应用代码...
pass
Q4:如何导出数据到Excel? A:添加下载按钮:
import pandas as pd
from io import BytesIO
# 生成示例数据
data = pd.DataFrame({'A': range(10), 'B': range(10, 20)})
# 转换为Excel
output = BytesIO()
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
data.to_excel(writer, index=False, sheet_name='Sheet1')
output.seek(0)
# 添加下载按钮
st.download_button(
label="下载Excel",
data=output,
file_name="export_data.xlsx",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
Q5:如何实现实时通知?
A:使用st.toast显示短暂通知:
if st.button("发送通知"):
st.toast("操作成功!", icon="✅")
# 或显示错误通知
# st.toast("操作失败", icon="❌")
随着Streamlit 1.50版本的发布,三大新特性正在重塑开发体验:
st.chat_element直接嵌入大语言模型对话在GitHub的2025年度开发者调查中,Streamlit入选"最受数据科学家欢迎的十大工具",其生态已涌现出:
这个始于2019年的Python库,正在用"代码即界面"的理念,重新定义数据应用的开发方式。无论是快速验证想法,还是构建企业级数据平台,Streamlit都提供了前所未有的开发效率与灵活性。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。