How to save and restore session so it persist after shutting down

python 3.11.3
Streamlit latest


enforceSerializableSessionState = true

I’ve been trying to use this

import os
import pickle

import streamlit as st

def save_session_state():
        with open('session_state.pkl', 'wb') as f:
            print("saving session_state", st.session_state)
            pickle.dump(st.session_state, f)
    except Exception as e:
        print("Error during saving session state:", e)

def load_session_state():
    if os.path.exists('session_state.pkl'):
            with open('session_state.pkl', 'rb') as f:
                loaded_state = pickle.load(f)
                print("Loaded session state:", loaded_state)
                return loaded_state
        except Exception as e:
            print("Error during loading session state:", e)
        print("session_state.pkl not found")
    return None

And load on my

loaded_state = load_session_state()
if loaded_state is not None:

First thing after page config

And adding save_session_state() at the bottom of every page.

But it doesn’t work, when it comes to load it’s empty…

What is the way to achieve state persistence across reboots?

I have the same issue so I would like to know if you managed to solve the issue (and eventually, how)?

Hello, I think this thread my serve you

Thank you for your quick response.

Following this thread, I got around the problem by using the dictionnary type. This is not very elegant but it seems to work with my example.

def save_session_state(file_path):
    with open(file_path, 'wb') as f:
            pickle.dump(st.session_state.to_dict(), f)

def load_session_state(file_path):
    if os.path.exists(file_path):
        with open(file_path, 'rb') as f:
                loaded_state = pickle.load(f)
                for k, v in loaded_state.items():
                    st.session_state[k] = v
        print("File not found.")