Cache data

hi,
i have a multi pages Streamlit app. I would like to have variable that are globals ie that are defined in a page and known everywhere.
How to define this type of variable ?
How to get its value in other pages ?
How to test if the variable is defined ?

Just to finish my variable could be a variable or a dataframe

Thx

Hi,
It sounds like session state may work for you.

I am going to verify if it’s that what I was looking for.
One more question :
Is it possible if the variable has not been loaded in the page, to force the app to go to the page where it will be loaded.
I mean, imagine that, I load my data in page call page1 and if the user open the app and directly goes to page2, I suppose that I will get an error message. How to tell streamlit that the user should go to page1 and launch this page.
Thx.

Cordialement

Ah yes I think this is possible with streamlit extras:

https://extras.streamlit.app/Switch%20page%20function

I am sorry but I could not find the example that answers to my question. Maybe can you be more precise in your answer ?
Thx

Cordialement

Sure!

For example, as you said, if the user goes straight to page 2 but the variable 'my_variable" has not been loaded into session state yet, send them to page 1:

from streamlit_extras.switch_page_button import switch_page

if 'my_variable' not in st.session_state:
    switch_page("page_1")

i have a little problem with st.session_state in a multipage app.
I create a page with parameters value which I store inside a “global variable” by using (for example):

selected_indices = st.multiselect(“Choix de l’indice”,
[‘indice1’, ‘indice2’, ‘indice3’],
)
st.session_state[‘selected_indices’] = selected_indices

the selected_indices existed when I change once a page but when I rechange my page, it is no longer found…
Second question how to rememorize my previous choice in my parameter page each time I change page in my app ?
I hope you understand my problem and you could help me.

Hi @Jacques2101, there is a common issue with widgets and multipage apps. Normally widget state is preserved (e.g. if you click a checkbox it stays clicked), but if the widgets are removed from the page (e.g. if you switch pages) their values are lost. There is an easy workaround which is to stick this at the top of every page in your app.

for k, v in st.session_state.items():
    st.session_state[k] = v

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