Simple example of persistence, and waiting for input

So, as this has come up a few times, here is a really simple example of using a persistent object, between runs, as well as waiting for data entry to be complete before submitting.

This happens to use a persistent list, but you could use any mutable data structure.

import streamlit as st

#create cache object for the "chat"
@st.cache(allow_output_mutation=True)
def Chat():
    return []

chat=Chat()
name = st.sidebar.text_input("Name")
message = st.sidebar.text_area("Message")
if st.sidebar.button("Post chat message"):
    chat.append((name,message))

if len(chat) > 10:
    del(chat[0])

try:
    names, messages = zip(*chat)
    chat1 = dict(Name = names, Message =  messages)
    st.table(chat1)
except ValueError:
    st.title("Enter your name and message into the sidebar, and post!")
5 Likes

Hey @madflier, thanks for sharing this! :slight_smile:

This is a very helpful example, another way of doing this is using @tvst’s SessionState gist

import streamlit as st
import SessionState


state = SessionState.get(chat_list=[])

name = st.sidebar.text_input("Name")
message = st.sidebar.text_area("Message")
if st.sidebar.button("Post chat message"):
    state.chat_list.append((name, message))

if len(state.chat_list) > 10:
    del (state.chat_list[0])

try:
    names, messages = zip(*state.chat_list)
    chat1 = dict(Name=names, Message=messages)
    st.table(chat1)
except ValueError:
    st.title("Enter your name and message into the sidebar, and post!")
2 Likes

Very true. However, this does involve importing a whole new module - my version is literally three lines of code, and makes it pretty clear what’s happening.

The other (dis)advantage about using the SessionState gist is that I think the state may only be shared by the current user.

Using the version I’ve posted, all users connecting to the server see the same object, (which may well not be what you want, but is certainly vital for the “Chat server”!)

1 Like

it is very easy realization to keep the state. Thanks for sharing. It solved my problem.

Hello @fanraul,

Glad that it solves your problem!
Beware though, with this method anyone can clear streamlit cache, and therefore any stored state.