100% found this document useful (1 vote)
237 views39 pages

Complete Streamlit Guide

Uploaded by

Mabtoor Mabx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
237 views39 pages

Complete Streamlit Guide

Uploaded by

Mabtoor Mabx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Complete Streamlit Guide

Table of Contents
1. Streamlit and Its Importance
2. How to Install Streamlit

3. Basic Syntax of Streamlit


4. How to Run Streamlit Files in Windows

5. Main Built-in Functions


6. Widgets
7. Layouts

8. File Upload in Streamlit


9. Web Requests and APIs

10. Best Practices


11. Summary

1. Streamlit and Its Importance

What is Streamlit?
Streamlit is an open-source Python library that makes it easy to create and share beautiful, custom
web applications for machine learning and data science. It transforms Python scripts into interactive
web apps with minimal code.

Key Features:
Rapid Development: Build apps in pure Python without HTML, CSS, or JavaScript
Interactive Widgets: Built-in widgets for user input and interaction

Real-time Updates: Apps update automatically when code changes


Easy Deployment: Simple sharing and deployment options
Rich Media Support: Display charts, images, videos, and more

Importance of Streamlit:
Democratizes App Development: Enables data scientists to create web apps without web
development expertise

Rapid Prototyping: Quick iteration and testing of ideas


Data Visualization: Excellent for creating interactive dashboards
Machine Learning Deployment: Easy deployment of ML models
Collaboration: Share insights and models with stakeholders easily

Visual Diagram: Streamlit Architecture

┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐


│ Python Script │───▶│ Streamlit App │───▶│ Web Browser │
│ │ │ │ │ │
│ • Data Processing│ │ • Interactive UI │ │ • User Interface│
│ • ML Models │ │ • Widgets │ │ • Real-time │
│ • Visualizations│ │ • Layouts │ │ Updates │
└─────────────────┘ └──────────────────┘ └─────────────────┘

2. How to Install Streamlit

Installation Methods:

Method 1: Using pip (Recommended)

bash

pip install streamlit

Method 2: Using conda

bash

conda install -c conda-forge streamlit

Method 3: Install specific version

bash

pip install streamlit==1.28.0

Verify Installation:

bash

streamlit hello

System Requirements:
Python 3.8 or higher

pip or conda package manager


Modern web browser

3. Basic Syntax of Streamlit

Core Concepts:
Streamlit apps are Python scripts that run from top to bottom

Every time a user interacts with a widget, the entire script reruns
Use st. prefix for all Streamlit functions

Basic Structure:

python

import streamlit as st

# App title
[Link]("My First Streamlit App")

# Display text
[Link]("Hello, World!")

# Create a simple widget


name = st.text_input("Enter your name:")
if name:
[Link](f"Hello, {name}!")

Key Principles:
1. Import streamlit: Always start with import streamlit as st

2. Top-to-bottom execution: Code runs sequentially


3. Automatic rerun: App reruns when user interacts with widgets

4. State management: Use session state for persistent data

4. How to Run Streamlit Files in Windows

Step-by-Step Process:

Step 1: Save your Python file

python
# Save as: my_app.py
import streamlit as st

[Link]("My Streamlit App")


[Link]("This is my first app!")

Step 2: Open Command Prompt or PowerShell

Press Win + R , type cmd , press Enter

Or press Win + X , select "Windows PowerShell"

Step 3: Navigate to your file directory

bash

cd C:\path\to\your\file

Step 4: Run the Streamlit app

bash

streamlit run my_app.py

Step 5: Access the app

Browser will automatically open

Default URL: [Link]

Alternative Methods:

Using Python directly:

bash

python -m streamlit run my_app.py

Specifying port:

bash

streamlit run my_app.py --[Link] 8502

5. Main Built-in Functions


5.1 Title Function

python

[Link]("Main Application Title")

Purpose: Creates the main heading of your app

5.2 Header Function

python

[Link]("Section Header")

Purpose: Creates section headers (smaller than title)

5.3 Subheader Function

python

[Link]("Subsection Header")

Purpose: Creates subsection headers (smaller than header)

5.4 Text Function

python

[Link]("This is plain text")


[Link]("Line 1\nLine 2\nLine 3")

Purpose: Displays plain text with monospace font

5.5 Write Function

python
[Link]("This is markdown text")
[Link]("**Bold text** and *italic text*")
[Link]("Here's a list:")
[Link]("- Item 1")
[Link]("- Item 2")

