Best practice to save and load widget state from file? (Multi page app)

Summary

I’d like to save the current values of all input widgets across my pages to a json file to allow users to export their inputs.

Similar to that I want to set all values of input widgets using the exported json file.

According to the docs the widget state is automatically written into st.session_state which only seems to work for one page at a time and not for multi page apps where some pages haven’t even been rendered yet.

Is there a recommended workaround?

Thanks!

Steps to reproduce

Code within the landing page:

"""Dashboard Landing Page."""

import streamlit as st
import time
import json

# Write session state to dict
widget_values = {}
for key in st.session_state:
    widget_values[key] = st.session_state[key]
    
widget_values_json = json.dumps(widget_values)

st.write("## Session State:\n")
st.write(widget_values_json)

st.download_button("Save inputs to file", widget_values_json, file_name=time.strftime("%Y%m%d-%H%M%S")+".json", key="dl")

uploaded_file = st.file_uploader("Load inputs from file", type="json", accept_multiple_files=False, key="ul")
if uploaded_file is not None:
    widget_values = json.loads(uploaded_file.getvalue())
    st.write(widget_values)

In app page:

"""App page"""
import streamlit as st

for k, v in st.session_state.items():
    st.session_state[k] = v

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