Multi-page app with session state

Edit: Streamlit 0.84.0 has officially introduced session state. Go check it out: Session State for Streamlit :balloon:


Hello there :wave:

For a project I needed to build multi-page app with a settings page. As I’ve seen this topic requesting the feature, I decided to share the solution I came up with. It features a custom version of @thiago’s SessionState.

It still relies on hacks, but it should work in most cases. It was tested with Streamlit version 0.61.0 (and now 0.65).

Things you must be aware of before using it:

  • You must call state.sync() at the end of your app if you set a widget’s default value to a state variable. This function triggers a rerun if you store a new state value or update an already stored object. This is how I fix rollback issues when you interact with widgets bound to a state value. In my demo I call it at the end of main().

  • If you use state.sync(), you won’t be able to store objects that Streamlit cannot hash, just like when you use @st.cache and you get a UnhashableTypeError.

  • If I start to drag a slider, 1 second later the mouse is released, probably because of my rerun :man_shrugging:

streamlit-app-2020-05-27-12-05-97.webm

30 Likes

Thanks for this demo! So when calling _get_state, I can then just declare any input/data to store in the session state within any page function?

Hello @vnguyendc,

Exactly. To sum up how you can interact with the state object:

  • You can assign data like so : state.my_value = "my value"
  • Accessing an undefined value will return None instead of throwing an exception
  • You can initialize a value only once by using the state object as a function: `state(my_value=“init value”).

I’ll add a little bit more documentation to the gist later on.

2 Likes

One thing I want to do is preserve a pandas dataframe across pages, however I get this error when trying to store a dataframe in a session state:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Mainly due to the comparison being done in this line:

 if (item not in data or data[item] != value) and item not in self._item_rerun:

Any idea how to work around this?

2 Likes

Thanks for your feedback.

I’ve updated the session state implementation in the gist. Instead of doing a naive value comparison, I normalize them first using an internal streamlit function used in their caching system. Now, every object supported by st.cache should work fine.

I’ve also added the possibility to access state values like so : state["my_input"]. This can be useful when you need to assign values dynamically.

Tell me if it works better for you now.

3 Likes

Thanks a lot for this. This is very helpful. I’ll definitely provide more feedback as I continue to implement this code in the application I’m building.

1 Like

Hi Synode,

The session state implementation is working great so far. However, I was wondering if you would be able to implement something where all stored inputs could be reset after a certain action? for example for my application, if I upload a new dataset, I would like to have all inputs reset. I dont want the end user to have to refresh the page every time.

Hello @vnguyendc,

Thanks for your feedback!
I’ve updated the gist. Now you can use state.clear() to clear saved values.

1 Like

Wow @okld. This is an awesome implementation! :sunny:

Programmable state is on our roadmap (after custom components and one-click deploy), and this example will definitely provide inspiration. I can see better why you want to tie the state to a page.

We are not implementing (or even designing) yet, but we’d love to collaborate at some point. In particualr, I’d be curious to know if there are any features in Streamlit which would unblock progress on programmable state for you, or any other thoughts you have.

5 Likes

Hello @Adrien_Treuille,

Thanks for your message, and also to your team for this amazing framework!

I had some small ideas related to widgets’ key parameter, and I think it could possibly be useful in designing an easy-to-use session state, and bring even more interaction to Streamlit apps : Proposal for a more useful key parameter (feat. session state, RESTful app and HTTP query string)

4 Likes

How would I be able to create custom hash functions for specific objects? For example, I need to define a custom hash function for XGBRegressor in order to store in the state.

1 Like

That’s something I need to add, indeed. I’ll update the snippet in a few hours. After the modification you’ll be able to pass hash functions to _get_state({...}) in a dictionary as you do with @st.cache.

1 Like

I’ve updated the gist, you can now pass hash functions as described in my previous reply.

2 Likes

Thank you very helpful. Will give you feedback

Hi @okld I’ve started playing with this afternoon. This truly is an outstanding template that will benefit many, well done! :raised_hands:

Now, having pasted some of my code, I have the following issue:

UnboundLocalError: local variable 'st' referenced before assignment
Traceback:
File "c:\users\charly\desktop\multi-sessions-app\venv\lib\site-packages\streamlit\ScriptRunner.py", line 319, in _run_script
    exec(code, module.__dict__)
File "C:\Users\Charly\Desktop\Multi-sessions-app\st_demo_settings.py", line 400, in <module>
    main()
File "C:\Users\Charly\Desktop\Multi-sessions-app\st_demo_settings.py", line 22, in main
    pages[page](state)
File "C:\Users\Charly\Desktop\Multi-sessions-app\st_demo_settings.py", line 29, in cloud_nlp
    st.title(":chart_with_upwards_trend: Dashboard page")  

Would fixing the issue be as easy as re-arranging some blocks/functions within the code?

Thanks,
Charly

Hmm, maybe. It’s just weird that it’s related to st though. Could you share what you have so far?

2 Likes

Thanks @okld! I’ve sorted it :ok_hand:

I’ve now added 2 of my apps within the same app - SO thrilled by this!

Out of interest, is it possible to retain the state/results of these 2 added tabs?

Currently, if I trigger results in 1 tab, switch to another tab then come back, these results are gone. Not a deal breaker but it would be super nice to retain their states as well! :slight_smile:

Thanks,
Charly

3 Likes

If you’re using the page structure implemented in my gist, I pass to each page function a state object as argument into which you can retain any value you want.

I’ll update my post but you need to call that state.sync() function only if you’re binding a widget to a state value.

2 Likes

Great, I’ll have a play!

Would that also retain:

#1 - files uploaded via Streamlit’s file uploader?
#2 - modified dataframes?

Thanks,
Charly

1 Like

That should work, yes! That’s the main purpose of this gist actually, save some state across pages :wink:

2 Likes