# Write variables
data = {"name": "John", "age": 30}
[Link](data)

# Write dataframes
import pandas as pd
df = [Link]({"A": [1, 2, 3], "B": [4, 5, 6]})
[Link](df)

Purpose: Most versatile function - displays text, markdown, dataframes, charts, etc.

5.6 Success Function

python

[Link]("Operation completed successfully!")


[Link]("An error occurred!")
[Link]("This is a warning message")
[Link]("This is an info message")

Purpose: Display colored alert messages

Complete Example:

python
import streamlit as st
import pandas as pd

# Title and headers


[Link]("🎯 My Data Dashboard")
[Link]("Data Analysis Section")
[Link]("Sample Dataset")

# Text and write examples


[Link]("This is plain text")
[Link]("This is **markdown** text with formatting")

# Sample data
data = {
'Product': ['A', 'B', 'C', 'D'],
'Sales': [100, 150, 80, 200],
'Profit': [20, 30, 15, 40]
}
df = [Link](data)
[Link](df)

# Status messages
if [Link]("Process Data"):
[Link]("Data processed successfully!")
[Link]("Processing completed in 0.5 seconds")

6. Widgets

6.1 Button Widget

python

# Basic button
if [Link]("Click Me"):
[Link]("Button was clicked!")

# Button with key (for multiple buttons)


if [Link]("Submit", key="submit_btn"):
[Link]("Form submitted!")

6.2 Checkbox Widget

python
# Basic checkbox
agree = [Link]("I agree to terms and conditions")
if agree:
[Link]("Thank you for agreeing!")

# Checkbox with default value


debug_mode = [Link]("Enable debug mode", value=True)

6.3 Radio Button Widget

python

# Basic radio buttons


option = [Link](
"Choose your favorite color:",
("Red", "Green", "Blue")
)
[Link](f"You selected: {option}")

# Radio with horizontal layout


genre = [Link](
"Choose your favorite movie genre:",
("Comedy", "Drama", "Documentary"),
horizontal=True
)

6.4 Selectbox Widget

python

# Basic selectbox
option = [Link](
"Select a programming language:",
("Python", "Java", "C++", "JavaScript", "Go")
)
[Link](f"You selected: {option}")

# Selectbox with default index


cities = ["New York", "London", "Tokyo", "Paris"]
city = [Link]("Choose a city:", cities, index=2) # Tokyo selected by default

6.5 Slider Widget

python
# Number slider
age = [Link]("Select your age:", 0, 100, 25)
[Link](f"Your age: {age}")

# Range slider
values = [Link](
"Select a range of values:",
0.0, 100.0, (25.0, 75.0)
)
[Link](f"Range: {values[0]} to {values[1]}")

# Date slider
from datetime import datetime, date
start_date = [Link](
"Select date:",
value=datetime(2023, 1, 1),
min_value=datetime(2020, 1, 1),
max_value=datetime(2025, 12, 31),
format="MM/DD/YYYY"
)

6.6 Number Input Widget

python

# Integer input
number = st.number_input("Enter a number:", min_value=0, max_value=100, value=10, step=1)

# Float input
price = st.number_input("Enter price:", min_value=0.0, value=10.50, step=0.25, format="%.2f")

6.7 Text Input Widget

python

# Single line text input


name = st.text_input("Enter your name:", placeholder="Your name here")

# Password input
password = st.text_input("Enter password:", type="password")

# Text area for multi-line input


message = st.text_area("Enter your message:", height=100)

6.8 Date Input Widget


python

# Single date
birthday = st.date_input("Select your birthday:")

# Date range
from datetime import date
dates = st.date_input(
"Select date range:",
value=[date(2023, 1, 1), date(2023, 12, 31)],
min_value=date(2020, 1, 1),
max_value=date(2025, 12, 31)
)

Complete Widget Example:

python
import streamlit as st
from datetime import date

[Link]("🎛️ Widget Showcase")

# Form with multiple widgets


with [Link]("user_form"):
[Link]("User Information")

name = st.text_input("Full Name:")


age = [Link]("Age:", 18, 100, 25)
email = st.text_input("Email:", type="default")

favorite_color = [Link]("Favorite Color:", ("Red", "Blue", "Green"))

