How to save stuff *on disconnect*?

Hi everyone!

TLDR:
I’m looking for a way to save some items from st.session_state when a session is closed.

The long story:
I’m building an app, that reads from and writes to a database. Users are shown data and based on that data, create their inputs. They then save these inputs, by clicking a button, back to the database. Since the input decisions are numerous and difficult, users will spend literal hours in this app. Some users (often due to bad WiFi) experienced disconnects from their VPN or internet connection. Depending on their last save, they can lose quite a lot of work. I do not, however, want to automatically save their progress every X minutes, because the data transfer takes a few seconds and thus disrupts the user experience.
What I would love is a way of detecting the event of a user disconnecting and that to trigger saving the current progress. Is there a way to achieve that? I’d be happy with a proxy like tracking time since last input…

Thanks and have a nice day :slight_smile:

my solution so far:

  • Use a timer from the threading module. There is a problem with getting the context right when creating a thread from a streamlit script, but luckily a workaround is available here: Improve "missing ReportContext" threading error · Issue #1326 · streamlit/streamlit · GitHub
  • Unfortunately, the threading.Timer cannot be restarted. Thus, on each rerun, I cancel the current timer and create a new one.
  • That seems to work, even when the user deliberately closes the window.
1 Like

There’s the new streamlit fragment where you can set the function that saves the data to rerun every x second

1 Like

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