Skip to content

建立 2026-09-14 更新 2026-09-14

快取

沒有快取時,每次拖滑桿都會重新讀檔、重查資料庫、重載模型。App 會變得很慢。Streamlit 提供兩個裝飾器,用途不同,不要混用。

cache_data:快取資料

適合回傳 DataFrame、dict、list、數字、API 結果。每次呼叫會拿到複本,比較安全。

import streamlit as st
import pandas as pd

@st.cache_data
def load_csv(path):
    return pd.read_csv(path)

df = load_csv("sales.csv")

參數變了才會重算。資料會過期時可加 ttl

@st.cache_data(ttl=300)
def get_live_data():
    return api.fetch()

cache_resource:快取連線與模型

適合資料庫連線、Hugging Face pipeline、scikit-learn 模型。回傳的是同一個物件,所有 session 共用。

@st.cache_resource
def get_model():
    from transformers import pipeline
    return pipeline("sentiment-analysis")

model = get_model()

若你改了這個物件,所有使用者都會看到改變。這正是連線池與模型要的行為,但不要拿它快取使用者自己的表單資料。

怎麼選?

回傳內容 用哪個
DataFrame、查詢結果、處理後的資料 @st.cache_data
DB 連線、ML 模型、客戶端物件 @st.cache_resource
不確定 先試 cache_data

官方進階說明:Advanced concepts