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


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

存儲單例對象的函數裝飾器。

每個單例對象都在連接到應用程序的所有用戶之間共享。單例對象must 是線程安全的,因為它們可以同時從多個線程訪問。

(如果線程安全是一個問題,請考慮使用st.session_state來存儲 per-session 單例對象。)

您可以使用 f.clear() 清除 memory 函數的緩存。

函數簽名

st.experimental_singleton(func=None, *, show_spinner=True, suppress_st_warning=False)
參數說明

func (callable)

創建單例的函數。 Streamlit 散列函數的源代碼。

show_spinner (boolean)

啟用微調器。默認為 True 以在存在 "cache miss" 並且正在創建單例時顯示微調器。

suppress_st_warning (boolean)

禁止從單例函數中調用 Streamlit 函數的警告。

示例

@st.experimental_singleton
 def get_database_session(url):
     # Create a database session object that points to the URL.
     return session

s1 = get_database_session(SESSION_URL_1)
# Actually executes the function, since this is the first time it was
# encountered.

s2 = get_database_session(SESSION_URL_1)
# Does not execute the function. Instead, returns its previously computed
# value. This means that now the connection object in s1 is the same as in s2.

s3 = get_database_session(SESSION_URL_2)
# This is a different URL, so the function executes.

默認情況下,單例函數的所有參數都必須是可散列的。任何名稱以開頭的參數_不會被散列。對於不可散列的參數,您可以將其用作"escape hatch":

@st.experimental_singleton
 def get_database_session(_sessionmaker, url):
     # Create a database connection object that points to the URL.
     return connection

s1 = get_database_session(create_sessionmaker(), DATA_URL_1)
# Actually executes the function, since this is the first time it was
# encountered.

s2 = get_database_session(create_sessionmaker(), DATA_URL_1)
# Does not execute the function. Instead, returns its previously computed
# value - even though the _sessionmaker parameter was different
# in both calls.

可以通過程序清除單例函數的緩存:

@st.experimental_singleton
 def get_database_session(_sessionmaker, url):
     # Create a database connection object that points to the URL.
     return connection

get_database_session.clear()
# Clear all cached entries for this function.

相關用法


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