Created
August 8, 2023 01:08
-
-
Save sfc-gh-dmatthews/1771c909c13d224e4d45cf15196ddae9 to your computer and use it in GitHub Desktop.
Stateful Streamlit data editory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Put home.py in a working directory. Put page_1.py and page_2.py in a folder named pages. | |
import streamlit as st | |
import pandas as pd | |
def initialize(): | |
# the data | |
st.session_state.df1 = pd.DataFrame({'A':[1,2],'B':[3,4]}) | |
st.session_state.df2 = pd.DataFrame({'A':[1,2],'B':[3,4]}) | |
# the shadow data | |
st.session_state._df1 = pd.DataFrame({'A':[1,2],'B':[3,4]}) | |
st.session_state._df2 = pd.DataFrame({'A':[1,2],'B':[3,4]}) | |
def changed_page(page): | |
'Detect if the page was changed' | |
if st.session_state.get('page') == page: | |
return False | |
st.session_state.page = page # initialize or change | |
return True | |
def save(df_name): | |
'Overwrite data with shadow data' | |
st.session_state[df_name] = st.session_state['_'+df_name] | |
if 'df1' not in st.session_state: | |
initialize() | |
if changed_page('home'): | |
save('df1') | |
save('df2') | |
st.header('df1') | |
st.write(st.session_state.df1) | |
st.header('df2') | |
st.write(st.session_state.df2) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import streamlit as st | |
import pandas as pd | |
from home import initialize, changed_page, save | |
if 'df1' not in st.session_state: | |
initialize() | |
if changed_page('page1'): | |
save('df1') | |
save('df2') | |
st.session_state._df1 = st.data_editor(st.session_state.df1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import streamlit as st | |
import pandas as pd | |
from home import initialize, changed_page, save | |
if 'df1' not in st.session_state: | |
initialize() | |
if changed_page('page2'): | |
save('df1') | |
save('df2') | |
st.session_state._df2 = st.data_editor(st.session_state.df2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment