st.cache - 函数缓存装饰器
streamlit的cache
装饰器用于记忆函数的历史执行。
方法原型
streamlit.cache(func=None, persist=False, allow_output_mutation=False, show_spinner=True, suppress_st_warning=False, **kwargs)
参数:
- func:要缓存的函数
- persist :是否缓存到磁盘,布尔值
- allow_output_mutation:是否允许修改输出,布尔值
- show_spinner:是否显示执行状态,布尔值
- suppress_st_warning:是否抑制警告信息输出,布尔值
示例代码
>>> @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. Just 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.
下面的代码设置persist参数:
>>> @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