New Component: Streamlit-Cookies-Controller

Hello when reloading a page the cookie resets. I was wondering if there is any way to fix this?

1 Like

Having the same issueā€¦ hoping someone can chime in here.

1 Like

Very useful, thank you!

When streamlit is deployed on a K8 pod (access via route) cookies are shared between sessionsā€¦
Does this means the cookies are kept on server side ?

Hi @Nathan_Chen! Nice component :slight_smile:

I was wondering how you actually access the browsers cookies with the component :thinking: I saw that you wrap the CookieController class around st.session_state.

I recently went with a similar approach and overwrote the classā€™ dunder methods to make state easier to access. I added a typed item getter to ensure fail safety for items that are not available in session_state. Would love to get your feedback on this:

class StateController(object):
    """Usage: 
    Instantiate controller: 
        state = StateController()
    Set a value: 
        state['str_user_guid'] = '00000000-0000-0000-0000-000000000000'
        state['bool_user_logged_in'] = True
        state['dict_user_details'] = {"name": "John"}
        data = st.file_uploader('Upload Excel File', type='xlsx')
        if data:
            state['df_excel_upload'] = pd.read_excel(data)
    Get a value: 
        user_guid = state.str_user_guid
        state.bool_user_logged_in:
            st.write(f'Welcome {state.dict_user_details.get("name")}!')
        if not state.df_excel_upload.empty:
            df = (
                state.df_excel_upload
                .pipe(transform)
                )
    Delete a value: 
        if st.button('Logout'): 
            state.pop('str_user_guid')
            state.pop('bool_user_logged_in')
            state.pop('dict_user_details')
    """

    def __getattr__(self, item: str):
        return self.typed_getter(item)

    def __setattr__(self, item: str, value: Any):
        st.session_state[item] = value

    def __setitem__(self, item: str, value: Any):
        st.session_state[item] = value

    def __getitem__(self, item: str):
        return self.typed_getter(item)

    def to_dict(self):
        return st.session_state

    def pop(self, item: str):
        """only use for deletion"""
        return st.session_state.pop(item, None)
        
    def typed_getter(self, item: str):
        """Itemgetter from session_state with simple protocol for default values.
        First part of key string (item) indicates the datatype of item. 
        Defaults to a falsey value when not present in session_state.

        Args:
            item (str): key of the item to fetch from session_state

        Returns:
            Any: The value of the requested item in session_state, defaulted according to its datatype.
        """
        dtype, _ = item.split('_', maxsplit=1)
        if dtype == 'series':
            return st.session_state.get(item, pd.Series())
        if dtype == 'df':
            return st.session_state.get(item, pd.DataFrame())
        if dtype == 'bool':
            return st.session_state.get(item, False)
        if dtype == 'int':
            return st.session_state.get(item, 0)
        if dtype == 'float':
            return st.session_state.get(item, 0.0)
        if dtype == 'str':
            return st.session_state.get(item, None)
        if dtype == 'dict':
            return st.session_state.get(item, dict())
        else:
            return st.session_state.get(item, None)

Cheers
Mo

1 Like

I cannot remove the cookie.
I set user after login success in login page.

controller = CookieController()
controller.set('user', user['sAMAccountName'])

On mainpage:

if st.sidebar.button("logout"):
            controller.remove('user')
            controller.refresh()

The cookie user is still available even after reloading page.
and it show the error on server :
streamlit.errors.StreamlitAPIException: st.session_state.cookiescannot be modified after the widget with keycookies is instantiated
Can anyone help me for this?

2 Likes

Cookies are sill present and can be seen in the developer tool of the browser.
Any solution to this?

Did you find any solution?

same here!

This is not working - the cookie resets / does not persist in browser
Also this is just a copy of the cookie manager in extra_streamlit_components, isnā€™t it?