Is there a way to get data cache in multi page app

Hi, my question is simple. I would like to load data in an app with multi page and that tis DataFrame will be available in others pages.

in a page, I would like to have:

@st.cache_data
def load_data():
     df1 = pd.read_parquet('df1.parquet')
     df2 = pd.read_parquet('df2.parquet')
     df3 = pd.read_parquet('df3.parquet')
     df4 = pd.read_parquet('df4.parquet')
     return df1, df2, df3, df4

df1, df2, df3, df4 = load_data()

and in other page that these data will be available without running again load_data()

How should I do ?
Thxs.

Hi @Jacques2101

Have you lookined into using session state where you can assign your data to the session state variable.

Here are the Docs page (which has several examples to spark your ideas) on this

And also here

Hope this helps!

To achieve this, you can use Streamlit’s session_state to store the loaded data and make it available across different pages of your multi-page app. Here’s an example of how you can structure your code:

import streamlit as st
import pandas as pd

# Define a function to load the data
@st.cache
def load_data():
    df1 = pd.read_parquet('df1.parquet')
    df2 = pd.read_parquet('df2.parquet')
    df3 = pd.read_parquet('df3.parquet')
    df4 = pd.read_parquet('df4.parquet')
    return df1, df2, df3, df4

# Define a function to set up session state
def setup_session_state():
    if 'loaded_data' not in st.session_state:
        st.session_state.loaded_data = load_data()

# Page 1: Load Data
def page_load_data():
    setup_session_state()

    df1, df2, df3, df4 = st.session_state.loaded_data

    # Use the loaded data in the rest of the page
    st.write("Page 1: Load Data")
    st.write("Data Frame 1", df1)
    st.write("Data Frame 2", df2)
    st.write("Data Frame 3", df3)
    st.write("Data Frame 4", df4)

# Page 2: Use Data
def page_use_data():
    setup_session_state()

    df1, df2, df3, df4 = st.session_state.loaded_data

    # Use the loaded data in the rest of the page
    st.write("Page 2: Use Data")
    st.write("Data Frame 1", df1)
    st.write("Data Frame 2", df2)
    st.write("Data Frame 3", df3)
    st.write("Data Frame 4", df4)

# Sidebar to switch between pages
page = st.sidebar.selectbox("Select a page", ("Load Data", "Use Data"))

# Display the selected page
if page == "Load Data":
    page_load_data()
elif page == "Use Data":
    page_use_data()

the data is loaded only once, and subsequent pages can access the loaded data from the st.session_state.loaded_data attribute without rerunning the data loading function.

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