- Spec files
pypi-streamlit
Describes: pkg:pypi/streamlit@1.50.x
- Description
- A faster way to build and share data apps
- Author
- tessl
- Last updated
state-management.md docs/
1# State Management23Session state, query parameters, and context management for maintaining application state across interactions. Streamlit provides powerful state management capabilities that persist data between script reruns.45## Capabilities67### Session State89Persistent state management that survives script reruns, enabling stateful applications.1011```python { .api }12session_state: SessionStateProxy13```1415Session state acts like a dictionary that persists across app reruns. Any data stored in session state will be available in subsequent reruns until the session ends.1617**Key Properties:**18- **Persistence**: Values persist across script reruns19- **Dictionary-like**: Supports standard dict operations (get, set, del, keys, etc.)20- **Widget Integration**: Automatically syncs with widget values when `key` parameter is used21- **Initialization**: Values can be initialized on first access2223Example usage:24```python25# Initialize session state26if "count" not in st.session_state:27st.session_state.count = 02829# Access and modify state30if st.button("Increment"):31st.session_state.count += 13233st.write(f"Count: {st.session_state.count}")3435# Store complex data36if "data" not in st.session_state:37st.session_state.data = {"users": [], "settings": {}}3839# Widget state integration40name = st.text_input("Name", key="user_name")41# st.session_state.user_name now contains the input value4243# Callback functions with state44def update_data():45st.session_state.data["last_update"] = datetime.now()4647st.button("Update", on_click=update_data)48```4950**Common Patterns:**51```python52# Conditional initialization53if "initialized" not in st.session_state:54st.session_state.initialized = True55st.session_state.user_data = load_user_data()5657# Page state management58if "current_page" not in st.session_state:59st.session_state.current_page = "home"6061# Multi-step forms62if "form_step" not in st.session_state:63st.session_state.form_step = 16465# Data caching in state66if "processed_data" not in st.session_state:67st.session_state.processed_data = expensive_computation()68```6970### Query Parameters7172URL query parameter management for shareable and bookmarkable app states.7374```python { .api }75query_params: QueryParamsProxy76```7778Query parameters provide a way to encode app state in the URL, making it possible to share specific app states or bookmark particular views.7980**Key Properties:**81- **URL Integration**: Automatically syncs with browser URL82- **Shareable**: URLs can be shared to recreate app state83- **Dictionary-like**: Standard dict operations for parameter access84- **Type Handling**: All values are strings (conversion needed for other types)8586Example usage:87```python88# Read query parameters89params = st.query_params90page = params.get("page", "home") # Default to "home"91user_id = params.get("user_id")9293# Set query parameters (updates URL)94st.query_params["page"] = "dashboard"95st.query_params["filter"] = "active"9697# Multiple parameters98st.query_params.update({99"view": "table",100"sort": "name",101"order": "asc"102})103104# Clear specific parameter105if "temp_param" in st.query_params:106del st.query_params["temp_param"]107108# Clear all parameters109st.query_params.clear()110111# Type conversion (all query params are strings)112if "page_num" in st.query_params:113page_num = int(st.query_params["page_num"])114else:115page_num = 1116```117118**Common Patterns:**119```python120# Page routing with query params121page = st.query_params.get("page", "home")122123if page == "home":124show_home_page()125elif page == "data":126show_data_page()127128# Filter state in URL129filters = {130"category": st.query_params.get("category", "all"),131"status": st.query_params.get("status", "active"),132"sort": st.query_params.get("sort", "name")133}134135# Update URL when filters change136if st.selectbox("Category", options, key="cat_filter") != filters["category"]:137st.query_params["category"] = st.session_state.cat_filter138139# Shareable dashboard state140st.query_params.update({141"chart_type": selected_chart,142"date_range": f"{start_date}_{end_date}",143"metrics": ",".join(selected_metrics)144})145```146147### Context Information148149Access to current execution context and environment information.150151```python { .api }152context: ContextProxy153```154155Context provides access to information about the current execution environment, headers, and request details.156157**Key Properties:**158- **Headers**: Access to HTTP headers from the request159- **Environment**: Information about the execution context160- **Request Details**: Client and server information161162Example usage:163```python164# Access request headers165headers = st.context.headers166user_agent = headers.get("User-Agent", "Unknown")167referer = headers.get("Referer")168169# Client information170st.write(f"User Agent: {user_agent}")171172# Check for specific headers173if "Authorization" in headers:174auth_token = headers["Authorization"]175user = validate_token(auth_token)176```177178### Legacy Query Parameter Functions (Deprecated)179180These functions are deprecated but still available for backward compatibility.181182```python { .api }183def experimental_get_query_params():184"""185Get current query parameters (deprecated).186187Returns:188dict: Current query parameters189190Note:191Deprecated in favor of st.query_params192"""193194def experimental_set_query_params(**kwargs):195"""196Set query parameters (deprecated).197198Args:199**kwargs: Query parameters to set200201Note:202Deprecated in favor of st.query_params203"""204```205206### State Management Patterns207208#### Widget State Synchronization209210```python211# Automatic state sync with key parameter212name = st.text_input("Name", key="user_name")213# st.session_state.user_name is automatically updated214215# Manual state access216if st.session_state.user_name:217st.write(f"Hello, {st.session_state.user_name}!")218219# Callback with state update220def on_name_change():221st.session_state.greeting = f"Hello, {st.session_state.user_name}!"222223st.text_input("Name", key="user_name", on_change=on_name_change)224```225226#### Multi-Step Workflows227228```python229# Initialize workflow state230if "step" not in st.session_state:231st.session_state.step = 1232st.session_state.form_data = {}233234# Step navigation235if st.session_state.step == 1:236name = st.text_input("Enter name")237if st.button("Next") and name:238st.session_state.form_data["name"] = name239st.session_state.step = 2240st.rerun()241242elif st.session_state.step == 2:243email = st.text_input("Enter email")244col1, col2 = st.columns(2)245with col1:246if st.button("Previous"):247st.session_state.step = 1248st.rerun()249with col2:250if st.button("Submit") and email:251st.session_state.form_data["email"] = email252submit_form(st.session_state.form_data)253st.success("Form submitted!")254```255256#### Conditional State Initialization257258```python259# Initialize state with default values260defaults = {261"user_preferences": {"theme": "light", "language": "en"},262"app_data": {"last_sync": None, "version": "1.0"},263"ui_state": {"sidebar_expanded": True, "current_tab": 0}264}265266for key, value in defaults.items():267if key not in st.session_state:268st.session_state[key] = value269270# Or with a helper function271def init_state(key, default_value):272if key not in st.session_state:273st.session_state[key] = default_value274275init_state("counter", 0)276init_state("messages", [])277init_state("user_data", {})278```279280#### URL-Driven Navigation281282```python283# URL-based page routing284def navigate_to(page_name):285st.query_params["page"] = page_name286st.rerun()287288# Page selector that updates URL289current_page = st.query_params.get("page", "home")290291pages = {292"home": "π Home",293"data": "π Data",294"settings": "βοΈ Settings"295}296297# Create navigation298selected = st.selectbox("Navigate to:",299options=list(pages.keys()),300format_func=lambda x: pages[x],301index=list(pages.keys()).index(current_page) if current_page in pages else 0302)303304if selected != current_page:305navigate_to(selected)306307# Display current page308if current_page == "home":309st.title("Home Page")310elif current_page == "data":311st.title("Data Page")312elif current_page == "settings":313st.title("Settings Page")314```315316#### State Persistence Across Sessions317318```python319# Save state to external storage320def save_state():321state_data = {322"user_preferences": st.session_state.get("user_preferences", {}),323"app_settings": st.session_state.get("app_settings", {})324}325# Save to file, database, etc.326save_to_storage(user_id, state_data)327328def load_state():329# Load from file, database, etc.330state_data = load_from_storage(user_id)331if state_data:332st.session_state.update(state_data)333334# Initialize with saved state335if "loaded" not in st.session_state:336load_state()337st.session_state.loaded = True338339# Save state periodically or on changes340if st.button("Save Preferences"):341save_state()342st.success("Preferences saved!")343```