Configs2026年4月12日·1 分钟阅读

Streamlit — Build Data Apps in Pure Python in Minutes

Streamlit is the fastest way to build and share data applications. Write a Python script with Streamlit commands and get an interactive web app with widgets, charts, and real-time updates — no frontend experience needed.

AI
AI Open Source · Community
快速使用

先拿来用,再决定要不要深挖

这里应该同时让用户和 Agent 知道第一步该复制什么、安装什么、落到哪里。

# Install Streamlit
pip install streamlit

# Create app.py
cat > app.py << 'PYEOF'
import streamlit as st
import pandas as pd
import numpy as np

st.title("My Data App")
data = pd.DataFrame(np.random.randn(100, 3), columns=["A", "B", "C"])
st.line_chart(data)
slider_val = st.slider("Filter rows", 0, 100, 50)
st.dataframe(data[:slider_val])
PYEOF

# Run the app
streamlit run app.py

Introduction

Streamlit turns Python scripts into interactive web applications. Instead of learning HTML, CSS, JavaScript, and a frontend framework, you just write Python code using Streamlit widgets. Every time you save the file, the app automatically refreshes. This makes it the go-to tool for data scientists, ML engineers, and analysts who want to share their work as interactive dashboards.

With over 44,000 GitHub stars and backing from Snowflake (acquired in 2022), Streamlit has become the standard for building data-focused web applications in Python.

What Streamlit Does

Streamlit takes a fundamentally different approach to web apps. Instead of the traditional request-response cycle, Streamlit reruns your entire Python script from top to bottom whenever a user interacts with a widget. This makes the programming model incredibly simple — your app is just a script that runs sequentially.

Architecture Overview

[Python Script (app.py)]
        |
   [Streamlit Runtime]
   Reruns script on each
   widget interaction
        |
+-------+-------+
|       |       |
[Widgets]  [Data]   [Layout]
st.slider  st.dataframe  st.columns
st.button  st.line_chart st.sidebar
st.text_input st.map    st.tabs
st.selectbox  st.metric st.expander
        |
   [React Frontend]
   Auto-generated UI
   with WebSocket sync
        |
   [Browser]
   localhost:8501

Self-Hosting & Configuration

# Full-featured Streamlit app
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 Dashboard")

# Sidebar filters
with st.sidebar:
    uploaded_file = st.file_uploader("Upload CSV", type="csv")
    date_range = st.date_input("Date Range", [])

if uploaded_file:
    df = pd.read_csv(uploaded_file)

    col1, col2, col3 = st.columns(3)
    col1.metric("Total Revenue", f"${df['revenue'].sum():,.0f}")
    col2.metric("Orders", f"{len(df):,}")
    col3.metric("Avg Order", f"${df['revenue'].mean():,.0f}")

    fig = px.bar(df.groupby("category")["revenue"].sum().reset_index(),
                 x="category", y="revenue", title="Revenue by Category")
    st.plotly_chart(fig, use_container_width=True)

    st.dataframe(df, use_container_width=True)
else:
    st.info("Upload a CSV file to get started.")
# Deploy to Streamlit Cloud (free)
# Push to GitHub, then connect at share.streamlit.io

# Self-hosted production
streamlit run app.py --server.port 8501 --server.address 0.0.0.0

Key Features

  • Pure Python — no HTML, CSS, or JavaScript needed
  • Instant Widgets — sliders, buttons, file uploaders, and more in one line
  • Auto-Refresh — app updates live when you save the source file
  • Data Display — native support for DataFrames, charts, maps, and metrics
  • Caching — @st.cache_data and @st.cache_resource for performance
  • Multi-Page Apps — file-based routing with pages/ directory
  • Session State — maintain state across reruns with st.session_state
  • Free Cloud Deploy — share apps via Streamlit Community Cloud

Comparison with Similar Tools

Feature Streamlit Gradio Dash Panel Shiny (Python)
Primary Use Data apps ML demos Dashboards Dashboards Data apps
Learning Curve Very Low Very Low Moderate Moderate Low
UI Customization Limited Limited High (CSS) High Moderate
Layout Control Basic Auto Full (Flex) Full Moderate
ML Integration Good Excellent Good Good Good
Free Hosting Yes (Cloud) Yes (Spaces) No No Yes (shinyapps)
Enterprise Snowflake HuggingFace Plotly Anaconda Posit

FAQ

Q: Streamlit vs Gradio — which should I use? A: Gradio is better for ML model demos and quick interfaces for model inputs/outputs. Streamlit is better for data dashboards, analytics apps, and multi-page applications with complex layouts.

Q: Can Streamlit handle production workloads? A: Streamlit is designed for internal tools, dashboards, and data apps. For high-traffic public-facing applications, consider a traditional web framework. Snowflake offers enterprise Streamlit hosting.

Q: How do I handle heavy computations? A: Use @st.cache_data to cache expensive computations and @st.cache_resource for database connections. These decorators prevent recomputation across reruns and users.

Q: Can I customize the look and feel? A: Streamlit supports theming via .streamlit/config.toml, custom CSS via st.markdown with unsafe_allow_html, and custom components written in React. However, deep UI customization is limited by design.

Sources

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产