Streamlit: A Magical Web Application Framework!

Streamlit: Build Beautiful Web Applications with Just a Few Lines of Python Code!

Hello everyone! Today I want to introduce you to a Python library that I absolutely love – Streamlit. Are you still struggling to build web applications? Still worried about front-end development? With Streamlit, you only need to know how to write Python code to create beautiful web applications! No need to understand HTML, CSS, or JavaScript; Streamlit takes care of everything for you. Whether it’s data visualization or deploying machine learning applications, it can handle it all with ease.

Getting Started Quickly

First, let’s install Streamlit:

pip install streamlit

Now let’s write the simplest example:

import streamlit as st

st.title("My First Streamlit App")
name = st.text_input("Please enter your name")
if name:
    st.write(f"Hello, {name}!")
    
if st.button("Click Me"):
    st.balloons()

To run this program, just enter the following command in the command line:

streamlit run app.py

Isn’t it super simple? This small program already has:

  1. Title display
  2. Text input box
  3. Button interaction
  4. Balloon animation effect

The Ultimate Data Display Tool

One of Streamlit’s most powerful features is data display. Let’s see how to display various data:

import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px

# Create sample data
data = pd.DataFrame({
    'Name': ['Xiao Ming', 'Xiao Hong', 'Xiao Zhang', 'Xiao Li'],
    'Age': [18, 20, 19, 22],
    'Score': [85, 92, 78, 95]
})

# Display table
st.subheader("Student Information Table")
st.dataframe(data)  # You can also use st.table()

# Draw chart
st.subheader("Score Distribution")
fig = px.bar(data, x='Name', y='Score')
st.plotly_chart(fig)

# Display statistics
st.subheader("Statistical Information")
st.metric(label="Average Score", value=f"{data['Score'].mean():.1f}")

Tip: Streamlit supports various chart libraries, such as Matplotlib, Plotly, Altair, etc. You can use the libraries you are most familiar with to create charts.

Sidebar and Layout Control

Want your application to look more professional? Try these layout controls:

import streamlit as st

# Sidebar
with st.sidebar:
    st.title("Settings")
    color = st.color_picker("Choose Color")
    size = st.slider("Choose Size", 10, 100)

# Column layout
col1, col2 = st.columns(2)
with col1:
    st.header("Left Column")
    st.write("This is the content on the left.")
    
with col2:
    st.header("Right Column")
    st.write("This is the content on the right.")

# Expandable container
with st.expander("Click to Expand"):
    st.write("Here is some additional information...")
    st.code("print('Hello, Streamlit!')")

File Upload and Download

Streamlit makes file handling super simple:

import streamlit as st
import pandas as pd

uploaded_file = st.file_uploader("Choose a CSV file", type='csv')
if uploaded_file is not None:
    # Read data
    df = pd.read_csv(uploaded_file)
    st.write("Data Preview:")
    st.dataframe(df)
    
    # Process data (example: calculate the average for each column)
    means = df.mean()
    
    # Generate download link
    st.download_button(
        label="Download Processed Results",
        data=means.to_csv().encode('utf-8'),
        file_name='results.csv'
    )

Cache Mechanism

If your application needs to handle large amounts of data or complex calculations, you can use caching to improve performance:

import streamlit as st
import time

@st.cache_data  # Add cache decorator
def expensive_computation(n):
    time.sleep(2)  # Simulate time-consuming operation
    return n ** 2

number = st.number_input("Enter a number", value=10)
result = expensive_computation(number)
st.write(f"Calculation Result: {result}")

Tip: <span>@st.cache_data</span> decorator caches the return value of the function. When the input is the same, it directly returns the cached result, greatly improving application performance!

Practical Mini Project: Mood Diary

Let’s integrate what we’ve learned and create a simple mood diary application:

import streamlit as st
import pandas as pd
from datetime import datetime

# Initialize data
if 'diary_entries' not in st.session_state:
    st.session_state.diary_entries = []

st.title("πŸ“ My Mood Diary")

# Sidebar: Add new diary entry
with st.sidebar:
    st.header("Write New Diary")
    date = st.date_input("Date", datetime.now())
    mood = st.selectbox("Mood", ["😊 Happy", "😒 Sad", "😑 Angry", "😌 Calm"])
    content = st.text_area("Content")
    
    if st.button("Save"):
        st.session_state.diary_entries.append({
            "Date": date,
            "Mood": mood,
            "Content": content
        })
        st.success("Saved successfully!")

# Main page: Display diary list
if st.session_state.diary_entries:
    df = pd.DataFrame(st.session_state.diary_entries)
    st.dataframe(df, use_container_width=True)
    
    # Simple statistics
    st.subheader("Mood Statistics")
    mood_counts = df['Mood'].value_counts()
    st.bar_chart(mood_counts)
else:
    st.info("No diary entries yet, go write the first one!")

Exercises

  1. Create a to-do list manager that supports adding, deleting, and marking tasks as complete.
  2. Make a simple data visualization dashboard that displays basic statistics of a CSV file.
  3. Develop an online calculator that supports basic mathematical operations.

Conclusion

Streamlit is truly a magical tool! It allows us to:

  • Quickly build web application interfaces
  • Effortlessly display various data and charts
  • Simply implement user interaction features
  • Conveniently handle file uploads and downloads

Most importantly, it allows us to focus on Python code and business logic without worrying about the details of front-end development. Whether you are a data analyst, machine learning engineer, or Python enthusiast, Streamlit is a tool worth mastering!

Remember to write and practice more, and search for documentation and solutions when you encounter problems. The official Streamlit documentation is well-written and contains a lot of examples for reference.

Your next step is to try transforming your own Python projects into web applications, allowing more people to use your work. Go for it!

Leave a Comment