Caching across pages in Multipage App

I think I found a way to give you the best of both worlds – using st.cache_resource so that it will persist across sessions PLUS using st.session_state to persist across pages within a single session.

It’s a bit hacky, but it does the trick.

import streamlit as st
import time


@st.cache_resource
def _test_import_cache(a, b):
    time.sleep(10)
    print("finished import")
    return a * b


def test_import_cache(a, b):
    key = f"import_cache_{a}_{b}"
    if key not in st.session_state:
        st.session_state[key] = _test_import_cache(a, b)
    return st.session_state[key]


test = test_import_cache(5, 50)
1 Like