系列参考: python︱写markdown一样写网页,代码快速生成web工具:streamlit介绍(一) python︱写markdown一样写网页,代码快速生成web工具:streamlit 重要组件介绍(二) python︱写markdown一样写网页,代码快速生成web工具:streamlit 展示组件(三) python︱写markdown一样写网页,代码快速生成web工具:streamlit lay-out布局(四) python︱写markdown一样写网页,代码快速生成web工具:streamlit 缓存(五) python︱写markdown一样写网页,代码快速生成web工具:streamlit 数据探索案例(六) streamlit opencv/YOLOv3 快速构建自己的图像目标检测demo网页(七)
github代码链接:mattzheng/streamlit_demo
文章目录
- 1 不适用cache的方式
- 2 cache
- 3 cache 可选项
- 4 cache 返回字典型
整个文档可参考:https://docs.streamlit.io/en/stable/caching.html
当您用@st标记一个函数时。缓存装饰器,它告诉Streamlit无论何时调用函数都需要检查以下几件事:
- The input parameters that you called the function with
- The value of any external variable used in the function
- The body of the function
- The body of any function used inside the cached function
cache在后台操作的步骤为:
代码语言:javascript复制For example, when the function expensive_computation(a, b), decorated with @st.cache, is executed with a=2 and b=21, Streamlit does the following:
1 Computes the cache key
2 If the key is found in the cache, then:
- Extracts the previously-cached (output, output_hash) tuple.
- Performs an Output Mutation Check, where a fresh hash of the output is computed and compared to the stored output_hash.
- If the two hashes are different, shows a Cached Object Mutated warning. (Note: Setting allow_output_mutation=True disables this step).
3 If the input key is not found in the cache, then:
- Executes the cached function (i.e. output = expensive_computation(2, 21)).
- Calculates the output_hash from the function’s output.
- Stores key → (output, output_hash) in the cache.
4 Returns the output.
1 不适用cache的方式
比如求指数,如果不缓存,重新刷新一次还是需要重新计算
代码语言:javascript复制import streamlit as st
import time
def expensive_computation(a, b):
time.sleep(2) #