Streamlit and session variable - how do I create a session in one .py file and view it in another?

I am using streamlit and I call a function in a separate function file from a login script, the function.py queries SQL and loads a bunch of data in the st.session as follows:

st.session_state["company_id"] = company_id

Once the user has logged in , I want to reference that st.session_state[“company_id”] from the rest of my application in all the other .py files, I have tried to output st.session_state[“company_id”] and all I get is:
KeyError: 'st.session_state has no key “company_id”.Did you forget to initialize it?
I am running streamlit on local machine - python v3.11.5 / streamlit v1.28.0

There must be something else going on that is altering the session state, or the code that is setting company_id isn’t actually running. Here is an example of a main streamlit page, a sample1.py script that is imported, and a second page called pages/another_page.py

When I do streamlit run app37.py, I see 42, and when I switch to “another page”, I also see 42.

Can you show a simplified example of your code which shows you setting the session state variable and then not seeing it when you try to use it from another file?

So I have a login screen where I set the session state to “logged in”:

  if st.button("Login"):
        # Check login credentials
        # st.write(checklogin(username, password))
        
        if checklogin(username, password):
            st.success("Login successful! Redirecting to the Dashboard...")
            st.session_state["logged_in"] = True
            redirect_js = """<meta http-equiv="refresh" content="0;url=dashboard"> """
            st.markdown(redirect_js, unsafe_allow_html=True)

When it opens the redirect Dashboard screen, the session_state does not exist and gives the 'KeyError: 'st.session_state has no key “logged_in”. Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization’ message.

If I pass the same session variable from another test page and then go to the Dashboard, it works fine.

It looks to me like your JS is causing a browser refresh. A refresh kills the current session and starts a new one, so the session state is lost.

I would highly recommend just using st.switch_page rather than javascript to switch to a new page after login

1 Like

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