當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Streamlit st.cache用法及代碼示例

當您使用 Streamlit 的緩存注釋標記函數時,它會告訴 Streamlit 每當調用該函數時,它應該檢查三件事:

  1. 函數名稱
  2. 構成函數體的實際代碼
  3. 調用函數的輸入參數

如果這是 Streamlit 第一次看到這三個項目,具有這些確切的值,並且在那個確切的組合中,它會運行該函數並將結果存儲在本地緩存中。

然後,下次調用該函數時,如果這三個值沒有更改,Streamlit 知道它可以完全跳過執行該函數。相反,它隻是從本地緩存中讀取輸出並將其傳遞給調用者。

主要限製是 Streamlit 的緩存函數不知道發生在注釋函數主體之外的更改。

有關 Streamlit 緩存、其配置參數及其限製的更多信息,請參閱Caching

用於 memory 函數執行的函數裝飾器。

函數簽名

st.cache(func=None, persist=False, allow_output_mutation=False, show_spinner=True, suppress_st_warning=False, hash_funcs=None, max_entries=None, ttl=None)
參數說明

func (callable)

要緩存的函數。 Streamlit 散列函數和相關代碼。

persist (boolean)

是否將緩存持久化到磁盤上。

allow_output_mutation (boolean)

當返回值發生突變時,Streamlit 會顯示警告,因為這可能會產生意想不到的後果。這是通過在內部散列返回值來完成的。

如果您知道自己在做什麽並且想要覆蓋此警告,請將其設置為 True。

show_spinner (boolean)

啟用微調器。默認為 True 以在緩存未命中時顯示微調器。

suppress_st_warning (boolean)

禁止從緩存函數中調用 Streamlit 函數的警告。

hash_funcs (dict or None)

將類型或完全限定名稱映射到散列函數。這用於覆蓋 Streamlit 緩存機製中哈希器的行為:當哈希器遇到一個對象時,它將首先檢查其類型是否與此 dict 中的鍵匹配,如果是,將使用提供的函數生成一個哈希它。有關如何使用它的示例,請參見下文。

max_entries (int or None)

保留在緩存中的最大條目數,或 None 用於無界緩存。 (將新條目添加到完整緩存時,將刪除最舊的緩存條目。)默認值為無。

ttl (float or None)

將條目保留在緩存中的最大秒數,如果緩存條目不應過期,則為 None。默認值為無。

示例

@st.cache
 def fetch_and_clean_data(url):
     # Fetch data from URL here, and then clean it up.
     return data

d1 = fetch_and_clean_data(DATA_URL_1)
# Actually executes the function, since this is the first time it was
# encountered.

d2 = fetch_and_clean_data(DATA_URL_1)
# Does not execute the function. Instead, returns its previously computed
# value. This means that now the data in d1 is the same as in d2.

d3 = fetch_and_clean_data(DATA_URL_2)
# This is a different URL, so the function executes.

設置堅持參數,使用該命令如下:

@st.cache(persist=True)
 def fetch_and_clean_data(url):
     # Fetch data from URL here, and then clean it up.
     return data

要禁用散列返回值,請設置allow_output_mutation參數為True

@st.cache(allow_output_mutation=True)
 def fetch_and_clean_data(url):
     # Fetch data from URL here, and then clean it up.
     return data

要覆蓋默認散列行為,請傳遞自定義散列函數。您可以通過映射類型來做到這一點(例如MongoClient) 到哈希函數 (ID) 像這樣:

@st.cache(hash_funcs={MongoClient: id})
 def connect_to_database(url):
     return MongoClient(url)

或者,您可以映射類型的完全限定名稱(例如“pymongo.mongo_client.MongoClient”) 改為散列函數:

@st.cache(hash_funcs={"pymongo.mongo_client.MongoClient": id})
 def connect_to_database(url):
     return MongoClient(url)

相關用法


注:本文由純淨天空篩選整理自streamlit.io大神的英文原創作品 st.cache。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。