A faster way to build and share data apps
Application configuration, execution control, and utility functions for managing app behavior, page settings, and runtime control flow.
Configure global page settings, appearance, and metadata.
def set_page_config(page_title=None, page_icon=None, layout="centered", initial_sidebar_state="auto", menu_items=None):
"""
Configure the default settings of the page.
Note: This must be called as the first Streamlit command in your script.
Parameters:
- page_title (str): The page title shown in browser tab
- page_icon (str): Emoji or image URL for the page favicon
- layout (str): Page layout ('centered' or 'wide')
- initial_sidebar_state (str): Initial sidebar state ('auto', 'expanded', 'collapsed')
- menu_items (dict): Custom menu items in the hamburger menu
Returns:
None
"""Control script execution flow and trigger reruns.
def rerun():
"""
Rerun the script immediately.
Returns:
None (function does not return)
"""
def stop():
"""
Stop execution of the script immediately.
Returns:
None (function does not return)
"""
def switch_page(page):
"""
Programmatically switch to another page in a multipage app.
Parameters:
- page (str or Page): Page name or Page object to switch to
Returns:
None (function does not return)
"""Get and set Streamlit configuration options.
def get_option(key):
"""
Return the value of a given Streamlit config option.
Parameters:
- key (str): Configuration option key (e.g., 'theme.primaryColor')
Returns:
Any: Configuration option value
"""
def set_option(key, value):
"""
Set a Streamlit config option to the given value.
Parameters:
- key (str): Configuration option key
- value: Value to set for the configuration option
Returns:
None
"""Utilities for development, debugging, and code inspection.
def echo(code_location="above"):
"""
Use in a `with` block to draw source code on the app, then execute it.
Parameters:
- code_location (str): Where to show code ('above' or 'below')
Returns:
ContextManager: Echo context manager
"""
def help(obj):
"""
Display the help string for an object (function, class, module, etc.).
Parameters:
- obj: Python object to show help for
Returns:
None
"""Add branding elements to your application.
def logo(image, link=None, icon_image=None, size="medium"):
"""
Display a logo widget in the top-left corner of the app.
Parameters:
- image: Logo image (file path, URL, PIL Image, or bytes)
- link (str): URL to navigate to when logo is clicked
- icon_image: Small icon version of the logo for mobile/collapsed view
- size (str): Logo size ('small', 'medium', 'large')
Returns:
None
"""Access runtime context and environment information.
# Context information proxy
context: ContextProxy
# Access patterns:
# st.context.cookies # Browser cookies (if available)
# st.context.headers # HTTP headers (if available)
# st.context.query_params # URL query parametersSecurely access secrets and configuration values.
# Secrets singleton for accessing secrets.toml and environment variables
secrets: SecretsProxy
# Access patterns:
# st.secrets["api_key"] # Access secret by key
# st.secrets.database.password # Access nested secrets
# st.secrets.has_key("key") # Check if secret existsimport streamlit as st
# Must be first Streamlit command
st.set_page_config(
page_title="My Analytics App",
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'https://docs.streamlit.io',
'Report a bug': 'https://github.com/streamlit/streamlit/issues',
'About': "This is my custom analytics dashboard built with Streamlit!"
}
)
st.title("📊 Analytics Dashboard")
st.write("This app uses wide layout and custom page configuration.")
# Wide layout example
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Revenue", "$125K", "8%")
with col2:
st.metric("Users", "2.4K", "12%")
with col3:
st.metric("Sessions", "8.3K", "5%")
with col4:
st.metric("Bounce Rate", "32%", "-2%")
# Sample wide chart
import pandas as pd
import numpy as np
chart_data = pd.DataFrame(
np.random.randn(50, 4),
columns=['A', 'B', 'C', 'D']
)
st.subheader("Performance Over Time")
st.line_chart(chart_data)# Rerun example
st.title("🔄 Execution Control Demo")
# Counter with auto-increment
if 'counter' not in st.session_state:
st.session_state.counter = 0
st.write(f"Counter: {st.session_state.counter}")
col1, col2, col3, col4 = st.columns(4)
with col1:
if st.button("➕ Increment"):
st.session_state.counter += 1
st.rerun() # Immediately rerun to show updated counter
with col2:
if st.button("➖ Decrement"):
st.session_state.counter -= 1
st.rerun()
with col3:
if st.button("🔄 Reset"):
st.session_state.counter = 0
st.rerun()
with col4:
if st.button("🛑 Stop"):
st.error("Execution stopped!")
st.stop() # This stops execution here
# This line won't execute if stop button was clicked
st.success("Script is still running!")
# Conditional execution control
if st.session_state.counter > 10:
st.warning("Counter is getting high!")
if st.button("Auto-reset counter"):
st.session_state.counter = 0
st.success("Counter has been reset!")
st.rerun()
if st.session_state.counter < 0:
st.info("Counter went negative, stopping execution.")
st.stop()# Define pages
def page_home():
st.title("🏠 Home")
st.write("Welcome to the home page!")
if st.button("Go to Analytics"):
st.switch_page("pages/analytics.py")
def page_analytics():
st.title("📊 Analytics")
st.write("Analytics page content")
if st.button("Go to Settings"):
st.switch_page("pages/settings.py")
def page_settings():
st.title("⚙️ Settings")
st.write("Settings page content")
if st.button("Go Home"):
st.switch_page("streamlit_app.py")
# For demonstration - normally these would be in separate files
current_page = st.radio("Simulate page:", ["Home", "Analytics", "Settings"])
if current_page == "Home":
page_home()
elif current_page == "Analytics":
page_analytics()
else:
page_settings()st.subheader("⚙️ Configuration Options")
# Display current theme colors
try:
primary_color = st.get_option('theme.primaryColor')
bg_color = st.get_option('theme.backgroundColor')
secondary_bg = st.get_option('theme.secondaryBackgroundColor')
text_color = st.get_option('theme.textColor')
st.write("**Current Theme Colors:**")
col1, col2 = st.columns(2)
with col1:
st.write(f"Primary Color: `{primary_color}`")
st.write(f"Background Color: `{bg_color}`")
with col2:
st.write(f"Secondary Background: `{secondary_bg}`")
st.write(f"Text Color: `{text_color}`")
except Exception as e:
st.info("Theme colors not configured or accessible")
# Server configuration
try:
server_port = st.get_option('server.port')
server_address = st.get_option('server.address')
st.write("**Server Configuration:**")
st.write(f"Port: `{server_port}`")
st.write(f"Address: `{server_address}`")
except Exception as e:
st.info("Server configuration not accessible")
# Development settings
st.write("**Development Options:**")
# Example of setting options (usually done in config.toml)
if st.button("Enable Development Mode"):
try:
st.set_option('logger.level', 'debug')
st.success("Development mode enabled!")
except Exception as e:
st.error(f"Could not set option: {e}")st.subheader("📝 Code Echo Demo")
st.write("The code below will be displayed and then executed:")
# Echo code above execution
with st.echo():
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create plot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Sine Wave')
ax.set_xlabel('X values')
ax.set_ylabel('Y values')
# Display in Streamlit
st.pyplot(fig)
st.divider()
# Echo code below execution
st.write("Execute first, then show code:")
with st.echo(code_location="below"):
# This will execute first, then show the code
import pandas as pd
data = pd.DataFrame({
'A': [1, 2, 3, 4],
'B': [10, 20, 30, 40]
})
st.bar_chart(data.set_index('A'))
# Help example
st.subheader("🆘 Help Documentation")
col1, col2 = st.columns(2)
with col1:
st.write("**Help for built-in functions:**")
if st.button("Show help for st.write"):
st.help(st.write)
with col2:
st.write("**Help for Python objects:**")
if st.button("Show help for pandas.DataFrame"):
try:
import pandas as pd
st.help(pd.DataFrame)
except ImportError:
st.error("Pandas not available")# Logo examples
st.subheader("🏷️ Logo and Branding")
# Set logo (normally done at top of app)
try:
st.logo(
"https://streamlit.io/images/brand/streamlit-logo-primary-colormark-darktext.png",
link="https://streamlit.io",
size="large"
)
st.success("Logo set successfully!")
except Exception as e:
st.info("Logo example (requires valid image URL)")
# Custom branding elements
st.markdown("""
<div style="
background: linear-gradient(90deg, #FF6B6B, #4ECDC4);
padding: 1rem;
border-radius: 0.5rem;
text-align: center;
color: white;
font-weight: bold;
margin: 1rem 0;
">
🚀 Custom Brand Header
</div>
""", unsafe_allow_html=True)st.subheader("🔐 Secrets Management")
# Accessing secrets (create secrets.toml file in .streamlit folder)
try:
# Example secrets.toml structure:
# [database]
# host = "localhost"
# port = 5432
# username = "user"
# password = "secret"
# [api]
# key = "your-api-key"
# endpoint = "https://api.example.com"
st.write("**Available secrets:**")
# Check if secrets exist
if st.secrets.get("database"):
st.write("✅ Database configuration found")
db_config = st.secrets["database"]
st.write(f"Database host: `{db_config.get('host', 'not set')}`")
st.write(f"Database port: `{db_config.get('port', 'not set')}`")
# Never display sensitive values like passwords
st.write("Password: `[HIDDEN]`")
else:
st.write("❌ Database configuration not found")
if st.secrets.get("api"):
st.write("✅ API configuration found")
api_config = st.secrets["api"]
st.write(f"API endpoint: `{api_config.get('endpoint', 'not set')}`")
st.write("API key: `[HIDDEN]`")
else:
st.write("❌ API configuration not found")
except Exception as e:
st.info("No secrets file found. Create `.streamlit/secrets.toml` to use secrets.")
st.code("""
# Example .streamlit/secrets.toml file:
[database]
host = "localhost"
port = 5432
username = "myuser"
password = "mypassword"
[api]
key = "your-api-key-here"
endpoint = "https://api.example.com"
""")
# Environment variables as secrets
import os
st.write("**Environment Variables:**")
if os.getenv("STREAMLIT_ENV"):
st.write(f"Environment: `{os.getenv('STREAMLIT_ENV')}`")
else:
st.write("No STREAMLIT_ENV variable set")
# Safe secret usage pattern
def get_database_url():
try:
db_config = st.secrets["database"]
return f"postgresql://{db_config['username']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/dbname"
except KeyError:
st.error("Database configuration incomplete")
return None
if st.button("Test Database Connection (Simulated)"):
db_url = get_database_url()
if db_url:
# In real app, you would use this URL to connect to database
st.success("Database URL generated successfully!")
st.write("Connection would be established with configured credentials")
else:
st.error("Could not generate database URL")st.subheader("🌐 Context Information")
# Query parameters from URL
st.write("**Query Parameters:**")
query_params = st.context.query_params if hasattr(st.context, 'query_params') else st.query_params
if query_params:
st.json(dict(query_params))
else:
st.write("No query parameters in URL")
# Headers (if available)
st.write("**Request Headers:**")
try:
if hasattr(st.context, 'headers'):
# Only show safe headers
safe_headers = ['user-agent', 'accept-language', 'accept-encoding']
headers_info = {k: v for k, v in st.context.headers.items() if k.lower() in safe_headers}
if headers_info:
st.json(headers_info)
else:
st.write("No safe headers to display")
else:
st.write("Headers not available in current context")
except Exception as e:
st.write("Headers not accessible")
# Session information
st.write("**Session Information:**")
session_info = {
"Session State Keys": list(st.session_state.keys()),
"Number of State Variables": len(st.session_state)
}
st.json(session_info)st.subheader("🔧 Advanced Configuration")
# Performance monitoring
if st.button("Check Performance Settings"):
try:
# Check caching settings
cache_settings = {
"Cache Enabled": True, # Always enabled in current versions
"Max Cache Size": "Not directly accessible",
}
st.json(cache_settings)
# Memory usage (if available)
import psutil
process = psutil.Process()
memory_info = {
"Memory Usage (MB)": round(process.memory_info().rss / 1024 / 1024, 2),
"CPU Percent": f"{process.cpu_percent()}%"
}
st.json(memory_info)
except ImportError:
st.info("Install psutil for memory monitoring: `pip install psutil`")
except Exception as e:
st.error(f"Could not get performance info: {e}")
# Development utilities
if st.checkbox("Development Mode"):
st.warning("🚨 Development mode enabled")
# Show session state
with st.expander("Session State Debug"):
st.json(dict(st.session_state))
# Show configuration
with st.expander("App Configuration"):
config_info = {
"Python Path": __file__ if '__file__' in globals() else "Unknown",
"Streamlit Version": st.__version__,
}
st.json(config_info)
# Clear all caches
if st.button("🧹 Clear All Caches"):
st.cache_data.clear()
st.cache_resource.clear()
st.success("All caches cleared!")Install with Tessl CLI
npx tessl i tessl/pypi-streamlit@1.49.0