programming_languages = [Link](
"Programming Languages:",
["Python", "JavaScript", "Java", "C++", "Go", "Rust"]
)

experience = [Link]("Experience Level:",


["Beginner", "Intermediate", "Advanced", "Expert"])

subscribe = [Link]("Subscribe to newsletter")

submitted = st.form_submit_button("Submit")

if submitted:
[Link]("Form submitted successfully!")
[Link]({
"name": name,
"age": age,
"email": email,
"favorite_color": favorite_color,
"languages": programming_languages,
"experience": experience,
"subscribe": subscribe
})

7. Layouts

7.1 Columns Layout

python
# Create columns
col1, col2, col3 = [Link](3)

with col1:
[Link]("Column 1")
[Link]("Content for column 1")

with col2:
[Link]("Column 2")
[Link]("Content for column 2")

with col3:
[Link]("Column 3")
[Link]("Content for column 3")

# Columns with different widths


col1, col2 = [Link]([2, 1]) # col1 is twice as wide as col2

7.2 Sidebar Layout

python

# Add content to sidebar


[Link]("Navigation")
[Link]("This is in the sidebar")

# Sidebar widgets
page = [Link]("Choose a page:", ["Home", "About", "Contact"])
[Link]("Adjust parameter:", 0, 100, 50)

# Main content
[Link]("Main Content Area")
[Link](f"Current page: {page}")

7.3 Expander Layout

