Some code for cookie-based session management

So. After searching everywhere, I found a way to create a standard web-app style session in Streamlit using the extra-streamlit-components package’s CookieManager as a bridge between st.session_state

NOTE: It works with any data that can be json encoded

First, create a folder called /sessions in the document root. This is where the session json files will be stored

Full Code here - session.py

import extra_streamlit_components as stx
import streamlit as st
from json import dumps, loads
import os

class Session:
cookie_manager = None
session_id = None
session_vars =

@staticmethod
def init():

    Session.cookie_manager = stx.CookieManager()
    cookies = Session.cookie_manager.get_all()

    if 'ajs_anonymous_id' in cookies:
        Session.session_id = cookies['ajs_anonymous_id']
        Session.get_user_session()

    
@staticmethod
def get_user_session():
    session_file = os.getcwd() + '/sessions/' + Session.session_id + '.json'
    if os.path.exists(session_file):
        with open(session_file) as json_file:
            data = loads(json_file.read())
            for i in data:
                st.session_state[i] = data[i]
        
@staticmethod
def append_value(key, value):
    if key not in st.session_state:
        st.session_state[key] = []

    st.session_state[key].append(value)

@staticmethod
def set_value(key, value):
    Session.session_vars.append(key)
    Session.session_vars = list(set(Session.session_vars))
    st.session_state[key] = value
    Session.save()


@staticmethod
def get_value(key):
    return st.session_state[key] if key in st.session_state else None

@staticmethod
def save():
    data = {}
    for i in Session.session_vars:
        if i not in st.session_state:
            continue
        data[i] = st.session_state[i]

    session_file = os.getcwd() + '/sessions/' + Session.session_id + '.json'
    with open(session_file, 'w') as outfile:
        outfile.write(dumps(data))

Usage is straightforward.

At the beginning of the app, you need to do

from session import Session

Session.init()

This will initialize the session.

After that, instead of using st.session_state, use the following helper functions

Session.set_value(key, value)
Session.get_value(key)

Essentially, with Session.init(), it will load the JSON file into session_state

Every time you set a session value, it will write contents to the session file for persistence.

This may seem hacky, but didn’t find of another way to create an easy interface for persistent session variable management.

If your app uses a session variable to track its state/progress, reloading the page will return it to the same state.

5 Likes

How are these cookies if we are saving the content to a folder in storage?

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