Session State for Streamlit 🎈

My example application for a secure Hydralit multi-page app has a login form at the front door. You can see the login page code by expanding the “Show App Code” expander on the page. Can also see the host application code by expanding using “Show Host Code”. The entire example code is located here.

Hydralit-secure-example

3 Likes

Thanks for sharing, this is cool stuff! :smiley:
I’ve just got my login example to work except I have to press submit one more time after successful login to get rid of the login page.
Actually thought of using the time.sleep after successful login as well to show the success message before refreshing.
How did you implement the self.do_redirect() function(what does it do underneath)? I can’t see if it’s a Hydralit specific function or a Streamlit one.

It’s a Hydralit function that comes from the HydraHeadApp template class. The simple version of what it does is, set session state variable to the target app, then run st.experimental_rerun().

2 Likes

Awesome! The st.experimental_rerun() function was all I needed to get my idea working! Thanks a lot :smiley: Session state and the rerun function work great together.

Hydralit looks lit :fire: by the way, I’ll definitely play around with it.
I’m trying to find a way to call the Web Share API on button click to easily share Streamlit app data on mobile(to Telegram or Whatsapp for instance), any chance that’s already implemented in Hydralit?

1 Like

Would you mind showing how you are using st.experimental_rerun() in your case?

I am trying to use it, but keeps re-runnig endlessly. :thinking: :thinking:

Of course! It took me a while to figure out so I want to help others save that time :smiley:

I have a login form like this where on submit it uses the time module(import time) with time.sleep(1) to give the st.success message some time to show before it reloads:

with st.form(key='login_form'):
        if "username" not in st.session_state:
            email = st.text_input("Username or e-mail")
            password = st.text_input("Password", type="password")
        submit_button = st.form_submit_button(label="Submit")

    if submit_button:
        if email.lower() in users and users[email.lower()] == password:
            st.success("Succesfully logged in! :tada:")
            st.session_state.logged_in = True
            with st.spinner("Redirecting to application..."):
                    time.sleep(1)
                    st.experimental_rerun()

As you can see I set the logged_in state to True on successful user/pass combination which it checks for in the rest of my application when setting the radio button options for navigation and such.
I log a timestamp in my db on login as well so I can set the session state logged_in to False again after X time when using some function in the app.

1 Like

Has anyone found that they can’t use the debugger in their streamlit code anymore once they use the native state management? Now whenever I use the debugger, it’s as if it can’t store any data in the st.session_state object.

When I run the app, the code runs fine. However when I use my debugger in pycharm, I can’t get past the first line that accesses the st.session_state call because the “dictionary” is empty.

See this example:

print(st.session_state)
{}
st.session_state['foo'] = 'bar'
st.session_state['foo']
Traceback (most recent call last):
  File "/opt/anaconda3/envs/yogen2/lib/python3.7/site-packages/streamlit/state/session_state.py", line 381, in __getitem__
    return self._getitem(widget_id, key)
  File "/opt/anaconda3/envs/yogen2/lib/python3.7/site-packages/streamlit/state/session_state.py", line 424, in _getitem
    raise KeyError
KeyError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/opt/anaconda3/envs/yogen2/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3457, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-9404e5a9ae15>", line 1, in <module>
    st.session_state['foo']
  File "/opt/anaconda3/envs/yogen2/lib/python3.7/site-packages/streamlit/state/session_state.py", line 666, in __getitem__
    return state[key]
  File "/opt/anaconda3/envs/yogen2/lib/python3.7/site-packages/streamlit/state/session_state.py", line 383, in __getitem__
    raise KeyError(_missing_key_error_message(key))
KeyError: 'st.session_state has no key "foo". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization'
print(st.session_state)
{}

anyone know the answer to this or have workarounds? surely I’m not the only one

It seems like you never initialized “foo”. The docs give the following example:

# Initialization
if 'key' not in st.session_state:
    st.session_state['key'] = 'value'

Looks like you may just be missing that if statement line. Hope that helps!

Hey @Probability. Love the Hydralit component. In the hydralit-example, the GIF shows how one can login and logout from the page. I tried implementing the login followed by redirection to the home page.

However, the Login tab appears again in the Hydralit parent page and gives me an error :
:sob: Error triggered from app: Logout
Details: ‘Logout’

Also, does hydralit keep a user logged in permanently until a logout button is displayed?

How can I resolve this issue?