python
# Basic expander
with [Link]("Click to expand"):
[Link]("This content is hidden by default")
[Link]("[Link]

# Expander with custom label and expanded state


with [Link]("Advanced Settings", expanded=True):
debug = [Link]("Debug mode")
log_level = [Link]("Log level:", ["INFO", "DEBUG", "ERROR"])

7.4 Container Layout

python

# Use container for grouping


container = [Link]()
[Link]("This is inside the container")

# Empty container for later use


placeholder = [Link]()
# Later in code:
[Link]("Content added later")

7.5 Tabs Layout

python

tab1, tab2, tab3 = [Link](["Data", "Charts", "Settings"])

with tab1:
[Link]("Data Tab")
[Link]("Display your data here")

with tab2:
[Link]("Charts Tab")
[Link]("Display your charts here")

with tab3:
[Link]("Settings Tab")
[Link]("App settings here")

7.6 Image Display

python
# Display image from URL
[Link]("[Link] caption="Sample Image")

# Display local image


[Link]("path/to/local/[Link]", width=300)

# Display multiple images


col1, col2, col3 = [Link](3)
with col1:
[Link]("[Link]", caption="Image 1")
with col2:
[Link]("[Link]", caption="Image 2")
with col3:
[Link]("[Link]", caption="Image 3")

7.7 Markdown

python

# Basic markdown
[Link]("# This is a header")
[Link]("**Bold text** and *italic text*")
[Link]("[Link to Google]([Link]

# Markdown with HTML


[Link]("""
<div style="background-color: #f0f0f0; padding: 10px; border-radius: 5px;">
<h3>Custom Styled Content</h3>
<p>This uses HTML within markdown</p>
</div>
""", unsafe_allow_html=True)

# Code blocks
[Link]("""
```python
def hello_world():
print("Hello, World!")

""")
### Complete Layout Example:
```python
import streamlit as st
import pandas as pd
import numpy as np

[Link]("📊 Advanced Layout Dashboard")

# Sidebar
[Link]("Dashboard Controls")
chart_type = [Link]("Chart Type:", ["Line", "Bar", "Area"])
data_points = [Link]("Data Points:", 10, 100, 50)

# Main content with tabs


tab1, tab2, tab3 = [Link](["📈 Data Visualization", "📋 Data Table", "⚙️ Settings"])

# Generate sample data


data = [Link]({
'x': range(data_points),
'y': [Link](data_points).cumsum()
})

with tab1:
col1, col2 = [Link]([3, 1])

with col1:
if chart_type == "Line":
st.line_chart(data.set_index('x'))
elif chart_type == "Bar":
st.bar_chart(data.set_index('x'))
else:
st.area_chart(data.set_index('x'))

with col2:
[Link]("Data Points", data_points)
[Link]("Max Value", f"{data['y'].max():.2f}")
[Link]("Min Value", f"{data['y'].min():.2f}")

with tab2:
[Link](data, use_container_width=True)

with [Link]("Data Statistics"):


[Link]([Link]())

with tab3:
[Link]("Application Settings")
theme = [Link]("Theme:", ["Light", "Dark", "Auto"])
auto_refresh = [Link]("Auto-refresh data")
refresh_interval = st.number_input("Refresh interval (seconds):", 1, 60, 5)

8. File Upload in Streamlit

8.1 Basic File Upload

python

uploaded_file = st.file_uploader("Choose a file")


if uploaded_file is not None:
# Display file details
[Link]("Filename:", uploaded_file.name)
[Link]("File size:", uploaded_file.size, "bytes")
[Link]("File type:", uploaded_file.type)

8.2 Specific File Types

python

# Upload CSV files only


csv_file = st.file_uploader("Upload CSV file", type=['csv'])
if csv_file is not None:
df = pd.read_csv(csv_file)
[Link](df)

# Upload image files


image_file = st.file_uploader("Upload an image", type=['png', 'jpg', 'jpeg', 'gif'])
if image_file is not None:
[Link](image_file, caption="Uploaded Image")

# Upload multiple file types


data_file = st.file_uploader(
"Upload data file",
type=['csv', 'xlsx', 'json', 'txt']
)

8.3 Multiple File Upload

python
uploaded_files = st.file_uploader(
"Choose multiple files",
accept_multiple_files=True,
type=['csv', 'xlsx']
)

if uploaded_files:
for uploaded_file in uploaded_files:
[Link](f"Processing: {uploaded_file.name}")
# Process each file
if uploaded_file.[Link]('.csv'):
df = pd.read_csv(uploaded_file)
[Link]([Link]())

8.4 Advanced File Processing

python
import streamlit as st
import pandas as pd
import json
from PIL import Image
import io

[Link]("📁 Advanced File Upload")

uploaded_file = st.file_uploader(
"Upload your file",
type=['csv', 'xlsx', 'json', 'txt', 'png', 'jpg', 'jpeg']
)

if uploaded_file is not None:


file_details = {
"filename": uploaded_file.name,
"filetype": uploaded_file.type,
"filesize": uploaded_file.size
}
[Link](file_details)

# Process based on file type


if uploaded_file.type == "text/csv":
df = pd.read_csv(uploaded_file)
[Link]("CSV Data Preview")
[Link]([Link]())
[Link](f"Shape: {[Link]}")

# Download processed data


csv = df.to_csv(index=False)
st.download_button(
label="Download processed CSV",
data=csv,
file_name="processed_data.csv",
mime="text/csv"
)

elif uploaded_file.type in ["image/png", "image/jpeg", "image/jpg"]:


image = [Link](uploaded_file)
[Link]("Image Preview")
[Link](image, caption="Uploaded Image")
[Link](f"Image size: {[Link]}")
[Link](f"Image mode: {[Link]}")

elif uploaded_file.type == "application/json":


json_data = [Link](uploaded_file)
[Link]("JSON Data")
[Link](json_data)

else:
# Text files
string_data = uploaded_file.read().decode("utf-8")
[Link]("File Content")
st.text_area("Content:", string_data, height=200)

8.5 File Upload with Progress Bar

python

import time

uploaded_file = st.file_uploader("Upload large file")


if uploaded_file is not None:
# Simulate processing with progress bar
progress_bar = [Link](0)
status_text = [Link]()

for i in range(100):
progress_bar.progress(i + 1)
status_text.text(f'Processing... {i+1}%')
[Link](0.01) # Simulate processing time

status_text.text('Processing complete!')
[Link]("File processed successfully!")

9. Web Requests and APIs

9.1 Making HTTP Requests

python
import streamlit as st
import requests
import json

[Link]("🌐 API Integration")

# Simple GET request


if [Link]("Fetch Random Quote"):
response = [Link]("[Link]
if response.status_code == 200:
quote_data = [Link]()
[Link](f"**Quote:** {quote_data['content']}")
[Link](f"**Author:** {quote_data['author']}")
else:
[Link]("Failed to fetch quote")

9.2 API with Parameters

python

# Weather API example (conceptual)


[Link]("Weather Information")
city = st.text_input("Enter city name:")

if city and [Link]("Get Weather"):


# Note: Replace with actual API key and endpoint
api_key = "your_api_key_here"
url = f"[Link]
params = {
"q": city,
"appid": api_key,
"units": "metric"
}

try:
response = [Link](url, params=params)
if response.status_code == 200:
weather_data = [Link]()
[Link](f"Weather in {city}")
[Link](f"Temperature: {weather_data['main']['temp']}°C")
[Link](f"Description: {weather_data['weather'][0]['description']}")
else:
[Link]("City not found or API error")
except Exception as e:
[Link](f"Error: {str(e)}")
9.3 REST API with Different Methods

python
import streamlit as st
import requests
import json

[Link]("🔄 REST API Demo")

# API Base URL


base_url = "[Link]

# GET Request
[Link]("GET Request - Fetch Posts")
if [Link]("Fetch Posts"):
response = [Link](f"{base_url}/posts")
if response.status_code == 200:
posts = [Link]()[:5] # Show first 5 posts
for post in posts:
with [Link](f"Post {post['id']}: {post['title'][:50]}..."):
[Link](f"**User ID:** {post['userId']}")
[Link](f"**Title:** {post['title']}")
[Link](f"**Body:** {post['body']}")

# POST Request
[Link]("POST Request - Create Post")
with [Link]("create_post"):
user_id = st.number_input("User ID:", min_value=1, value=1)
title = st.text_input("Post Title:")
body = st.text_area("Post Body:")

if st.form_submit_button("Create Post"):
post_data = {
"userId": user_id,
"title": title,
"body": body
}

response = [Link](f"{base_url}/posts", json=post_data)


if response.status_code == 201:
[Link]("Post created successfully!")
[Link]([Link]())
else:
[Link]("Failed to create post")

# API with Authentication (example)


[Link]("API with Headers")
api_key = st.text_input("Enter API Key:", type="password")
if api_key and [Link]("Make Authenticated Request"):
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}

# Example request with headers


try:
response = [Link](
"[Link]
headers=headers
)
if response.status_code == 200:
user_data = [Link]()
[Link]("Authenticated successfully!")
[Link](f"Username: {user_data.get('login', 'N/A')}")
[Link](f"Name: {user_data.get('name', 'N/A')}")
else:
[Link]("Authentication failed")
except Exception as e:
[Link](f"Error: {str(e)}")

9.4 Caching API Responses

python
import streamlit as st
import requests
import time

@st.cache_data(ttl=300) # Cache for 5 minutes


def fetch_api_data(url):
"""Fetch data from API with caching"""
response = [Link](url)
return [Link]() if response.status_code == 200 else None

[Link]("📊 Cached API Data")

# This will only make API call once every 5 minutes


if [Link]("Fetch Cached Data"):
with [Link]("Fetching data..."):
data = fetch_api_data("[Link]
if data:
[Link]("Data fetched (cached for 5 minutes)")
[Link](data[:3]) # Show first 3 users
else:
[Link]("Failed to fetch data")

9.5 Complete API Integration Example

python
import streamlit as st
import requests
import pandas as pd
import [Link] as px

[Link]("🚀 Complete API Integration")

# Sidebar for API selection


[Link]("API Selection")
api_choice = [Link](
"Choose API:",
["JSONPlaceholder", "Random User", "Cat Facts"]
)

if api_choice == "JSONPlaceholder":
resource = [Link]("Select resource:", ["posts", "users", "comments"])

if [Link](f"Fetch {[Link]()}"):
with [Link]("Loading..."):
response = [Link](f"[Link]
if response.status_code == 200:
data = [Link]()
df = [Link](data)

[Link](f"Fetched {len(data)} {resource}")


[Link]([Link](10))

# Download option
csv = df.to_csv(index=False)
st.download_button(
label=f"Download {resource} CSV",
data=csv,
file_name=f"{resource}.csv",
mime="text/csv"
)

elif api_choice == "Random User":


num_users = [Link]("Number of users:", 1, 20, 5)

if [Link]("Generate Random Users"):


with [Link]("Generating users..."):
response = [Link](f"[Link]
if response.status_code == 200:
data = [Link]()
users = data['results']
for i, user in enumerate(users):
col1, col2 = [Link]([1, 3])
with col1:
[Link](user['picture']['large'])
with col2:
[Link](f"**Name:** {user['name']['first']} {user['name']['last']}")
[Link](f"**Email:** {user['email']}")
[Link](f"**Location:** {user['location']['city']}, {user['location']['country']}")

else: # Cat Facts


if [Link]("Get Random Cat Fact"):
response = [Link]("[Link]
if response.status_code == 200:
fact = [Link]()
[Link](f"🐱 {fact['fact']}")
[Link](f"Fact length: {fact['length']} characters")

10. Best Practices

10.1 Performance Best Practices

Use Caching

python

@st.cache_data
def load_data():
# Expensive data loading operation
return pd.read_csv("large_dataset.csv")

@st.cache_resource
def init_model():
# Load ML model (singleton resource)
return [Link]("[Link]")

Optimize Widget Usage

python
# Good: Use session state for expensive operations
if 'processed_data' not in st.session_state:
st.session_state.processed_data = expensive_processing()

# Good: Use forms to batch widget interactions


with [Link]("my_form"):
name = st.text_input("Name")
age = st.number_input("Age")
submitted = st.form_submit_button("Submit")

if submitted:
process_form_data(name, age)

10.2 Code Organization

Modular Structure

python

# [Link]
def load_data():
return pd.read_csv("[Link]")

def preprocess_data(df):
# Data preprocessing logic
return df

# main_app.py
import streamlit as st
from utils import load_data, preprocess_data

def main():
[Link]("My App")
data = load_data()
processed_data = preprocess_data(data)
[Link](processed_data)

if __name__ == "__main__":
main()

Configuration Management

python
# [Link]
class Config:
APP_TITLE = "My Streamlit App"
DEFAULT_THEME = "light"
API_BASE_URL = "[Link]

# [Link]
from config import Config

[Link](Config.APP_TITLE)

10.3 User Experience Best Practices

Loading States

python

# Show loading spinner


with [Link]("Processing data..."):
result = expensive_operation()

# Progress bar for long operations


progress_bar = [Link](0)
for i in range(100):
[Link](0.01)
progress_bar.progress(i + 1)

Error Handling

python

try:
data = load_external_data()
[Link]("Data loaded successfully!")
except FileNotFoundError:
[Link]("Data file not found. Please upload a file.")
except Exception as e:
[Link](f"An unexpected error occurred: {str(e)}")
[Link]("Please try again or contact support.")

Input Validation

python
email = st.text_input("Enter your email:")
if email:
if "@" not in email:
[Link]("Please enter a valid email address")
else:
[Link]("Email format is valid")

age = st.number_input("Enter your age:", min_value=0, max_value=150)


if age < 18:
[Link]("You must be 18 or older to proceed")

10.4 Security Best Practices

Environment Variables

python

import os
import streamlit as st

# Use environment variables for sensitive data


API_KEY = [Link]("API_KEY")
if not API_KEY:
[Link]("API key not found. Please set the API_KEY environment variable.")
[Link]()

# Secure API calls


headers = {"Authorization": f"Bearer {API_KEY}"}

Input Sanitization

python

import re

user_input = st.text_input("Enter username:")


if user_input:
# Sanitize input
if [Link]("^[a-zA-Z0-9_]+$", user_input):
[Link]("Valid username")
else:
[Link]("Username can only contain letters, numbers, and underscores")

10.5 State Management Best Practices

Session State Usage


python

# Initialize session state


if 'counter' not in st.session_state:
st.session_state.counter = 0

# Update session state


if [Link]("Increment"):
st.session_state.counter += 1

[Link](f"Counter: {st.session_state.counter}")

# Complex state management


if 'user_data' not in st.session_state:
st.session_state.user_data = {
'name': '',
'preferences': [],
'history': []
}

10.6 Deployment Best Practices

[Link]

txt

streamlit>=1.28.0
pandas>=1.5.0
plotly>=5.0.0
requests>=2.28.0
pillow>=9.0.0

Configuration Files

toml
# .streamlit/[Link]
[theme]
primaryColor = "#FF6B6B"
backgroundColor = "#FFFFFF"
secondaryBackgroundColor = "#F0F2F6"
textColor = "#262730"

[server]
port = 8501
enableCORS = false
enableXsrfProtection = true

10.7 Testing Best Practices

Unit Testing

python

# test_app.py
import pytest
from app import process_data, validate_input

def test_process_data():
sample_data = [1, 2, 3, 4, 5]
result = process_data(sample_data)
assert len(result) == 5
assert all(isinstance(x, int) for x in result)

def test_validate_input():
assert validate_input("valid@[Link]") == True
assert validate_input("invalid-email") == False

10.8 Complete Best Practices Example

python
import streamlit as st
import pandas as pd
import logging
import os
from typing import Optional
import time

# Configure logging
[Link](level=[Link])
logger = [Link](__name__)

# Configuration
class AppConfig:
TITLE = "📊 Professional Streamlit App"
MAX_FILE_SIZE = 200 * 1024 * 1024 # 200MB
ALLOWED_EXTENSIONS = ['csv', 'xlsx', 'json']
CACHE_TTL = 3600 # 1 hour

@st.cache_data(ttl=AppConfig.CACHE_TTL)
def load_data(file_path: str) -> Optional[[Link]]:
"""Load data with caching and error handling"""
try:
if file_path.endswith('.csv'):
return pd.read_csv(file_path)
elif file_path.endswith('.xlsx'):
return pd.read_excel(file_path)
else:
raise ValueError("Unsupported file format")
except Exception as e:
[Link](f"Error loading data: {str(e)}")
return None

def validate_dataframe(df: [Link]) -> bool:


"""Validate dataframe structure"""
if df is None or [Link]:
return False

required_columns = ['id', 'name', 'value']


return all(col in [Link] for col in required_columns)

def main():
# Page configuration
st.set_page_config(
page_title=[Link],
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded"
)

# Initialize session state


if 'processed_data' not in st.session_state:
st.session_state.processed_data = None
if 'processing_complete' not in st.session_state:
st.session_state.processing_complete = False

# App header
[Link]([Link])
[Link]("---")

# Sidebar
with [Link]:
[Link]("🔧 Configuration")

# File upload with validation


uploaded_file = st.file_uploader(
"Upload your data file",
type=AppConfig.ALLOWED_EXTENSIONS,
help=f"Maximum file size: {AppConfig.MAX_FILE_SIZE // (1024*1024)}MB"
)

if uploaded_file:
if uploaded_file.size > AppConfig.MAX_FILE_SIZE:
[Link]("File size exceeds maximum limit")
return

# Processing options
[Link]("Processing Options")
remove_nulls = [Link]("Remove null values", value=True)
normalize_data = [Link]("Normalize data")

if [Link]("Process Data", type="primary"):


with [Link]("Processing data..."):
try:
# Save uploaded file temporarily
temp_file = f"temp_{uploaded_file.name}"
with open(temp_file, "wb") as f:
[Link](uploaded_file.getbuffer())

# Load and validate data


df = load_data(temp_file)

if df is not None and validate_dataframe(df):


# Process data based on options
if remove_nulls:
df = [Link]()

if normalize_data:
numeric_columns = df.select_dtypes(include=['number']).columns
df[numeric_columns] = (df[numeric_columns] - df[numeric_columns].mean()) / df[numeric_co

st.session_state.processed_data = df
st.session_state.processing_complete = True
[Link]("Data processed successfully!")

else:
[Link]("Invalid data format or structure")

# Clean up temp file


[Link](temp_file)

except Exception as e:
[Link](f"Processing failed: {str(e)}")
[Link](f"Data processing error: {str(e)}")

# Main content area


if st.session_state.processing_complete and st.session_state.processed_data is not None:
df = st.session_state.processed_data

# Display metrics
col1, col2, col3, col4 = [Link](4)
with col1:
[Link]("Total Rows", len(df))
with col2:
[Link]("Total Columns", len([Link]))
with col3:
[Link]("Memory Usage", f"{df.memory_usage(deep=True).sum() / 1024**2:.2f} MB")
with col4:
[Link]("Null Values", [Link]().sum().sum())

# Data preview
[Link]("📋 Data Preview")
[Link]([Link](100), use_container_width=True)

# Data analysis tabs


tab1, tab2, tab3 = [Link](["📊 Summary", "📈 Visualizations", "⬇️ Export"])

with tab1:
[Link]("Statistical Summary")
[Link]([Link]())
# Data types
[Link]("Data Types")
dtype_df = [Link]({
'Column': [Link],
'Data Type': [Link],
'Non-Null Count': [Link](),
'Null Count': [Link]().sum()
})
[Link](dtype_df)

with tab2:
if len(df.select_dtypes(include=['number']).columns) > 0:
numeric_columns = df.select_dtypes(include=['number']).[Link]()

selected_column = [Link]("Select column for visualization:", numeric_columns)

col1, col2 = [Link](2)


with col1:
[Link]("Histogram")
st.bar_chart(df[selected_column].value_counts().head(20))

with col2:
[Link]("Box Plot")
[Link]("Box plot data:")
[Link](df[selected_column].describe())
else:
[Link]("No numeric columns available for visualization")

with tab3:
[Link]("Export Processed Data")

col1, col2 = [Link](2)

with col1:
csv = df.to_csv(index=False)
st.download_button(
label="📥 Download as CSV",
data=csv,
file_name="processed_data.csv",
mime="text/csv"
)

with col2:
# Convert to Excel
from io import BytesIO
buffer = BytesIO()
with [Link](buffer, engine='openpyxl') as writer:
df.to_excel(writer, sheet_name='Processed Data', index=False)

st.download_button(
label="📥 Download as Excel",
data=[Link](),
file_name="processed_data.xlsx",
mime="application/[Link]"
)

else:
# Welcome message
[Link]("👆 Please upload a data file using the sidebar to get started")

# Feature showcase
[Link]("🚀 Features")
feature_cols = [Link](3)

with feature_cols[0]:
[Link]("**📊 Data Processing**")
[Link]("- Remove null values")
[Link]("- Normalize data")
[Link]("- Statistical analysis")

with feature_cols[1]:
[Link]("**📈 Visualizations**")
[Link]("- Interactive charts")
[Link]("- Data distributions")
[Link]("- Summary statistics")

with feature_cols[2]:
[Link]("**⬇️ Export Options**")
[Link]("- CSV format")
[Link]("- Excel format")
[Link]("- Processed data")

if __name__ == "__main__":
main()

11. Summary

Key Takeaways
Streamlit is a powerful, user-friendly framework for creating data applications with minimal code.
Here are the essential points covered in this guide:
Core Concepts

Simple Syntax: Use st. prefix for all Streamlit functions


Reactive Model: Apps rerun from top to bottom on user interaction

No Web Development Required: Pure Python approach to web apps

Essential Components

Display Functions:

[Link]() , [Link]() , [Link]() for headings

[Link]() for versatile content display

[Link]() for plain text

Status messages: [Link]() , [Link]() , [Link]() , [Link]()

Interactive Widgets:

Input: st.text_input() , st.number_input() , st.date_input()


Selection: [Link]() , [Link]() , [Link]()
Controls: [Link]() , [Link]()

Layout Options:

[Link]() for side-by-side content

[Link] for navigation panels

[Link]() for tabbed interfaces

[Link]() for collapsible sections

Advanced Features

File Upload: Support for various file types with st.file_uploader()


API Integration: HTTP requests with caching using @st.cache_data

State Management: Persistent data with st.session_state


Performance: Caching with @st.cache_data and @st.cache_resource

Best Practices Summary

1. Performance
Use caching for expensive operations
Implement proper state management

Use forms to batch widget interactions

2. Code Organization
Structure code modularly
Use configuration files

Implement proper error handling

3. User Experience
Provide loading indicators

Validate user inputs


Handle errors gracefully

4. Security
Use environment variables for sensitive data

Sanitize user inputs


Implement proper authentication

5. Deployment
Create proper [Link]
Configure app settings

Test thoroughly before deployment

Common Use Cases

Data Dashboards: Interactive data visualization and analysis

Machine Learning: Model deployment and demonstration


Prototyping: Rapid application development
Reports: Dynamic, interactive reporting tools

APIs: Frontend interfaces for backend services

Getting Started Checklist

1. ✅ Install Streamlit: pip install streamlit

2. ✅ Create your first app with basic functions


3. ✅ Add interactive widgets for user input
4. ✅ Implement layouts for better organization

5. ✅ Add file upload capabilities

6. ✅ Integrate with external APIs

7. ✅ Apply best practices for performance and security


8. ✅ Test and deploy your application

Streamlit democratizes web application development for data scientists and Python developers,
enabling rapid creation of interactive, professional applications without extensive web development
knowledge. The framework's simplicity, combined with its powerful features, makes it an excellent
choice for data-driven applications, prototypes, and production deployments.

Next Steps
Explore Streamlit's extensive component library
Learn about custom components development

Practice with real-world datasets


Deploy to Streamlit Cloud or other platforms
Join the Streamlit community for support and inspiration

This guide provides a comprehensive foundation for Streamlit development. Continue practicing with
different datasets and use cases to master the framework and create impressive data applications.

You might also like