- Spec files
pypi-streamlit
Describes: pkg:pypi/streamlit@1.16.x
- Description
- The fastest way to build and share data apps
- Author
- tessl
- Last updated
caching-config.md docs/
1# Configuration, Caching, and State Management23Application configuration, performance optimization through caching decorators, session state management, and utility functions for app lifecycle control. These capabilities help you build performant, stateful applications with proper configuration management.45## Capabilities67### Page Configuration89Configure global app settings and appearance.1011```python { .api }12def set_page_config(13page_title: str = None,14page_icon: str = None,15layout: str = "centered",16initial_sidebar_state: str = "auto",17menu_items: dict = None18) -> None:19"""20Configure the page settings (must be first Streamlit command).2122Parameters:23- page_title: Title shown in browser tab24- page_icon: Icon shown in browser tab (emoji or image URL)25- layout: Page layout ("centered" or "wide")26- initial_sidebar_state: Initial sidebar state ("auto", "expanded", "collapsed")27- menu_items: Custom menu items dictionary28"""29```3031#### Usage Example3233```python34import streamlit as st3536# Configure page (must be first Streamlit command)37st.set_page_config(38page_title="My Data App",39page_icon="๐",40layout="wide",41initial_sidebar_state="expanded",42menu_items={43'Get Help': 'https://docs.streamlit.io/',44'Report a bug': "https://github.com/myorg/myapp/issues",45'About': "This is a demo app built with Streamlit!"46}47)4849st.title("Welcome to My App")50```5152### Configuration Options5354Access and modify Streamlit's configuration system.5556```python { .api }57def get_option(key: str):58"""59Get the value of a configuration option.6061Parameters:62- key: Configuration key (e.g., "theme.primaryColor")6364Returns:65The current value of the configuration option66"""6768def set_option(key: str, value) -> None:69"""70Set the value of a configuration option.7172Parameters:73- key: Configuration key (e.g., "theme.primaryColor")74- value: New value for the configuration option75"""76```7778#### Usage Example7980```python81import streamlit as st8283# Get current configuration84current_theme = st.get_option("theme.base")85st.write(f"Current theme: {current_theme}")8687# Set configuration options88st.set_option("theme.primaryColor", "#FF6B6B")89st.set_option("theme.backgroundColor", "#FFFFFF")9091# Common configuration options92st.write("Available config categories:")93st.write("- theme.*: UI theme settings")94st.write("- server.*: Server configuration")95st.write("- browser.*: Browser behavior")96st.write("- logger.*: Logging configuration")97```9899### Legacy Caching100101Traditional caching decorator for expensive computations.102103```python { .api }104@cache(persist: bool = False, allow_output_mutation: bool = False, suppress_st_warning: bool = False, hash_funcs: dict = None, max_entries: int = None, ttl: float = None, show_spinner: bool = True)105def cached_function():106"""107Decorator for caching function results (legacy).108109Parameters:110- persist: Whether to persist cache across sessions111- allow_output_mutation: Whether to allow mutation of cached results112- suppress_st_warning: Whether to suppress Streamlit warnings113- hash_funcs: Custom hash functions for parameters114- max_entries: Maximum number of cache entries115- ttl: Time-to-live in seconds116- show_spinner: Whether to show spinner during computation117"""118```119120#### Usage Example121122```python123import streamlit as st124import pandas as pd125import time126127@st.cache128def load_data(file_path):129"""Load data with caching to avoid repeated file reads."""130time.sleep(2) # Simulate expensive operation131return pd.read_csv(file_path)132133@st.cache(ttl=3600) # Cache for 1 hour134def fetch_api_data(api_url):135"""Fetch data from API with time-based cache expiration."""136# Simulate API call137time.sleep(1)138return {"data": "api_result", "timestamp": time.time()}139140# Use cached functions141data = load_data("data.csv")142api_result = fetch_api_data("https://api.example.com/data")143144st.dataframe(data)145st.json(api_result)146```147148### Modern Caching (Experimental)149150New caching decorators with improved performance and features.151152```python { .api }153@experimental_memo(persist: str = None, show_spinner: bool = True, suppress_st_warning: bool = False, max_entries: int = None, ttl: float = None)154def memo_function():155"""156Decorator for caching data and computations (experimental).157158Parameters:159- persist: Persistence mode ("disk" or None)160- show_spinner: Whether to show spinner during computation161- suppress_st_warning: Whether to suppress Streamlit warnings162- max_entries: Maximum number of cache entries163- ttl: Time-to-live in seconds164"""165166@experimental_singleton(show_spinner: bool = True, suppress_st_warning: bool = False)167def singleton_function():168"""169Decorator for creating singleton objects (experimental).170171Parameters:172- show_spinner: Whether to show spinner during initialization173- suppress_st_warning: Whether to suppress Streamlit warnings174"""175```176177#### Usage Example178179```python180import streamlit as st181import pandas as pd182import numpy as np183184@st.experimental_memo185def expensive_computation(n):186"""Expensive computation with memo caching."""187# Simulate heavy computation188result = np.random.rand(n, n).dot(np.random.rand(n, n))189return result190191@st.experimental_singleton192def get_database_connection():193"""Create singleton database connection."""194# Simulate database connection setup195class MockDB:196def __init__(self):197self.connected = True198199def query(self, sql):200return pd.DataFrame({"result": [1, 2, 3]})201202return MockDB()203204# Use modern caching205matrix = expensive_computation(100)206db = get_database_connection()207208st.write(f"Matrix shape: {matrix.shape}")209st.dataframe(db.query("SELECT * FROM table"))210```211212### Session State213214Manage user session data that persists across app reruns.215216```python { .api }217session_state: SessionStateProxy218# Access via st.session_state219220class SessionStateProxy:221"""Session state management interface."""222223def __getitem__(self, key: str) -> Any:224"""Get session state value."""225226def __setitem__(self, key: str, value: Any) -> None:227"""Set session state value."""228229def __contains__(self, key: str) -> bool:230"""Check if key exists in session state."""231232def __delitem__(self, key: str) -> None:233"""Delete session state key."""234```235236#### Usage Example237238```python239import streamlit as st240241# Initialize session state242if "counter" not in st.session_state:243st.session_state.counter = 0244245if "user_data" not in st.session_state:246st.session_state.user_data = {}247248# Use session state with widgets249col1, col2, col3 = st.columns(3)250251with col1:252if st.button("Increment"):253st.session_state.counter += 1254255with col2:256if st.button("Decrement"):257st.session_state.counter -= 1258259with col3:260if st.button("Reset"):261st.session_state.counter = 0262263st.write(f"Counter: {st.session_state.counter}")264265# Form data persistence266with st.form("user_form"):267name = st.text_input("Name", value=st.session_state.user_data.get("name", ""))268age = st.number_input("Age", value=st.session_state.user_data.get("age", 0))269270if st.form_submit_button("Save"):271st.session_state.user_data["name"] = name272st.session_state.user_data["age"] = age273st.success("Data saved to session!")274275# Display all session state (for debugging)276with st.expander("Session State Debug"):277st.write(st.session_state)278```279280### Secrets Management281282Securely access application secrets and configuration.283284```python { .api }285secrets: SecretsProxy286# Access via st.secrets287288class SecretsProxy:289"""Secrets management interface."""290291def __getitem__(self, key: str) -> Any:292"""Get secret value."""293294def __contains__(self, key: str) -> bool:295"""Check if secret exists."""296```297298#### Usage Example299300```python301import streamlit as st302303# Access secrets (configured in .streamlit/secrets.toml)304db_password = st.secrets["database"]["password"]305api_key = st.secrets["api_key"]306307# Use secrets safely308if "database" in st.secrets:309connection_string = f"postgresql://user:{st.secrets.database.password}@localhost/db"310st.success("Database configured")311else:312st.error("Database secrets not found")313314# Example secrets.toml structure:315st.code("""316# .streamlit/secrets.toml317api_key = "your-api-key-here"318319[database]320host = "localhost"321port = 5432322username = "user"323password = "secret-password"324""", language="toml")325```326327### App Control and Lifecycle328329Control application execution flow and provide user feedback.330331```python { .api }332def stop() -> NoReturn:333"""334Stop execution of the Streamlit script.335336Raises:337StreamlitAPIException: Always (stops execution)338"""339340def balloons() -> DeltaGenerator:341"""Display falling balloons animation."""342343def snow() -> DeltaGenerator:344"""Display falling snow animation."""345346def progress(value: float) -> DeltaGenerator:347"""348Display a progress bar.349350Parameters:351- value: Progress value between 0.0 and 1.0352353Returns:354DeltaGenerator: Progress bar object that can be updated355"""356357def spinner(text: str = "In progress...") -> ContextManager[None]:358"""359Display a spinner with text during long operations.360361Parameters:362- text: Text displayed next to spinner363364Returns:365Context manager for use with 'with' statement366"""367368def echo(code_location: str = "above") -> ContextManager[None]:369"""370Display code while executing it.371372Parameters:373- code_location: Where to show code ("above" or "below")374375Returns:376Context manager for code echoing377"""378```379380#### Usage Example381382```python383import streamlit as st384import time385386# Celebration animations387if st.button("Celebrate!"):388st.balloons()389st.success("Congratulations!")390391if st.button("Winter Theme"):392st.snow()393st.info("Let it snow!")394395# Progress bar396progress_bar = st.progress(0)397status_text = st.empty()398399for i in range(100):400progress_bar.progress(i + 1)401status_text.text(f'Progress: {i+1}%')402time.sleep(0.01)403404status_text.text('Operation completed!')405406# Spinner for long operations407with st.spinner('Loading data...'):408time.sleep(3) # Simulate long operation409data = [1, 2, 3, 4, 5]410411st.success('Data loaded!')412st.write(data)413414# Echo code execution415with st.echo():416# This code will be displayed and executed417x = 10418y = 20419result = x + y420st.write(f"The result is {result}")421422# Conditional stop423user_input = st.text_input("Enter 'stop' to halt execution:")424if user_input.lower() == 'stop':425st.error("Execution stopped by user!")426st.stop()427428st.write("This will only show if execution wasn't stopped")429```430431### Query Parameters (Experimental)432433Access and modify URL query parameters.434435```python { .api }436def experimental_get_query_params() -> Dict[str, List[str]]:437"""438Get the current query parameters from the URL.439440Returns:441Dictionary mapping parameter names to lists of values442"""443444def experimental_set_query_params(**kwargs) -> None:445"""446Set query parameters in the URL.447448Parameters:449- **kwargs: Parameter names and values to set450"""451```452453#### Usage Example454455```python456import streamlit as st457458# Get current query parameters459query_params = st.experimental_get_query_params()460st.write("Current query parameters:", query_params)461462# Use query parameters to set initial state463if "page" in query_params:464initial_page = query_params["page"][0]465else:466initial_page = "home"467468# Widget that updates URL469page = st.selectbox("Select page:", ["home", "data", "settings"],470index=["home", "data", "settings"].index(initial_page))471472# Update query parameters when selection changes473if page != initial_page:474st.experimental_set_query_params(page=page)475476# Multiple parameters477filter_type = st.selectbox("Filter:", ["all", "active", "inactive"])478sort_by = st.selectbox("Sort by:", ["name", "date", "priority"])479480# Update multiple parameters481st.experimental_set_query_params(482page=page,483filter=filter_type,484sort=sort_by485)486487st.write(f"Current page: {page}")488st.write(f"Filter: {filter_type}, Sort: {sort_by}")489```490491### Script Control (Experimental)492493Programmatically control script execution flow.494495```python { .api }496def experimental_rerun() -> NoReturn:497"""498Rerun the current script (experimental).499500Raises:501StreamlitAPIException: Always (triggers rerun)502"""503```504505#### Usage Example506507```python508import streamlit as st509510# Button that triggers rerun511if st.button("Refresh Data"):512# Clear any cached data if needed513st.cache.clear()514515# Trigger script rerun516st.experimental_rerun()517518# Conditional rerun based on state519if st.session_state.get("needs_refresh", False):520st.session_state.needs_refresh = False521st.experimental_rerun()522```523524### User Information (Experimental)525526Access user information in deployed apps.527528```python { .api }529experimental_user: UserInfoProxy530531class UserInfoProxy:532"""User information access interface (experimental)."""533534@property535def email(self) -> str:536"""Get user's email address (if available)."""537```538539#### Usage Example540541```python542import streamlit as st543544# Access user information (only works in deployed apps)545try:546user_email = st.experimental_user.email547st.write(f"Welcome, {user_email}!")548except:549st.write("User information not available (local development)")550551# Conditional features based on user552if hasattr(st.experimental_user, 'email'):553if "@company.com" in st.experimental_user.email:554st.info("You have admin access")555admin_section = st.checkbox("Show admin panel")556if admin_section:557st.write("Admin controls would go here")558```559560## Performance and Caching Best Practices561562- Use `@st.cache` or `@st.experimental_memo` for expensive data loading563- Use `@st.experimental_singleton` for database connections and ML models564- Store user input in `st.session_state` to maintain state across reruns565- Use `st.secrets` for sensitive configuration data566- Set appropriate TTL values for time-sensitive cached data567- Use `suppress_st_warning=True` to silence caching warnings in production