1 2 Persisting State Explained
Key Concepts
- Session State: Temporary storage that persists across reruns within a single session.
- Global State: Persistent storage that retains data across multiple sessions.
- st.session_state: A Streamlit object used to manage session state.
- st.experimental_get_query_params: A function to retrieve query parameters from the URL.
Session State
Session state in Streamlit is temporary storage that persists across reruns within a single session. This means that the data stored in session state will be available as long as the user is interacting with the application within the same browser tab.
Example:
import streamlit as st if 'counter' not in st.session_state: st.session_state.counter = 0 st.session_state.counter += 1 st.write(f"Counter: {st.session_state.counter}")
Global State
Global state in Streamlit is persistent storage that retains data across multiple sessions. This means that the data stored in global state will be available even if the user closes the browser tab and revisits the application later.
Example:
import streamlit as st import json def save_state(state): with open('state.json', 'w') as f: json.dump(state, f) def load_state(): try: with open('state.json', 'r') as f: return json.load(f) except FileNotFoundError: return {} state = load_state() state['counter'] = state.get('counter', 0) + 1 save_state(state) st.write(f"Counter: {state['counter']}")
st.session_state
st.session_state
is a Streamlit object used to manage session state. It allows you to store and retrieve data that persists across reruns within a single session.
Example:
import streamlit as st if 'username' not in st.session_state: st.session_state.username = st.text_input("Enter your username") st.write(f"Welcome, {st.session_state.username}!")
st.experimental_get_query_params
st.experimental_get_query_params
is a function to retrieve query parameters from the URL. This can be used to pass state between different pages or components within a Streamlit application.
Example:
import streamlit as st params = st.experimental_get_query_params() username = params.get('username', [''])[0] st.write(f"Welcome, {username}!")
Analogies
Think of session state as a sticky note on your desk that you write on and refer to while working on a project. The note is only useful during your current work session and is discarded once you finish. Global state, on the other hand, is like a permanent record in a ledger that you can refer to even after you've finished your work and come back later.
By mastering the concept of persisting state in Streamlit, you can create more interactive and user-friendly applications that retain important information across different interactions and sessions.