Caching and state
優化性能并為應用程序添加狀態!
Caching
緩存
Streamlit 為數據和全局資源提供了強大的緩存原語。即使從網絡加載數據、處理大型數據集或執行昂貴的計算,它們也能讓您的應用程序保持高性能。
本頁僅包含有關 st.cache_data API 的信息。如需深入了解緩存及其使用方法,請查閱緩存。
st.cache_data
裝飾器,用于緩存返回數據的函數(如數據幀轉換、數據庫查詢、ML 推斷)。
緩存對象以 "腌制 "形式存儲,這意味著緩存函數的返回值必須是可腌制的。緩存函數的每個調用者都會獲得自己的緩存數據副本。
您可以使用 func.clear() 清除函數的緩存,或使用 st.cache_data.clear() 清除整個緩存。
要緩存全局資源,請使用 st.cache_resource。有關緩存的更多信息,請訪問 https://docs.streamlit.io/develop/concepts/architecture/caching。
Function signature[source] | |
---|---|
st.cache_data(func=None, *, ttl, max_entries, show_spinner, persist, experimental_allow_widgets, hash_funcs=None) | |
Parameters | |
func (callable) | The function to cache. Streamlit hashes the function's source code. |
ttl (float, timedelta, str, or None) | The maximum time to keep an entry in the cache. Can be one of:
Note that ttl will be ignored if persist="disk" or persist=True. |
max_entries (int or None) | The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. |
show_spinner (bool or str) | Enable the spinner. Default is True to show a spinner when there is a "cache miss" and the cached data is being created. If string, value of show_spinner param will be used for spinner text. |
persist ("disk", bool, or None) | Optional location to persist cached data to. Passing "disk" (or True) will persist the cached data to the local disk. None (or False) will disable persistence. The default is None. |
experimental_allow_widgets (bool) | delete experimental_allow_widgets is deprecated and will be removed in a later version. Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. |
hash_funcs (dict or None) | Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. |
代碼
import streamlit as st@st.cache_data
def fetch_and_clean_data(url):# 從 URL 獲取數據,然后進行清理。return datad1 = fetch_and_clean_data(DATA_URL_1)
# 實際上執行函數,因為這是第一次遇到它。d2 = fetch_and_clean_data(DATA_URL_1)
# 不執行函數。而是返回之前計算的值。這意味著現在 d1 中的數據與 d2 中的數據相同。d3 = fetch_and_clean_data(DATA_URL_2)
# 這是一個不同的 URL,因此函數會執行。
這段代碼是使用streamlit庫來創建一個web應用程序。代碼中定義了一個名為fetch_and_clean_data的函數,用于從指定的URL獲取數據并進行清理處理。在函數上使用了@st.cache_data裝飾器,表示對函數的結果進行緩存,以便在后續調用時可以直接返回之前計算的數值,而不必重新執行函數。
接下來,代碼分別使用fetch_and_clean_data函數來獲取和清理兩個不同的URL所對應的數據。在第一次調用fetch_and_clean_data時,函數會執行并返回結果,并將結果緩存起來。在后續對相同URL的調用中,函數不會重新執行,而是直接返回之前緩存的結果。當傳入不同的URL時,函數會重新執行以獲取新的數據。
總之,這段代碼展示了如何使用streamlit庫來創建一個具有數據緩存功能的web應用程序,并在多次調用同一個函數時避免重復執行。
設置持續參數的命令如下:
import streamlit as st@st.cache_data(persist="disk")
def fetch_and_clean_data(url):# 從 URL 獲取數據,然后進行清理。return data
這段代碼使用了Streamlit庫,并定義了一個名為fetch_and_clean_data的函數,使用了@st.cache_data(persist="disk")裝飾器。這表示該函數的結果將被緩存,并且可以選擇將緩存持久化到磁盤上。
函數的作用是從指定的URL獲取數據,然后對數據進行清理和處理,最后返回處理后的數據。在實際調用該函數時,如果輸入的URL相同,函數將直接返回緩存中的結果,而不是重新執行獲取和清理數據的操作。
默認情況下,緩存函數的所有參數都必須是散列的。任何名稱以 _ 開頭的參數都不會被散列。對于不可散列的參數,可以將其作為 "逃生艙口":
import streamlit as st@st.cache_data
def fetch_and_clean_data(_db_connection, num_rows):# 從 URL 獲取數據,然后進行清理。return dataconnection = make_database_connection()
d1 = fetch_and_clean_data(connection, num_rows=10)
# 實際執行該函數,因為這是第一次遇到該函數。another_connection = make_database_connection()
d2 = fetch_and_clean_data(another_connection, num_rows=10)
# 不執行函數。相反,即使兩次調用中的 _database_connection 參數不同,也會返回先前計算出的值。
這段代碼是使用Streamlit框架進行數據緩存的示例。在這段代碼中,使用了`@st.cache_data`裝飾器來緩存`fetch_and_clean_data`函數的結果,以便在后續調用中重復使用已經計算過的數值。
首先,通過`make_database_connection`函數建立了一個數據庫連接`connection`,然后調用`fetch_and_clean_data`函數,并傳入`connection`和`num_rows=10`作為參數。由于這是第一次調用該函數,因此實際執行了函數并返回了數據`d1`。
接著,又建立了另一個數據庫連接`another_connection`,然后再次調用`fetch_and_clean_data`函數,并傳入`another_connection`和`num_rows=10`作為參數。由于該函數的結果已經被緩存,所以這次并沒有執行函數,而是直接返回之前計算過的數值,賦值給了`d2`。
這樣,通過數據緩存,可以避免重復執行耗時的數據獲取和清理操作,提高程序的運行效率。
緩存函數的緩存可按程序清除:
import streamlit as st@st.cache_data
def fetch_and_clean_data(_db_connection, num_rows):# 從 _db_connection 抓取數據,然后將其清理干凈。return datafetch_and_clean_data.clear(_db_connection, 50)
# 清除所提供參數的緩存條目。fetch_and_clean_data.clear()
# 清除該函數的所有緩存條目。
這段代碼是使用Streamlit庫來清除緩存數據的示例。首先,使用`@st.cache_data`裝飾器來定義一個函數`fetch_and_clean_data`,該函數可以從數據庫連接中獲取數據并進行清理,然后返回處理后的數據。
接下來,使用`fetch_and_clean_data.clear(_db_connection, 50)`來清除使用指定參數調用函數時緩存的數據條目。這將清除使用給定數據庫連接和行數調用函數時緩存的數據。
然后,使用`fetch_and_clean_data.clear()`來清除該函數的所有緩存條目,而不考慮調用時使用的參數。
這段代碼展示了如何使用Strea