How can I make the application automatically load the historical input value of the component?

I tried to use buttons to store and load input values.The code is as follows:

import streamlit as st
import pickle

Load session state from local file

if st.button(“Load session state”):
with open(“saved_dictionary.pkl”, “rb”) as f:
session_state = pickle.load(f)
st.session_state.update(session_state)

col1, col2, col3 = st.columns(3)
with col1:
num1 = st.text_input(“num1”, key=“num1”)
with col2:
num2 = st.text_input(“num2”, key=“num2”)
with col3:
try:
st.write(“”)
st.write(“”)
st.write(“Sum: “, int(num1) + int(num2))
except:
st.write(””)
st.write(“”)
st.write(“Error”)

Save session_state to local file

if st.button(“Submit session state”):
with open(“saved_dictionary.pkl”, “wb”) as f:
pickle.dump(dict(st.session_state), f)

Is there any way for streamlit to automatically store and load user input? Thx :smile:

Can you format your code properly?

Also check our forum’s posting guide.

okey, thank you

import streamlit as st
import pickle


# Load session state from local file
if st.button("Load session state"):
    with open("saved_dictionary.pkl", "rb") as f:
        session_state = pickle.load(f)
    st.session_state.update(session_state)



col1, col2, col3 = st.columns(3)
with col1:
    num1 = st.text_input("num1", key="num1")
with col2:
    num2 = st.text_input("num2", key="num2")
with col3:
    try:
        st.write("")
        st.write("")
        st.write("Sum: ", int(num1) + int(num2))
    except:
        st.write("")
        st.write("")
        st.write("Error")


# Save session_state  to local file
if st.button("Submit session state"):
    with open("saved_dictionary.pkl", "wb") as f:
        pickle.dump(dict(st.session_state), f)

    st.write("num1: ", num1)
    st.write("num2: ", num2)

You can try this example. It uses a form to get user input and display result. Also Pickled data is read to pandas dataframe to easily manipulate it. It also uses a callback in the form button.

import streamlit as st
from streamlit import session_state as ss
import pickle
import pandas as pd
from datetime import datetime
    

DATA_FILE = 'data.pkl'


def save_data(file_name, value1, value2):
    try:
        with open(file_name, 'rb') as file:
            data = pickle.load(file)
    except (FileNotFoundError, EOFError):
        data = []

    data.append({'value1': value1, 'value2': value2, 'timestamp': datetime.now()})

    with open(file_name, 'wb') as file:
        pickle.dump(data, file)

        
def load_data(file_name):
    try:
        with open(file_name, 'rb') as file:
            data = pickle.load(file)
        return pd.DataFrame(data)
    except (FileNotFoundError, EOFError):
        return pd.DataFrame()


def sum_cb():
    ss.sum = str(int(ss.num1) + int(ss.num2))
    save_data(DATA_FILE, ss.num1, ss.num2)
    

with st.form('form', clear_on_submit=False):
    col1, col2, col3 = st.columns(3)
    with col1:
        st.text_input("num1", key="num1")
    with col2:
        st.text_input("num2", key="num2")
    with col3:
        st.text_input("sum", key="sum", disabled=True)
    st.form_submit_button('Get Result', on_click=sum_cb)
    
st.markdown('# Current Data')
df = load_data(DATA_FILE)
st.dataframe(df, use_container_width=True)

Output

st.form is so cool! It solved my problem perfectly!Thank you!

import streamlit as st
from streamlit import session_state as ss
import pickle
import pandas as pd
from datetime import datetime
    

def save_data(file_name, value1, value2):
    try:
        with open(file_name, 'rb') as file:
            data = pickle.load(file)
    except (FileNotFoundError, EOFError):
        data = []

    data.append({'value1': value1, 'value2': value2, 'timestamp': datetime.now()})

    with open(file_name, 'wb') as file:
        pickle.dump(data, file)
        
def load_data(file_name):
    try:
        with open(file_name, 'rb') as file:
            data = pickle.load(file)
        return pd.DataFrame(data)
    except (FileNotFoundError, EOFError):
        return pd.DataFrame()

# Don't need reinput data when refresh page!
df = load_data('data.pkl')
pre_value1 = df['value1'].iloc[-1] if len(df) > 0 else ''
pre_value2 = df['value2'].iloc[-1] if len(df) > 0 else ''
pre_timestamp = df['timestamp'].iloc[-1] if len(df) > 0 else ''
st.code(f'Last time updated: {pre_timestamp}, num1: {pre_value1}, num2: {pre_value2}')

# Load data from old session
ss.num1 = st.session_state.num1 if 'num1' in st.session_state else pre_value1
ss.num2 = st.session_state.num2 if 'num2' in st.session_state else pre_value2

def sum_cb():
    ss.sum = str(int(ss.num1) + int(ss.num2))
    save_data('data.pkl', ss.num1, ss.num2)
    
# If I don't click the button, the value will be the last time I input
with st.form('form', clear_on_submit=False):
    col1, col2, col3 = st.columns(3)
    with col1:
        st.text_input("num1", key="num1")
    with col2:
        st.text_input("num2", key="num2")
    with col3:
        st.text_input("sum", key="sum", disabled=True)
    st.form_submit_button('Get Result', on_click=sum_cb)
    

Please let me show you!

RES_GIF

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