- 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
advanced-features.md docs/
1# Advanced Features23Chat interfaces, app fragments, modal dialogs, and database connections for sophisticated applications. These features enable building complex, interactive applications with modern UI patterns.45## Capabilities67### Chat Interface89Build conversational interfaces and chatbots with built-in message containers and input handling.1011```python { .api }12def chat_message(name, *, avatar=None):13"""14Create chat message container with sender name and optional avatar.1516Args:17name (str): Name of the message sender18avatar (str, optional): Avatar image URL, emoji, or user type ("user", "assistant")1920Returns:21DeltaGenerator: Chat message container context manager22"""2324def chat_input(placeholder=None, key=None, max_chars=None, on_submit=None, args=None, kwargs=None, *, disabled=False):25"""26Display chat input widget for user message entry.2728Args:29placeholder (str, optional): Placeholder text when empty30key (str, optional): Unique widget key for state management31max_chars (int, optional): Maximum number of characters allowed32on_submit (callable, optional): Callback function when message is submitted33args (tuple, optional): Arguments for on_submit callback34kwargs (dict, optional): Keyword arguments for on_submit callback35disabled (bool): Whether input is disabled3637Returns:38str: Submitted message text or empty string if no submission39"""40```4142Example usage:43```python44# Initialize chat history in session state45if "messages" not in st.session_state:46st.session_state.messages = []4748# Display chat history49for message in st.session_state.messages:50with st.chat_message(message["role"], avatar=message.get("avatar")):51st.write(message["content"])5253# Chat input54user_input = st.chat_input("Type your message here...")5556if user_input:57# Add user message to history58st.session_state.messages.append({59"role": "user",60"content": user_input,61"avatar": "π§βπ»"62})6364# Display user message65with st.chat_message("user", avatar="π§βπ»"):66st.write(user_input)6768# Generate and display assistant response69response = generate_response(user_input) # Your AI logic here7071st.session_state.messages.append({72"role": "assistant",73"content": response,74"avatar": "π€"75})7677with st.chat_message("assistant", avatar="π€"):78st.write(response)79```8081### App Fragments8283Create reusable, independently updating app components for better performance and modularity.8485```python { .api }86def fragment(func):87"""88Decorator to create app fragment that can update independently.8990Args:91func (callable): Function to convert to fragment9293Returns:94callable: Fragment function that can be called with arguments95"""96```9798Example usage:99```python100@st.fragment101def live_metrics_fragment():102"""Fragment that updates metrics independently."""103col1, col2, col3 = st.columns(3)104105with col1:106cpu_usage = get_cpu_usage() # Real-time data107st.metric("CPU Usage", f"{cpu_usage}%")108109with col2:110memory_usage = get_memory_usage()111st.metric("Memory", f"{memory_usage}%")112113with col3:114active_users = get_active_users()115st.metric("Active Users", active_users)116117# Auto-refresh every 5 seconds118time.sleep(5)119st.rerun()120121@st.fragment122def data_table_fragment(data, filters):123"""Fragment for data table that updates based on filters."""124filtered_data = apply_filters(data, filters)125st.dataframe(filtered_data)126127if st.button("Export Data"):128export_data(filtered_data)129st.success("Data exported!")130131# Main app132st.title("Dashboard")133134# Independent fragments135live_metrics_fragment() # Updates independently136137# Fragment with parameters138data = load_data()139current_filters = st.selectbox("Filter by", ["All", "Active", "Inactive"])140data_table_fragment(data, current_filters)141```142143### Modal Dialogs144145Create modal dialog overlays for focused user interactions and confirmations.146147```python { .api }148def dialog(title, *, width="small"):149"""150Create modal dialog container that overlays the main content.151152Args:153title (str): Dialog title displayed in header154width (str): Dialog width ("small", "medium", "large")155156Returns:157DeltaGenerator: Dialog container context manager158"""159```160161Example usage:162```python163# Dialog trigger164if st.button("Open Settings"):165st.session_state.show_settings = True166167# Dialog content168if st.session_state.get("show_settings", False):169@st.dialog("Application Settings")170def settings_dialog():171st.write("Configure your application settings")172173# Settings form174theme = st.selectbox("Theme", ["Light", "Dark"])175notifications = st.checkbox("Enable notifications")176auto_save = st.checkbox("Auto-save changes")177178col1, col2 = st.columns(2)179with col1:180if st.button("Save", type="primary"):181save_settings(theme, notifications, auto_save)182st.session_state.show_settings = False183st.rerun()184185with col2:186if st.button("Cancel"):187st.session_state.show_settings = False188st.rerun()189190settings_dialog()191192# Confirmation dialog193if st.button("Delete Item"):194st.session_state.confirm_delete = True195196if st.session_state.get("confirm_delete", False):197@st.dialog("Confirm Deletion", width="medium")198def confirm_dialog():199st.warning("Are you sure you want to delete this item?")200st.write("This action cannot be undone.")201202col1, col2 = st.columns(2)203with col1:204if st.button("Delete", type="primary"):205delete_item()206st.session_state.confirm_delete = False207st.success("Item deleted!")208st.rerun()209210with col2:211if st.button("Cancel"):212st.session_state.confirm_delete = False213st.rerun()214215confirm_dialog()216```217218### Database Connections219220Streamlined database connectivity with built-in connection management and query capabilities.221222```python { .api }223def connection(name, type=None, **kwargs):224"""225Create or retrieve database connection with automatic management.226227Args:228name (str): Connection name for reuse229type (str, optional): Connection type ("sql", "snowflake", etc.)230**kwargs: Connection-specific parameters231232Returns:233Connection: Database connection object with query methods234"""235```236237Example usage:238```python239# SQL database connection240conn = st.connection("my_database", type="sql", url="sqlite:///data.db")241242# Execute query243@st.cache_data244def load_data():245return conn.query("SELECT * FROM users WHERE active = 1")246247data = load_data()248st.dataframe(data)249250# Snowflake connection251snow_conn = st.connection(252"snowflake_db",253type="snowflake",254account=st.secrets["snowflake"]["account"],255user=st.secrets["snowflake"]["user"],256password=st.secrets["snowflake"]["password"],257database="ANALYTICS",258schema="PUBLIC"259)260261# Query with parameters262@st.cache_data263def get_sales_data(start_date, end_date):264query = """265SELECT date, product, sales266FROM sales_data267WHERE date BETWEEN %s AND %s268ORDER BY date269"""270return snow_conn.query(query, params=(start_date, end_date))271272# Custom connection parameters273postgres_conn = st.connection(274"postgres",275type="sql",276url="postgresql://user:password@localhost/mydb",277engine_kwargs={278"pool_size": 10,279"pool_recycle": 3600280}281)282```283284### Advanced Application Patterns285286#### Real-time Chat Application287288```python289import time290from datetime import datetime291292# Initialize chat application293if "chat_history" not in st.session_state:294st.session_state.chat_history = []295st.session_state.user_name = ""296297# User setup298if not st.session_state.user_name:299st.session_state.user_name = st.text_input("Enter your name to start chatting:")300if not st.session_state.user_name:301st.stop()302303st.title(f"π¬ Chat - Welcome {st.session_state.user_name}!")304305# Chat history fragment (updates independently)306@st.fragment307def chat_history_fragment():308"""Display chat messages with real-time updates."""309chat_container = st.container(height=400, border=True)310311with chat_container:312for message in st.session_state.chat_history:313timestamp = message.get("timestamp", "")314with st.chat_message(message["role"], avatar=message["avatar"]):315st.write(f"**{message['name']}** - {timestamp}")316st.write(message["content"])317318# Display chat history319chat_history_fragment()320321# Message input322message = st.chat_input("Type your message...")323324if message:325# Add message to history326new_message = {327"role": "user",328"name": st.session_state.user_name,329"content": message,330"avatar": "π§βπ»",331"timestamp": datetime.now().strftime("%H:%M:%S")332}333334st.session_state.chat_history.append(new_message)335336# Simulate bot response337if message.lower().startswith("!bot"):338bot_response = generate_bot_response(message[5:]) # Remove "!bot "339bot_message = {340"role": "assistant",341"name": "ChatBot",342"content": bot_response,343"avatar": "π€",344"timestamp": datetime.now().strftime("%H:%M:%S")345}346st.session_state.chat_history.append(bot_message)347348st.rerun()349```350351#### Interactive Dashboard with Fragments352353```python354@st.fragment355def metric_cards_fragment():356"""Independent metrics that update frequently."""357col1, col2, col3, col4 = st.columns(4)358359with col1:360revenue = get_current_revenue()361st.metric("Revenue", f"${revenue:,.2f}", delta="12.5%")362363with col2:364users = get_active_users()365st.metric("Active Users", f"{users:,}", delta="5.2%")366367with col3:368conversion = get_conversion_rate()369st.metric("Conversion Rate", f"{conversion:.1f}%", delta="-1.2%")370371with col4:372satisfaction = get_satisfaction_score()373st.metric("Satisfaction", f"{satisfaction}/5", delta="0.3")374375@st.fragment376def interactive_chart_fragment(data, chart_type, filters):377"""Chart fragment that updates based on user selections."""378filtered_data = apply_dashboard_filters(data, filters)379380if chart_type == "Line":381st.line_chart(filtered_data)382elif chart_type == "Bar":383st.bar_chart(filtered_data)384elif chart_type == "Area":385st.area_chart(filtered_data)386387# Main dashboard388st.title("π Real-time Dashboard")389390# Independent metrics (updates every few seconds)391metric_cards_fragment()392393# Interactive controls394col1, col2 = st.columns([1, 3])395396with col1:397chart_type = st.selectbox("Chart Type", ["Line", "Bar", "Area"])398date_range = st.date_input("Date Range", value=[datetime.now() - timedelta(days=30), datetime.now()])399categories = st.multiselect("Categories", ["Sales", "Marketing", "Support"])400401with col2:402# Load data403dashboard_data = load_dashboard_data()404filters = {405"date_range": date_range,406"categories": categories407}408409# Interactive chart fragment410interactive_chart_fragment(dashboard_data, chart_type, filters)411```412413#### Modal-Based Workflows414415```python416# Workflow state management417workflow_states = {418"create_project": False,419"edit_item": None,420"confirm_action": None421}422423for state_key in workflow_states:424if state_key not in st.session_state:425st.session_state[state_key] = workflow_states[state_key]426427# Main interface428st.title("Project Management")429430# Action buttons431col1, col2, col3 = st.columns(3)432433with col1:434if st.button("β New Project", type="primary"):435st.session_state.create_project = True436437with col2:438if st.button("π Edit Selected"):439if selected_item := get_selected_item():440st.session_state.edit_item = selected_item441442with col3:443if st.button("ποΈ Delete Selected"):444if selected_item := get_selected_item():445st.session_state.confirm_action = f"delete_{selected_item['id']}"446447# Create Project Dialog448if st.session_state.create_project:449@st.dialog("Create New Project", width="large")450def create_project_dialog():451st.write("Enter project details:")452453project_name = st.text_input("Project Name*")454description = st.text_area("Description")455456col1, col2 = st.columns(2)457with col1:458start_date = st.date_input("Start Date")459priority = st.selectbox("Priority", ["Low", "Medium", "High"])460461with col2:462due_date = st.date_input("Due Date")463assignee = st.selectbox("Assignee", get_team_members())464465# Dialog actions466col1, col2 = st.columns(2)467with col1:468if st.button("Create Project", type="primary", disabled=not project_name):469create_new_project({470"name": project_name,471"description": description,472"start_date": start_date,473"due_date": due_date,474"priority": priority,475"assignee": assignee476})477st.session_state.create_project = False478st.success("Project created!")479st.rerun()480481with col2:482if st.button("Cancel"):483st.session_state.create_project = False484st.rerun()485486create_project_dialog()487488# Edit Item Dialog489if st.session_state.edit_item:490@st.dialog("Edit Item", width="medium")491def edit_item_dialog():492item = st.session_state.edit_item493st.write(f"Editing: {item['name']}")494495# Editable fields496new_name = st.text_input("Name", value=item['name'])497new_status = st.selectbox("Status", ["Active", "Completed", "On Hold"],498index=["Active", "Completed", "On Hold"].index(item['status']))499500# Save/Cancel actions501col1, col2 = st.columns(2)502with col1:503if st.button("Save Changes", type="primary"):504update_item(item['id'], {"name": new_name, "status": new_status})505st.session_state.edit_item = None506st.success("Item updated!")507st.rerun()508509with col2:510if st.button("Cancel"):511st.session_state.edit_item = None512st.rerun()513514edit_item_dialog()515516# Confirmation Dialog517if st.session_state.confirm_action:518@st.dialog("Confirm Action")519def confirmation_dialog():520action = st.session_state.confirm_action521522if action.startswith("delete_"):523item_id = action.split("_")[1]524st.warning(f"Are you sure you want to delete item {item_id}?")525st.write("This action cannot be undone.")526527col1, col2 = st.columns(2)528with col1:529if st.button("Confirm", type="primary"):530execute_action(action)531st.session_state.confirm_action = None532st.success("Action completed!")533st.rerun()534535with col2:536if st.button("Cancel"):537st.session_state.confirm_action = None538st.rerun()539540confirmation_dialog()541```