Caching across pages in Multipage App

Summary

I want to run a piece of code in my Home page and then through caching, have that same code be accessible and preloaded in a page. Therefore, I only need to run the code once and caching will almost immediately return the value that I passed to the cached function. I want to use caching over session_state because I want the data to persist across sessions.

Steps to reproduce

Code snippet:

In Home.py:

import streamlit as st
from datetime import date, timedelta
import time


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


test = test_import_cache(5, 50)
st.write(test)

In page/sample.py:

import streamlit as st
from datetime import date, timedelta
import time
from Home import test_import_cache

test = test_import_cache(5, 50)
st.write(test)

If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

I expected the code in sample.py to run almost immedateily because it is cached after running Home.py first.

Actual behavior:
sample.py code executes the code for the full time it sleeps as if it were never cached

Debug info

  • Streamlit version: Streamlit, version 1.27.2
  • Python version: Python 3.11.3
  • Using conda, but this is local
  • OS version:
  • Browser version:

Requirements file

Using Conda? PipEnv? PyEnv? Pex? Share the contents of your requirements file here.
Not sure what a requirements file is? Check out this doc and add a requirements file to your app.

Links

  • Link to your GitHub repo:
  • Link to your deployed app:

Additional information

If needed, add any other context about the problem here.

Hi @Aaron_Ho

It seems you want the data to persist across pages in a multi-page app. Caching seems to make it run faster the second time when refreshing the same page. However, when switching to a new page, you’ll want to use session state to store data. More info in the Docs:

Hope this helps!

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

Thank you! This worked for me.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.