Quickly Build Python Applications with Streamlit

Data scientists and developers often need to turn models or data analysis results into intuitive applications, but traditional web development frameworks (like Flask and Django) require writing a lot of boilerplate code and even front-end development skills. Streamlit is a fast web application framework designed specifically for Python. With just a few lines of code, you can transform Python scripts into interactive applications, greatly facilitating the quick launch of data science projects.

Streamlit is an efficient and easy-to-use tool, especially suitable for data visualization, model deployment, and demonstrating project results. Whether it’s data exploration, machine learning model presentation, or business demos, Streamlit allows you to quickly achieve a professional interactive interface.

Why Choose Streamlit?

  1. No Front-End Development Skills Required:

  • No need for HTML, CSS, or JavaScript; just write logic in Python to build applications.
  • Instant Write and Display:

    • Similar to a Jupyter Notebook experience, the application updates immediately after saving the code.
  • Supports a Rich Set of Data Science Tools:

    • Seamlessly integrates with Pandas, Matplotlib, Plotly, Seaborn, Altair, etc., supporting direct display of data tables and charts.
  • Interactive Components:

    • Provides various interactive components like buttons, sliders, dropdown menus, file uploads, etc., allowing users to interact with the application in real time.
  • Simple Deployment:

    • One-click deployment of applications to the cloud, share with teams or clients.
  • Ideal for Rapid Iteration:

    • Streamlit is designed for rapid prototyping and demonstration, making it very suitable for agile development processes.

    Installing Streamlit

    Installing Streamlit is very simple; just one command is needed:

    pip install streamlit
    

    After installation, run the following command to check if the installation was successful:

    streamlit hello
    

    This will open a built-in demo application showcasing the basic functionalities of Streamlit.

    Getting Started: Build Your First Streamlit Application

    1. Create Application File

    Create a new file <span>app.py</span> and write the following code:

    import streamlit as st
    
    # Title
    st.title("My First Streamlit Application")
    
    # Text Input
    name = st.text_input("Please enter your name")
    
    # Button
    if st.button("Submit"):
        st.write(f"Hello, {name}! Welcome to Streamlit!")
    

    2. Run the Application

    Run the following command to start the application:

    streamlit run app.py
    

    Streamlit will open the application in your browser (default address is <span>http://localhost:8501</span>).

    Core Features of Streamlit

    1. Display Text and Titles

    Streamlit provides various methods to display text and titles:

    st.title("This is the Title")
    st.header("This is a Header")
    st.subheader("This is a Subheader")
    st.text("This is normal text")
    st.markdown("**Supports Markdown formatted text**")
    

    2. Display Data Tables and Data Frames

    Streamlit can directly display Pandas data frames or NumPy arrays:

    import pandas as pd
    import numpy as np
    
    # Create DataFrame
    df = pd.DataFrame(
        np.random.randn(10, 5),
        columns=["Column 1", "Column 2", "Column 3", "Column 4", "Column 5"]
    )
    
    # Display DataFrame
    st.dataframe(df)
    
    # Can also display as a static table
    st.table(df.head())
    

    3. Interactive Components

    Streamlit offers various interactive components that allow users to dynamically interact with the application:

    # Text Input
    name = st.text_input("Enter your name")
    
    # Select Box
    option = st.selectbox("Choose an option", ["Option 1", "Option 2", "Option 3"])
    
    # Slider
    value = st.slider("Select a value", 0, 100, 50)
    
    # File Upload
    file = st.file_uploader("Upload a file")
    

    4. Data Visualization

    Streamlit supports mainstream visualization tools like Matplotlib, Seaborn, Plotly, Altair, etc.

    Visualizing with Matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Create data
    x = np.linspace(0, 10, 100)
    y = np.sin(x)
    
    # Plot chart
    fig, ax = plt.subplots()
    ax.plot(x, y)
    
    # Display chart
    st.pyplot(fig)
    
    Using Streamlit Built-in Charts
    import numpy as np
    import pandas as pd
    
    # Create data
    chart_data = pd.DataFrame(
        np.random.randn(20, 3),
        columns=["a", "b", "c"]
    )
    
    # Display line chart
    st.line_chart(chart_data)
    

    5. Multi-Page Layout

    Streamlit supports multi-page switching, helping you build complex applications.

    # Create a multi-page application
    page = st.sidebar.selectbox("Choose a page", ["Home", "Analysis", "About"])
    
    if page == "Home":
        st.title("This is the Home Page")
    elif page == "Analysis":
        st.title("This is the Analysis Page")
    else:
        st.title("This is the About Page")
    

    Application Scenarios

    1. Data Exploration and Analysis

    • Quickly build interactive data analysis tools for team sharing and visualization.

    2. Machine Learning Model Presentation

    • Used to present the prediction results of machine learning models, making it easy for business teams to understand the model’s performance.

    3. Data Visualization Dashboards

    • Build data dashboards to display key metrics and trends in real time.

    4. Data Tools or Prototypes

    • Develop lightweight data tools or rapid prototypes to validate concepts.

    5. Automation Tools

    • Develop graphical interfaces for automation scripts to enhance user experience.

    Advantages and Comparison of Streamlit

    Features
    Streamlit
    Dash
    Flask/Django
    Learning Curve
    ✅ Very Simple
    Medium
    High
    Suitable for Data Science
    ✅ Designed for Data Science
    ✅ Suitable
    ❌ Requires Manual Integration of Data Tools
    Front-End Development
    ❌ Not Required
    ❌ Not Required
    ✅ Required
    Interactive Components
    ✅ Rich Built-in Components
    ✅ Supports Components
    ❌ Requires Manual Development
    Deployment Complexity
    ✅ Simple
    Medium
    Complex

    Deploying Streamlit Applications

    Streamlit supports various deployment methods, including local, cloud, and Docker.

    1. Local Deployment

    Start the local server by running the following command:

    streamlit run app.py
    

    2. Deploying with Streamlit Cloud

    Streamlit offers a free cloud service that allows one-click deployment of applications to the cloud:

    • Register an account on Streamlit Cloud.
    • Push the code to GitHub, then connect to Streamlit Cloud.
    • Click “Deploy” and the application will be accessible online.

    3. Deploying with Docker

    Create a <span>Dockerfile</span>:

    FROM python:3.9-slim
    
    WORKDIR /app
    
    COPY requirements.txt requirements.txt
    RUN pip install -r requirements.txt
    
    COPY . .
    
    EXPOSE 8501
    CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]
    

    Build and run the container:

    docker build -t streamlit-app .
    docker run -p 8501:8501 streamlit-app
    

    Practical Tips and Optimizations

    1. Use Caching to Speed Up:

      @st.cache
      def load_data():
          return pd.read_csv("data.csv")
      
    • Use the <span>@st.cache</span> decorator for complex calculations or data with long loading times.
  • Custom Themes:

    • Define themes in the <span>~/.streamlit/config.toml</span> file to adjust the application’s colors and styles.
  • Separate Logic and Interface:

    • Separate data processing logic from Streamlit interface code to keep the code clear and maintainable.
  • Optimize Performance:

    • Avoid loading too many components and data to ensure the interface is responsive.

    Streamlit is a fast, concise, and powerful Python application development framework designed for data scientists and machine learning engineers. It simplifies complex web application development, significantly shortening the cycle from data to product. If you are looking for an efficient way to transform data analysis or machine learning results into interactive applications, Streamlit will be your excellent choice!

    Leave a Comment