- Spec files
pypi-streamlit
Describes: pkg:pypi/streamlit@1.49.x
- Description
- A faster way to build and share data apps
- Author
- tessl
- Last updated
configuration-control.md docs/
1# Configuration and Control23Application configuration, execution control, and utility functions for managing app behavior, page settings, and runtime control flow.45## Capabilities67### Page Configuration89Configure global page settings, appearance, and metadata.1011```python { .api }12def set_page_config(page_title=None, page_icon=None, layout="centered", initial_sidebar_state="auto", menu_items=None):13"""14Configure the default settings of the page.1516Note: This must be called as the first Streamlit command in your script.1718Parameters:19- page_title (str): The page title shown in browser tab20- page_icon (str): Emoji or image URL for the page favicon21- layout (str): Page layout ('centered' or 'wide')22- initial_sidebar_state (str): Initial sidebar state ('auto', 'expanded', 'collapsed')23- menu_items (dict): Custom menu items in the hamburger menu2425Returns:26None27"""28```2930### Execution Control3132Control script execution flow and trigger reruns.3334```python { .api }35def rerun():36"""37Rerun the script immediately.3839Returns:40None (function does not return)41"""4243def stop():44"""45Stop execution of the script immediately.4647Returns:48None (function does not return)49"""5051def switch_page(page):52"""53Programmatically switch to another page in a multipage app.5455Parameters:56- page (str or Page): Page name or Page object to switch to5758Returns:59None (function does not return)60"""61```6263### Configuration Options6465Get and set Streamlit configuration options.6667```python { .api }68def get_option(key):69"""70Return the value of a given Streamlit config option.7172Parameters:73- key (str): Configuration option key (e.g., 'theme.primaryColor')7475Returns:76Any: Configuration option value77"""7879def set_option(key, value):80"""81Set a Streamlit config option to the given value.8283Parameters:84- key (str): Configuration option key85- value: Value to set for the configuration option8687Returns:88None89"""90```9192### Development and Debugging9394Utilities for development, debugging, and code inspection.9596```python { .api }97def echo(code_location="above"):98"""99Use in a `with` block to draw source code on the app, then execute it.100101Parameters:102- code_location (str): Where to show code ('above' or 'below')103104Returns:105ContextManager: Echo context manager106"""107108def help(obj):109"""110Display the help string for an object (function, class, module, etc.).111112Parameters:113- obj: Python object to show help for114115Returns:116None117"""118```119120### Branding and Identity121122Add branding elements to your application.123124```python { .api }125def logo(image, link=None, icon_image=None, size="medium"):126"""127Display a logo widget in the top-left corner of the app.128129Parameters:130- image: Logo image (file path, URL, PIL Image, or bytes)131- link (str): URL to navigate to when logo is clicked132- icon_image: Small icon version of the logo for mobile/collapsed view133- size (str): Logo size ('small', 'medium', 'large')134135Returns:136None137"""138```139140### Context Information141142Access runtime context and environment information.143144```python { .api }145# Context information proxy146context: ContextProxy147148# Access patterns:149# st.context.cookies # Browser cookies (if available)150# st.context.headers # HTTP headers (if available)151# st.context.query_params # URL query parameters152```153154### Secrets Management155156Securely access secrets and configuration values.157158```python { .api }159# Secrets singleton for accessing secrets.toml and environment variables160secrets: SecretsProxy161162# Access patterns:163# st.secrets["api_key"] # Access secret by key164# st.secrets.database.password # Access nested secrets165# st.secrets.has_key("key") # Check if secret exists166```167168## Usage Examples169170### Page Configuration171172```python173import streamlit as st174175# Must be first Streamlit command176st.set_page_config(177page_title="My Analytics App",178page_icon="π",179layout="wide",180initial_sidebar_state="expanded",181menu_items={182'Get Help': 'https://docs.streamlit.io',183'Report a bug': 'https://github.com/streamlit/streamlit/issues',184'About': "This is my custom analytics dashboard built with Streamlit!"185}186)187188st.title("π Analytics Dashboard")189st.write("This app uses wide layout and custom page configuration.")190191# Wide layout example192col1, col2, col3, col4 = st.columns(4)193194with col1:195st.metric("Revenue", "$125K", "8%")196with col2:197st.metric("Users", "2.4K", "12%")198with col3:199st.metric("Sessions", "8.3K", "5%")200with col4:201st.metric("Bounce Rate", "32%", "-2%")202203# Sample wide chart204import pandas as pd205import numpy as np206207chart_data = pd.DataFrame(208np.random.randn(50, 4),209columns=['A', 'B', 'C', 'D']210)211212st.subheader("Performance Over Time")213st.line_chart(chart_data)214```215216### Execution Control217218```python219# Rerun example220st.title("π Execution Control Demo")221222# Counter with auto-increment223if 'counter' not in st.session_state:224st.session_state.counter = 0225226st.write(f"Counter: {st.session_state.counter}")227228col1, col2, col3, col4 = st.columns(4)229230with col1:231if st.button("β Increment"):232st.session_state.counter += 1233st.rerun() # Immediately rerun to show updated counter234235with col2:236if st.button("β Decrement"):237st.session_state.counter -= 1238st.rerun()239240with col3:241if st.button("π Reset"):242st.session_state.counter = 0243st.rerun()244245with col4:246if st.button("π Stop"):247st.error("Execution stopped!")248st.stop() # This stops execution here249250# This line won't execute if stop button was clicked251st.success("Script is still running!")252253# Conditional execution control254if st.session_state.counter > 10:255st.warning("Counter is getting high!")256if st.button("Auto-reset counter"):257st.session_state.counter = 0258st.success("Counter has been reset!")259st.rerun()260261if st.session_state.counter < 0:262st.info("Counter went negative, stopping execution.")263st.stop()264```265266### Page Switching (Multipage App)267268```python269# Define pages270def page_home():271st.title("π Home")272st.write("Welcome to the home page!")273274if st.button("Go to Analytics"):275st.switch_page("pages/analytics.py")276277def page_analytics():278st.title("π Analytics")279st.write("Analytics page content")280281if st.button("Go to Settings"):282st.switch_page("pages/settings.py")283284def page_settings():285st.title("βοΈ Settings")286st.write("Settings page content")287288if st.button("Go Home"):289st.switch_page("streamlit_app.py")290291# For demonstration - normally these would be in separate files292current_page = st.radio("Simulate page:", ["Home", "Analytics", "Settings"])293294if current_page == "Home":295page_home()296elif current_page == "Analytics":297page_analytics()298else:299page_settings()300```301302### Configuration Management303304```python305st.subheader("βοΈ Configuration Options")306307# Display current theme colors308try:309primary_color = st.get_option('theme.primaryColor')310bg_color = st.get_option('theme.backgroundColor')311secondary_bg = st.get_option('theme.secondaryBackgroundColor')312text_color = st.get_option('theme.textColor')313314st.write("**Current Theme Colors:**")315col1, col2 = st.columns(2)316317with col1:318st.write(f"Primary Color: `{primary_color}`")319st.write(f"Background Color: `{bg_color}`")320321with col2:322st.write(f"Secondary Background: `{secondary_bg}`")323st.write(f"Text Color: `{text_color}`")324325except Exception as e:326st.info("Theme colors not configured or accessible")327328# Server configuration329try:330server_port = st.get_option('server.port')331server_address = st.get_option('server.address')332333st.write("**Server Configuration:**")334st.write(f"Port: `{server_port}`")335st.write(f"Address: `{server_address}`")336337except Exception as e:338st.info("Server configuration not accessible")339340# Development settings341st.write("**Development Options:**")342343# Example of setting options (usually done in config.toml)344if st.button("Enable Development Mode"):345try:346st.set_option('logger.level', 'debug')347st.success("Development mode enabled!")348except Exception as e:349st.error(f"Could not set option: {e}")350```351352### Code Echo and Documentation353354```python355st.subheader("π Code Echo Demo")356357st.write("The code below will be displayed and then executed:")358359# Echo code above execution360with st.echo():361import matplotlib.pyplot as plt362import numpy as np363364# Generate sample data365x = np.linspace(0, 10, 100)366y = np.sin(x)367368# Create plot369fig, ax = plt.subplots()370ax.plot(x, y)371ax.set_title('Sine Wave')372ax.set_xlabel('X values')373ax.set_ylabel('Y values')374375# Display in Streamlit376st.pyplot(fig)377378st.divider()379380# Echo code below execution381st.write("Execute first, then show code:")382383with st.echo(code_location="below"):384# This will execute first, then show the code385import pandas as pd386387data = pd.DataFrame({388'A': [1, 2, 3, 4],389'B': [10, 20, 30, 40]390})391392st.bar_chart(data.set_index('A'))393394# Help example395st.subheader("π Help Documentation")396397col1, col2 = st.columns(2)398399with col1:400st.write("**Help for built-in functions:**")401if st.button("Show help for st.write"):402st.help(st.write)403404with col2:405st.write("**Help for Python objects:**")406if st.button("Show help for pandas.DataFrame"):407try:408import pandas as pd409st.help(pd.DataFrame)410except ImportError:411st.error("Pandas not available")412```413414### Logo and Branding415416```python417# Logo examples418st.subheader("π·οΈ Logo and Branding")419420# Set logo (normally done at top of app)421try:422st.logo(423"https://streamlit.io/images/brand/streamlit-logo-primary-colormark-darktext.png",424link="https://streamlit.io",425size="large"426)427st.success("Logo set successfully!")428except Exception as e:429st.info("Logo example (requires valid image URL)")430431# Custom branding elements432st.markdown("""433<div style="434background: linear-gradient(90deg, #FF6B6B, #4ECDC4);435padding: 1rem;436border-radius: 0.5rem;437text-align: center;438color: white;439font-weight: bold;440margin: 1rem 0;441">442π Custom Brand Header443</div>444""", unsafe_allow_html=True)445```446447### Secrets Management448449```python450st.subheader("π Secrets Management")451452# Accessing secrets (create secrets.toml file in .streamlit folder)453try:454# Example secrets.toml structure:455# [database]456# host = "localhost"457# port = 5432458# username = "user"459# password = "secret"460461# [api]462# key = "your-api-key"463# endpoint = "https://api.example.com"464465st.write("**Available secrets:**")466467# Check if secrets exist468if st.secrets.get("database"):469st.write("β Database configuration found")470db_config = st.secrets["database"]471st.write(f"Database host: `{db_config.get('host', 'not set')}`")472st.write(f"Database port: `{db_config.get('port', 'not set')}`")473# Never display sensitive values like passwords474st.write("Password: `[HIDDEN]`")475else:476st.write("β Database configuration not found")477478if st.secrets.get("api"):479st.write("β API configuration found")480api_config = st.secrets["api"]481st.write(f"API endpoint: `{api_config.get('endpoint', 'not set')}`")482st.write("API key: `[HIDDEN]`")483else:484st.write("β API configuration not found")485486except Exception as e:487st.info("No secrets file found. Create `.streamlit/secrets.toml` to use secrets.")488489st.code("""490# Example .streamlit/secrets.toml file:491492[database]493host = "localhost"494port = 5432495username = "myuser"496password = "mypassword"497498[api]499key = "your-api-key-here"500endpoint = "https://api.example.com"501""")502503# Environment variables as secrets504import os505506st.write("**Environment Variables:**")507if os.getenv("STREAMLIT_ENV"):508st.write(f"Environment: `{os.getenv('STREAMLIT_ENV')}`")509else:510st.write("No STREAMLIT_ENV variable set")511512# Safe secret usage pattern513def get_database_url():514try:515db_config = st.secrets["database"]516return f"postgresql://{db_config['username']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/dbname"517except KeyError:518st.error("Database configuration incomplete")519return None520521if st.button("Test Database Connection (Simulated)"):522db_url = get_database_url()523if db_url:524# In real app, you would use this URL to connect to database525st.success("Database URL generated successfully!")526st.write("Connection would be established with configured credentials")527else:528st.error("Could not generate database URL")529```530531### Context Information532533```python534st.subheader("π Context Information")535536# Query parameters from URL537st.write("**Query Parameters:**")538query_params = st.context.query_params if hasattr(st.context, 'query_params') else st.query_params539if query_params:540st.json(dict(query_params))541else:542st.write("No query parameters in URL")543544# Headers (if available)545st.write("**Request Headers:**")546try:547if hasattr(st.context, 'headers'):548# Only show safe headers549safe_headers = ['user-agent', 'accept-language', 'accept-encoding']550headers_info = {k: v for k, v in st.context.headers.items() if k.lower() in safe_headers}551if headers_info:552st.json(headers_info)553else:554st.write("No safe headers to display")555else:556st.write("Headers not available in current context")557except Exception as e:558st.write("Headers not accessible")559560# Session information561st.write("**Session Information:**")562session_info = {563"Session State Keys": list(st.session_state.keys()),564"Number of State Variables": len(st.session_state)565}566st.json(session_info)567```568569### Advanced Configuration570571```python572st.subheader("π§ Advanced Configuration")573574# Performance monitoring575if st.button("Check Performance Settings"):576try:577# Check caching settings578cache_settings = {579"Cache Enabled": True, # Always enabled in current versions580"Max Cache Size": "Not directly accessible",581}582st.json(cache_settings)583584# Memory usage (if available)585import psutil586process = psutil.Process()587memory_info = {588"Memory Usage (MB)": round(process.memory_info().rss / 1024 / 1024, 2),589"CPU Percent": f"{process.cpu_percent()}%"590}591st.json(memory_info)592593except ImportError:594st.info("Install psutil for memory monitoring: `pip install psutil`")595except Exception as e:596st.error(f"Could not get performance info: {e}")597598# Development utilities599if st.checkbox("Development Mode"):600st.warning("π¨ Development mode enabled")601602# Show session state603with st.expander("Session State Debug"):604st.json(dict(st.session_state))605606# Show configuration607with st.expander("App Configuration"):608config_info = {609"Python Path": __file__ if '__file__' in globals() else "Unknown",610"Streamlit Version": st.__version__,611}612st.json(config_info)613614# Clear all caches615if st.button("π§Ή Clear All Caches"):616st.cache_data.clear()617st.cache_resource.clear()618st.success("All caches cleared!")619```