- 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
advanced-features.md docs/
1# Advanced Features23Advanced Streamlit functionality including authentication, navigation, fragments, dialogs, custom components, and data connections for sophisticated application development.45## Capabilities67### Multi-page Navigation89Navigate between multiple pages in a Streamlit application.1011```python { .api }12def navigation(pages, position="sidebar"):13"""14Render a navigation widget for multipage apps.1516Parameters:17- pages (list): List of Page objects or page configuration dicts18- position (str): Navigation position ('sidebar' or 'main')1920Returns:21Page: Currently selected page object22"""2324class Page:25"""26Configure a page for st.navigation in a multipage app.2728Parameters:29- page: Callable function or file path for the page30- title (str): Page title (optional, inferred from function name or filename)31- icon (str): Page icon (emoji or icon name)32- url_path (str): Custom URL path for the page33- default (bool): Whether this is the default page34"""35def __init__(self, page, title=None, icon=None, url_path=None, default=False):36pass37```3839### Fragments4041Create independently rerunning code sections for improved performance.4243```python { .api }44def fragment(func=None, *, run_every=None, rerun_on_update=True):45"""46Turn a function into a fragment that can rerun independently of the main app.4748Parameters:49- func (callable): Function to turn into a fragment50- run_every (float): Auto-rerun interval in seconds51- rerun_on_update (bool): Rerun fragment when its state changes5253Returns:54callable: Fragment function decorator55"""56```5758### Dialog Modals5960Create modal dialog overlays for focused user interactions.6162```python { .api }63def dialog(title, *, width="large"):64"""65Create a modal dialog overlay.6667Parameters:68- title (str): Dialog title69- width (str): Dialog width ('small', 'medium', 'large')7071Returns:72ContextManager: Dialog context manager73"""74```7576### Authentication7778User authentication and session management.7980```python { .api }81def login(user_info_provider=None, **kwargs):82"""83Display a login widget and authenticate the user.8485Parameters:86- user_info_provider: Custom user information provider87- **kwargs: Additional authentication configuration8889Returns:90bool: True if login was successful91"""9293def logout(button_text="Logout"):94"""95Display a logout button.9697Parameters:98- button_text (str): Text for the logout button99100Returns:101bool: True if logout button was clicked102"""103104# User information proxy105user: UserInfoProxy106```107108### Data Connections109110Connect to external data sources and databases.111112```python { .api }113def connection(name, type=None, **kwargs):114"""115Create or retrieve a connection to a data source.116117Parameters:118- name (str): Connection name119- type (str): Connection type ('sql', 'snowflake', etc.)120- **kwargs: Connection-specific configuration parameters121122Returns:123BaseConnection: Connection object124"""125```126127### Connection Classes128129Base classes for creating custom data connections.130131```python { .api }132class BaseConnection:133"""Base class for creating data connections."""134135def query(self, query, **kwargs):136"""Execute a query against the connection."""137pass138139def reset(self):140"""Reset the connection."""141pass142143class SQLConnection(BaseConnection):144"""Connection for SQL databases."""145146def query(self, query, params=None, ttl=None, **kwargs):147"""Execute SQL query with optional caching."""148pass149150class SnowflakeConnection(BaseConnection):151"""Connection for Snowflake data warehouse."""152153def query(self, query, params=None, ttl=None, **kwargs):154"""Execute Snowflake query."""155pass156157def write_pandas(self, df, table_name, **kwargs):158"""Write pandas DataFrame to Snowflake."""159pass160161class SnowparkConnection(BaseConnection):162"""Connection for Snowpark operations."""163164def session(self):165"""Get Snowpark session."""166pass167```168169### Custom Components170171Integration with custom HTML/JavaScript components.172173```python { .api }174# Access via st.components.v1175def declare_component(name, path=None, url=None):176"""177Create and register a custom component.178179Parameters:180- name (str): Component name181- path (str): Local component directory path182- url (str): URL to hosted component183184Returns:185callable: Component function186"""187188def html(html, width=None, height=None, scrolling=False):189"""190Render arbitrary HTML in an iframe.191192Parameters:193- html (str): HTML content to render194- width (int): iframe width in pixels195- height (int): iframe height in pixels196- scrolling (bool): Enable scrolling197198Returns:199Any: Component return value200"""201202def iframe(src, width=None, height=None, scrolling=False):203"""204Render an iframe with specified source.205206Parameters:207- src (str): iframe source URL208- width (int): iframe width in pixels209- height (int): iframe height in pixels210- scrolling (bool): Enable scrolling211212Returns:213Any: Component return value214"""215```216217### Chat Interface218219Specialized widgets for building chat applications.220221```python { .api }222def chat_message(name, avatar=None):223"""224Insert a chat message container.225226Parameters:227- name (str): Message sender name228- avatar (str): Avatar image URL or emoji229230Returns:231ContextManager: Chat message context manager232"""233234def chat_input(placeholder=None, disabled=False, key=None, max_chars=None, on_submit=None, args=None, kwargs=None):235"""236Display a chat input widget at the bottom of the app.237238Parameters:239- placeholder (str): Placeholder text240- disabled (bool): Disable the input241- key (str): Unique key for the widget242- max_chars (int): Maximum character limit243- on_submit (callable): Function to call on message submit244- args (tuple): Arguments to pass to on_submit function245- kwargs (dict): Keyword arguments to pass to on_submit function246247Returns:248str or None: Submitted message text249"""250```251252## Usage Examples253254### Multi-page Navigation255256```python257import streamlit as st258259# Define page functions260def home_page():261st.title("π Home Page")262st.write("Welcome to the home page!")263264st.subheader("Quick Stats")265col1, col2, col3 = st.columns(3)266267with col1:268st.metric("Users", "1,234", "12%")269with col2:270st.metric("Revenue", "$56.7K", "8%")271with col3:272st.metric("Growth", "23%", "2%")273274def analytics_page():275st.title("π Analytics")276st.write("Analytics dashboard")277278import pandas as pd279import numpy as np280281# Sample chart282chart_data = pd.DataFrame(283np.random.randn(20, 3),284columns=['A', 'B', 'C']285)286st.line_chart(chart_data)287288def settings_page():289st.title("βοΈ Settings")290st.write("Application settings")291292theme = st.selectbox("Theme", ["Light", "Dark", "Auto"])293notifications = st.checkbox("Enable notifications", value=True)294language = st.selectbox("Language", ["English", "Spanish", "French"])295296if st.button("Save Settings"):297st.success("Settings saved!")298299# Configure pages300pages = [301st.Page(home_page, title="Home", icon="π ", default=True),302st.Page(analytics_page, title="Analytics", icon="π"),303st.Page(settings_page, title="Settings", icon="βοΈ")304]305306# Render navigation307current_page = st.navigation(pages)308current_page.run()309```310311### Fragment Usage312313```python314@st.fragment(run_every=5) # Auto-refresh every 5 seconds315def live_metrics():316"""Fragment that updates independently."""317import random318import time319320st.subheader("π Live Metrics (Auto-refreshing)")321322col1, col2, col3 = st.columns(3)323324with col1:325cpu_usage = random.randint(20, 80)326st.metric("CPU Usage", f"{cpu_usage}%", f"{random.randint(-5, 5)}%")327328with col2:329memory_usage = random.randint(40, 90)330st.metric("Memory", f"{memory_usage}%", f"{random.randint(-3, 3)}%")331332with col3:333active_users = random.randint(100, 500)334st.metric("Active Users", active_users, random.randint(-20, 50))335336st.caption(f"Last updated: {time.strftime('%H:%M:%S')}")337338@st.fragment339def user_feedback():340"""Independent feedback fragment."""341st.subheader("π¬ User Feedback")342343if 'feedback_messages' not in st.session_state:344st.session_state.feedback_messages = []345346# Feedback form347with st.form("feedback_form", clear_on_submit=True):348message = st.text_area("Your feedback:")349rating = st.slider("Rating:", 1, 5, 3)350351if st.form_submit_button("Submit Feedback"):352if message:353st.session_state.feedback_messages.append({354'message': message,355'rating': rating,356'timestamp': time.strftime('%H:%M:%S')357})358st.success("Thank you for your feedback!")359360# Display recent feedback361if st.session_state.feedback_messages:362st.write("**Recent Feedback:**")363for feedback in st.session_state.feedback_messages[-3:]:364with st.expander(f"Rating: {feedback['rating']}/5 - {feedback['timestamp']}"):365st.write(feedback['message'])366367# Use fragments368st.title("Fragment Demo")369370# These fragments update independently371live_metrics()372st.divider()373user_feedback()374375# Regular content (reruns with main app)376st.subheader("π Main App Content")377st.write("This content reruns with the main app.")378if st.button("Refresh Main App"):379st.success("Main app refreshed!")380```381382### Dialog Modals383384```python385# Dialog for user confirmation386@st.dialog("Confirm Delete")387def confirm_delete_dialog(item_name):388st.write(f"Are you sure you want to delete **{item_name}**?")389st.warning("This action cannot be undone!")390391col1, col2 = st.columns(2)392393with col1:394if st.button("Cancel", use_container_width=True):395st.rerun()396397with col2:398if st.button("Delete", type="primary", use_container_width=True):399st.session_state.deleted_item = item_name400st.rerun()401402# Dialog for data input403@st.dialog("Add New Item", width="medium")404def add_item_dialog():405st.write("Enter item details:")406407name = st.text_input("Item name:")408category = st.selectbox("Category:", ["Electronics", "Books", "Clothing"])409price = st.number_input("Price:", min_value=0.01, format="%.2f")410description = st.text_area("Description:")411412col1, col2 = st.columns(2)413414with col1:415if st.button("Cancel", use_container_width=True):416st.rerun()417418with col2:419if st.button("Add Item", type="primary", use_container_width=True):420if name and price:421if 'items' not in st.session_state:422st.session_state.items = []423424st.session_state.items.append({425'name': name,426'category': category,427'price': price,428'description': description429})430st.rerun()431else:432st.error("Please fill in required fields")433434# Main interface435st.title("Dialog Demo")436437# Items list438if 'items' not in st.session_state:439st.session_state.items = [440{'name': 'Laptop', 'category': 'Electronics', 'price': 999.99, 'description': 'Gaming laptop'},441{'name': 'Book', 'category': 'Books', 'price': 19.99, 'description': 'Programming guide'}442]443444# Add item button445if st.button("β Add Item"):446add_item_dialog()447448# Display items449st.subheader("Items")450for i, item in enumerate(st.session_state.items):451col1, col2, col3, col4 = st.columns([2, 1, 1, 1])452453with col1:454st.write(f"**{item['name']}**")455st.caption(item['description'])456457with col2:458st.write(item['category'])459460with col3:461st.write(f"${item['price']:.2f}")462463with col4:464if st.button("ποΈ", key=f"delete_{i}", help="Delete item"):465confirm_delete_dialog(item['name'])466467# Handle deletion468if 'deleted_item' in st.session_state:469st.session_state.items = [470item for item in st.session_state.items471if item['name'] != st.session_state.deleted_item472]473st.success(f"Deleted {st.session_state.deleted_item}")474del st.session_state.deleted_item475st.rerun()476```477478### Authentication479480```python481# Basic authentication example482if 'authenticated' not in st.session_state:483st.session_state.authenticated = False484485if not st.session_state.authenticated:486st.title("π Login Required")487488# Simple login form489with st.form("login_form"):490username = st.text_input("Username:")491password = st.text_input("Password:", type="password")492493if st.form_submit_button("Login"):494# Simple authentication (replace with real auth)495if username == "admin" and password == "password":496st.session_state.authenticated = True497st.session_state.username = username498st.success("Login successful!")499st.rerun()500else:501st.error("Invalid credentials")502else:503# Authenticated content504col1, col2 = st.columns([3, 1])505506with col1:507st.title(f"Welcome, {st.session_state.username}!")508509with col2:510if st.button("Logout"):511st.session_state.authenticated = False512del st.session_state.username513st.rerun()514515# Protected content516st.subheader("Protected Dashboard")517st.write("This content is only visible to authenticated users.")518519# Sample dashboard520col1, col2, col3 = st.columns(3)521522with col1:523st.metric("Total Sales", "$45,231", "12%")524with col2:525st.metric("New Users", "156", "8%")526with col3:527st.metric("Conversion Rate", "3.2%", "0.5%")528```529530### Chat Interface531532```python533# Initialize chat history534if 'chat_history' not in st.session_state:535st.session_state.chat_history = [536{"role": "assistant", "content": "Hello! How can I help you today?"}537]538539st.title("π¬ Chat Interface")540541# Display chat history542for message in st.session_state.chat_history:543with st.chat_message(message["role"]):544st.write(message["content"])545546# Chat input547if prompt := st.chat_input("Type your message here..."):548# Add user message to history549st.session_state.chat_history.append({"role": "user", "content": prompt})550551# Display user message552with st.chat_message("user"):553st.write(prompt)554555# Generate response (simulate AI response)556import random557responses = [558"That's an interesting question!",559"I understand what you're asking.",560"Let me help you with that.",561"That's a great point!",562"I see what you mean."563]564565response = random.choice(responses) + f" You said: '{prompt}'"566567# Add assistant response to history568st.session_state.chat_history.append({"role": "assistant", "content": response})569570# Display assistant response571with st.chat_message("assistant"):572st.write(response)573574# Chat controls575col1, col2 = st.columns([1, 1])576577with col1:578if st.button("Clear Chat"):579st.session_state.chat_history = [580{"role": "assistant", "content": "Hello! How can I help you today?"}581]582st.rerun()583584with col2:585if st.button("Export Chat"):586chat_text = "\n".join([587f"{msg['role'].title()}: {msg['content']}"588for msg in st.session_state.chat_history589])590st.download_button(591"Download Chat",592chat_text,593file_name="chat_history.txt",594mime="text/plain"595)596```597598### Custom Components599600```python601# HTML component example602st.subheader("Custom HTML Component")603604html_content = """605<div style="606background: linear-gradient(45deg, #FF6B6B, #4ECDC4);607padding: 20px;608border-radius: 10px;609color: white;610text-align: center;611font-family: Arial, sans-serif;612">613<h2>π¨ Custom HTML Widget</h2>614<p>This is a custom HTML component with styling!</p>615<button onclick="alert('Hello from custom component!')"616style="617background: white;618color: #333;619border: none;620padding: 10px 20px;621border-radius: 5px;622cursor: pointer;623">624Click Me!625</button>626</div>627"""628629st.components.v1.html(html_content, height=200)630631# Iframe component example632st.subheader("Embedded Content")633634# Embed external content635st.components.v1.iframe(636"https://www.openstreetmap.org/export/embed.html?bbox=-0.1,51.5,-0.05,51.52",637width=700,638height=400639)640```641642### Data Connections643644```python645# SQL Connection example (conceptual - requires actual database)646try:647# Create connection648conn = st.connection("my_database", type="sql", url="sqlite:///example.db")649650# Query with caching651@st.cache_data652def get_user_data():653return conn.query("SELECT * FROM users LIMIT 10")654655# Use connection656st.subheader("Database Connection")657data = get_user_data()658st.dataframe(data)659660except Exception as e:661st.info("Database connection example (requires actual database setup)")662st.code("""663# SQL Connection usage:664conn = st.connection("my_db", type="sql", url="postgresql://...")665data = conn.query("SELECT * FROM table", ttl=600)666""")667668# File-based connection example669st.subheader("File Connection Simulation")670671@st.cache_data672def load_sample_data():673import pandas as pd674import numpy as np675676# Simulate loading from external source677return pd.DataFrame({678'id': range(1, 101),679'name': [f'User_{i}' for i in range(1, 101)],680'value': np.random.randn(100),681'category': np.random.choice(['A', 'B', 'C'], 100)682})683684data = load_sample_data()685st.dataframe(data.head())686687# Connection refresh688if st.button("Refresh Data"):689st.cache_data.clear()690st.rerun()691```