Suppose I have a data frame with all fancy widgets, dropdown, text input, slider etc. User can select different values on those widgets.
Is there a possible yet generic enough way to download all user’s current state on all those interactive widget into a JSON file or something? Our project requires us to save those user state and share it with another user. I have taken a look at SessionState https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92 , however this requires us to manually add all the widget values to the state, which might not be generic enough.
There isn’t a good way to do this in Streamlit, but it seems like the perfect job for a custom wrapper function.
For example, this make_recording_widget function wraps any st.widget and returns a new function that calls the original widget and also saves its current value to a global dictionary:
import streamlit as st
widget_values = {}
def make_recording_widget(f):
"""Return a function that wraps a streamlit widget and records the
widget's values to a global dictionary.
"""
def wrapper(label, *args, **kwargs):
widget_value = f(label, *args, **kwargs)
widget_values[label] = widget_value
return widget_value
return wrapper
button = make_recording_widget(st.button)
slider = make_recording_widget(st.slider)
checkbox = make_recording_widget(st.checkbox)
# ... create any other wrapped widgets you want
button("Recorded Button")
slider("Recorded Slider")
checkbox("Recorded Checkbox")
# All current widget values will be recorded in the widget_values dict.
# We print them here; they could also be serialized to JSON or whatever.
st.write("Recorded values: ", widget_values)
In this example, we’re just printing out all the widget values at the end of the script, but you could also serialize them to a JSON file, ship them off to a server, or what-have-you!
(Also note that if you have multiple widgets with the same label, you’ll need to come up with a different key to uniquely identify each widget; I’m just using label here for expediency sake, but internally, Streamlit uses a hash of all the values passed to each widget to uniquely identify that widget. Less fragile, but also much less readable by humans.)