DebianDebian Based

How To Install Streamlit on Debian 12

Install Streamlit on Debian 12

Streamlit has revolutionized how data scientists and machine learning engineers build interactive data applications. Its intuitive Python-based framework allows for rapid development of web applications without requiring extensive frontend knowledge. If you’re running Debian 12 (Bookworm) and want to leverage Streamlit’s powerful capabilities, this guide will walk you through the complete installation process and beyond.

Table of Contents

Understanding Streamlit

What is Streamlit?

Streamlit is an open-source Python library designed specifically for creating data applications with minimal effort. Unlike traditional web frameworks that require HTML, CSS, and JavaScript knowledge, Streamlit enables developers to build interactive, data-rich applications using pure Python code.

# A simple Streamlit app example
import streamlit as st
import pandas as pd

st.title("Hello Streamlit on Debian 12!")
st.write("This is how easy it is to create a Streamlit app.")

data = pd.DataFrame({"col1": [1, 2, 3], "col2": [4, 5, 6]})
st.dataframe(data)

The framework transforms scripts like this into fully functional web applications in seconds, making it ideal for data visualization, machine learning model deployments, and interactive dashboards.

Key Features and Benefits

Streamlit stands out from other frameworks due to several distinctive features:

  • Pure Python workflow with no frontend experience required
  • Reactive execution model that automatically updates components
  • Rich widget ecosystem for interactive elements
  • Live reloading during development
  • Powerful caching mechanism for performance optimization
  • Simple deployment options
  • Growing community and component ecosystem

Use Cases

Organizations and individuals use Streamlit for various applications, including:

  • Interactive data exploration dashboards
  • Machine learning model demonstrations
  • Rapid prototyping of data applications
  • Internal tools for data teams
  • Sharing insights with non-technical stakeholders
  • Educational tools and tutorials

Streamlit vs Other Frameworks

While many frameworks can build data applications, Streamlit’s focus on simplicity sets it apart:

  • Streamlit vs Dash: Streamlit requires less boilerplate code and has a gentler learning curve
  • Streamlit vs Flask: Flask offers more flexibility but requires more frontend knowledge
  • Streamlit vs Django: Django provides comprehensive web functionality but comes with significantly more complexity
  • Streamlit vs Gradio: Streamlit offers more extensive widgets and layout options, while Gradio specializes in ML model interfaces

Prerequisites for Debian 12

System Requirements

Before installing Streamlit, ensure your Debian 12 system meets these requirements:

  • CPU: Any modern processor (dual-core or better recommended)
  • RAM: Minimum 2GB (4GB+ recommended for data-intensive applications)
  • Storage: At least 5GB free space
  • Internet connection for package downloads
  • Debian 12 (Bookworm) with current updates

Required Dependencies

Streamlit relies on several system packages:

  • Python 3.7 or newer (Debian 12 comes with Python 3.11)
  • pip (Python package installer)
  • build-essential package (for compiling certain dependencies)
  • python3-dev (Python development headers)
  • Various libraries for data processing and visualization

Python Environment Setup

Debian 12 ships with Python 3.11, which works perfectly with Streamlit. You can verify your Python installation by running:

python3 --version

This should display Python 3.11.x, confirming your system has a compatible version.

Package Management Tools

You’ll use several package management tools throughout this process:

  • apt: Debian’s package manager for system libraries
  • pip: Python’s package installer for Python libraries
  • venv/virtualenv: For creating isolated Python environments

Terminal Access and Permissions

You’ll need terminal access with sufficient permissions to install packages. For most operations, you’ll need sudo privileges.

Preparing Your Debian 12 System

Updating Your System

Start by updating your Debian system to ensure you have the latest packages and security updates:

sudo apt update
sudo apt upgrade -y

This ensures your system has the latest security patches and package versions before proceeding.

Installing Essential Build Tools

Install the necessary development tools and libraries:

sudo apt install -y build-essential python3-dev python3-pip

These packages provide the compilers and development files needed to build Python packages that Streamlit depends on.

Setting Up Python

Although Python comes pre-installed on Debian 12, ensure you have pip for package management:

# Upgrade pip to the latest version
python3 -m pip install --upgrade pip

Using the latest version of pip helps avoid installation issues with newer packages.

Setting Up Version Control

Install Git for project management:

sudo apt install -y git

Git allows you to track changes in your Streamlit applications and collaborate with others efficiently.

Python Environment Setup Options

Using Virtual Environments

Virtual environments are essential for Python development as they isolate project dependencies, preventing conflicts between different projects and with system packages.

Setting Up venv

Python’s built-in venv module provides a straightforward way to create virtual environments:

# Create a project directory
mkdir streamlit_project
cd streamlit_project

# Create a virtual environment
python3 -m venv venv

# Activate the virtual environment
source venv/bin/activate

After activation, your terminal prompt will change (usually by adding “(venv)” at the beginning), indicating that the environment is active. All Python packages installed will now be confined to this environment.

To deactivate when finished:

deactivate

Using Anaconda/Miniconda

For data science work, Anaconda or Miniconda provides an alternative environment management system:

# Download and install Miniconda
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh -b
echo 'export PATH="$HOME/miniconda3/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

# Create a conda environment
conda create -n streamlit_env python=3.11
conda activate streamlit_env

Conda environments handle both Python packages and binary dependencies, making them particularly useful for complex data science stacks.

Using pipenv

Pipenv combines pip and virtualenv for a more modern Python workflow:

# Install pipenv
pip install pipenv

# Create a project directory
mkdir streamlit_project
cd streamlit_project

# Initialize environment and install packages
pipenv --python 3.11
pipenv shell

Pipenv maintains a Pipfile that tracks both direct dependencies and sub-dependencies, ensuring reproducible environments.

Environment Isolation Best Practices

Regardless of which method you choose:

  • Create one environment per project
  • Document dependencies in requirements.txt or environment.yml
  • Include environment files in version control
  • Regularly update dependencies for security

This discipline ensures consistent behavior across development, testing, and production environments.

Installing Streamlit

Installation via pip

With your virtual environment activated, installing Streamlit via pip is straightforward:

pip install streamlit

This command installs the latest stable version of Streamlit and its dependencies. If you need a specific version:

pip install streamlit==1.27.0  # Replace with desired version

The installation process may take a few minutes as it resolves and downloads dependencies.

Installation via conda

If using Anaconda or Miniconda:

conda install -c conda-forge streamlit

The conda-forge channel provides well-maintained packages for the data science community.

Installation via pipenv

When using Pipenv:

pipenv install streamlit

This adds Streamlit to your Pipfile and installs it in your virtual environment.

Dependency Resolution

Occasionally, you might encounter dependency conflicts. To resolve these:

  1. Try upgrading pip: pip install --upgrade pip
  2. Use verbose output to identify conflicts: pip install -v streamlit
  3. Install problematic dependencies manually before Streamlit
  4. Create a clean virtual environment and try again

Most conflicts arise from incompatible versions of packages required by different libraries.

Installation Validation

After installation, verify that Streamlit is correctly installed:

streamlit --version

This should display the installed Streamlit version number, confirming successful installation.

Installation Troubleshooting

Common installation issues include:

  • Missing system dependencies: Install with sudo apt install python3-dev build-essential
  • Permission errors: Ensure you’re using a virtual environment
  • Network issues: Verify your internet connection and proxy settings
  • Outdated pip: Update with pip install --upgrade pip
  • Incompatible Python: Ensure you’re using Python 3.7+

If you encounter cryptic error messages, try installing with verbose output:

pip install -v streamlit

This provides detailed information about the installation process, helping identify the source of problems.

Verifying Your Installation

Running the Hello Command

The simplest way to verify your Streamlit installation is to run the built-in demo:

streamlit hello

This command starts Streamlit’s demo application, which should automatically open in your web browser at http://localhost:8501. The demo showcases Streamlit’s capabilities through several interactive examples.

Understanding the Demo Apps

The hello command launches several demo applications:

  1. Welcome page: Introduces Streamlit’s features
  2. Animation demo: Shows animated data visualizations
  3. Plotting demo: Demonstrates various charting capabilities
  4. Dataframe demo: Shows interactive data handling
  5. Mapping demo: Illustrates geospatial visualization
  6. Widget demo: Showcases interactive UI controls

Exploring these demos provides insight into what’s possible with Streamlit and how the different components work together.

Testing Core Functionality

Create a minimal test application to further verify your installation:

# Create a test file
echo 'import streamlit as st

st.title("Streamlit Test")
st.write("Hello, Debian 12!")
st.slider("Test slider", 0, 100, 50)' > test_app.py

# Run the application
streamlit run test_app.py

If this displays a page with the title, text, and a functioning slider, your core functionality is working correctly.

Checking Version Information

To confirm your exact Streamlit version:

streamlit --version

For more detailed information about your environment, create a diagnostic script:

import streamlit as st
import pandas as pd
import numpy as np
import platform
import sys

st.write(f"Streamlit version: {st.__version__}")
st.write(f"Python version: {platform.python_version()}")
st.write(f"Pandas version: {pd.__version__}")
st.write(f"NumPy version: {np.__version__}")
st.write(f"System platform: {platform.system()} {platform.release()}")

This helps identify potential compatibility issues with your environment.

Creating Your First Streamlit App

Project Structure Setup

Begin by organizing your project:

mkdir -p my_streamlit_app
cd my_streamlit_app
python -m venv venv
source venv/bin/activate
pip install streamlit pandas matplotlib

A well-structured project might look like:

my_streamlit_app/
├── venv/                  # Virtual environment
├── data/                  # Data files
├── app.py                 # Main application
├── requirements.txt       # Dependencies
└── README.md              # Documentation

This organization keeps your files neatly arranged and makes maintenance easier.

Basic App Template

Create a file named app.py with this starter code:

import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Page configuration
st.set_page_config(
    page_title="My First Streamlit App",
    page_icon="",
    layout="wide"
)

# Main title and description
st.title("My First Streamlit App on Debian 12")
st.write("""
    This is a simple Streamlit application running on Debian 12.
    Let's explore some of Streamlit's features!
""")

# Sidebar for controls
st.sidebar.header("Dashboard Controls")
selected_option = st.sidebar.selectbox(
    "Choose a section",
    ["Data View", "Visualization", "Interactive Elements"]
)

# Main content based on selection
if selected_option == "Data View":
    st.header("Data View")
    # Generate sample data
    data = pd.DataFrame({
        'Category': ['A', 'B', 'C', 'D'],
        'Values': [10, 25, 15, 30]
    })
    st.dataframe(data)
    
elif selected_option == "Visualization":
    st.header("Data Visualization")
    fig, ax = plt.subplots()
    x = np.linspace(0, 10, 100)
    ax.plot(x, np.sin(x))
    st.pyplot(fig)
    
else:
    st.header("Interactive Elements")
    name = st.text_input("Enter your name")
    age = st.slider("Select your age", 0, 100, 25)
    if st.button("Say Hello"):
        st.success(f"Hello {name}, you are {age} years old!")

This template provides a foundation with multiple sections and interactive elements.

Adding Text Elements

Streamlit offers various text elements to structure your application:

st.title("Main Title")
st.header("Section Header")
st.subheader("Subsection Title")
st.markdown("**Bold text** and *italic text*")
st.code("print('Hello, Streamlit!')", language="python")
st.text("Plain text without formatting")
st.latex(r"\int_a^b f(x) dx")

These elements help organize information hierarchically and improve readability.

Implementing Widgets

Interactive widgets make your application dynamic:

# Input widgets
name = st.text_input("Enter your name")
age = st.number_input("Enter your age", min_value=0, max_value=120)
happy = st.checkbox("Are you happy?")

# Selection widgets
option = st.selectbox("Choose an option", ["Option 1", "Option 2", "Option 3"])
options = st.multiselect("Select multiple", ["A", "B", "C", "D"])

# Button widgets
if st.button("Say hello"):
    st.write(f"Hello, {name}!")

# Slider widgets
value = st.slider("Select a value", 0, 100, 50)
date_range = st.date_input("Select a date range")

Widgets collect user input that can drive your application’s behavior.

Displaying Data

Streamlit excels at data visualization:

# Create sample data
df = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100),
    'size': np.random.randint(100, 1000, 100)
})

# Display as a table
st.subheader("Data Table")
st.dataframe(df.head())

# Create various charts
st.subheader("Line Chart")
st.line_chart(df[['x', 'y']])

st.subheader("Bar Chart")
st.bar_chart(df[['x', 'y']])

# Standard matplotlib charts
st.subheader("Custom Chart")
fig, ax = plt.subplots()
ax.scatter(df['x'], df['y'], s=df['size']/10)
st.pyplot(fig)

# Maps
st.subheader("Map")
map_data = pd.DataFrame({
    'lat': [40.7128, 37.7749, 47.6062],
    'lon': [-74.0060, -122.4194, -122.3321]
})
st.map(map_data)

These visualizations transform raw data into actionable insights.

Running Your Application

To launch your application:

streamlit run app.py

The application will start and be available at http://localhost:8501 by default. Streamlit automatically reloads when you save changes to your code, facilitating rapid development.

Advanced Streamlit Features

Caching for Performance

Streamlit’s caching system improves performance by storing computation results:

# Cache data loading operations
@st.cache_data
def load_data():
    # This function will only run once, even if called multiple times
    df = pd.read_csv("large_file.csv")
    return df

data = load_data()  # Cached result

# Cache resource-intensive objects (like ML models)
@st.cache_resource
def create_model():
    # This function will only run once per session
    return ComplexModel()

model = create_model()  # Cached model

Effective caching dramatically improves application responsiveness, especially for data-intensive operations.

Layout Options

Control your application’s layout with containers:

# Create columns for side-by-side elements
col1, col2 = st.columns(2)
with col1:
    st.header("Column 1")
    st.image("image1.jpg")
with col2:
    st.header("Column 2")
    st.image("image2.jpg")

# Create expandable sections
with st.expander("Click to expand"):
    st.write("This content is hidden until expanded")

# Group elements in containers
container = st.container()
container.write("This is inside a container")

These layout options help organize complex applications into logical sections.

Session State

Maintain state between reruns with session state:

# Initialize state
if 'counter' not in st.session_state:
    st.session_state.counter = 0

# Update state
if st.button("Increment"):
    st.session_state.counter += 1

# Display state
st.write(f"Counter value: {st.session_state.counter}")

Session state preserves values across the reactive reruns that occur when users interact with widgets.

File Uploaders and Downloads

Handle file operations:

# File uploader
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
    data = pd.read_csv(uploaded_file)
    st.dataframe(data)

# File downloader
if st.button("Download Sample Data"):
    csv = df.to_csv(index=False)
    st.download_button(
        label="Download CSV",
        data=csv,
        file_name="sample_data.csv",
        mime="text/csv"
    )

These components enable users to provide their own data and save results from your application.

Deploying Streamlit on Debian 12

Local Deployment

For development or personal use, run Streamlit locally:

streamlit run app.py

To make it available on your local network:

streamlit run app.py --server.address 0.0.0.0

This allows other devices on your network to access the application using your machine’s IP address.

Server Deployment

For production use, set up a more robust deployment:

  1. Create a dedicated user for your Streamlit application:
    sudo adduser streamlit
    sudo su - streamlit
  2. Clone your application repository:
    git clone https://github.com/yourusername/your-streamlit-app.git
    cd your-streamlit-app
  3. Set up a virtual environment and install dependencies:
    python3 -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt

This approach separates your application from other system processes.

Using systemd for Service Management

Create a systemd service to manage your application:

sudo nano /etc/systemd/system/streamlit.service

Add the following content:

[Unit]
Description=Streamlit Application
After=network.target

[Service]
User=streamlit
WorkingDirectory=/home/streamlit/your-streamlit-app
ExecStart=/home/streamlit/your-streamlit-app/venv/bin/streamlit run app.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Enable and start the service:

sudo systemctl enable streamlit
sudo systemctl start streamlit

Now your application will start automatically on system boot and restart if it crashes.

Nginx Configuration

Set up Nginx as a reverse proxy:

sudo apt install nginx
sudo nano /etc/nginx/sites-available/streamlit

Add this configuration:

server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://localhost:8501;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Enable the site and restart Nginx:

sudo ln -s /etc/nginx/sites-available/streamlit /etc/nginx/sites-enabled
sudo systemctl restart nginx

This configuration forwards web traffic to your Streamlit application.

Security Considerations

Protect your deployment:

  • Keep Debian and all packages updated
  • Use HTTPS with Let’s Encrypt certificates
  • Implement authentication for sensitive applications
  • Use environment variables for secrets
  • Limit permissions for the Streamlit user

Security should be a priority, especially for public-facing applications.

Common Installation Issues and Solutions

Dependency Conflicts

If you encounter dependency conflicts:

  1. Start with a fresh virtual environment
  2. Install problematic packages individually before Streamlit
  3. Use pip install --no-dependencies for problematic packages
  4. Check for conflicting versions in your requirements

Most conflicts occur with numerical libraries like numpy or scipy.

Port Availability Issues

If port 8501 is unavailable:

# Check what's using the port
sudo lsof -i :8501

# Use a different port
streamlit run app.py --server.port 8502

Update any proxy configurations to reflect the new port.

Permission Problems

Permission issues usually manifest as access denied errors:

  • Ensure your user has write access to the project directory
  • Check ownership of virtual environment directories
  • Use sudo only when necessary for system packages

Most permission issues can be resolved by properly setting directory and file ownership.

ModuleNotFoundError

If you encounter missing module errors:

  1. Verify your virtual environment is activated
  2. Install missing packages: pip install package_name
  3. Check your Python path: python -c "import sys; print(sys.path)"

Most module errors occur when running outside the intended environment.

Performance Optimization

Memory Management

Reduce memory usage:

  • Load only necessary data columns
  • Process data in chunks for large datasets
  • Use efficient data types (e.g., categorical for strings with repetition)
  • Implement pagination for large datasets

Efficient memory usage improves responsiveness and allows larger datasets.

Caching Strategies

Implement strategic caching:

# For data that rarely changes
@st.cache_data(ttl=3600)  # 1-hour cache
def load_reference_data():
    return pd.read_csv("reference.csv")

# For expensive computations
@st.cache_resource
def create_ml_model():
    return train_complex_model()

Proper caching dramatically improves responsiveness by avoiding redundant computations.

Background Processing

Handle long-running tasks:

with st.spinner('Processing data...'):
    # Long-running operation here
    result = perform_lengthy_calculation()
st.success('Done!')

Progress indicators keep users informed during complex operations.

Maintenance and Upgrades

Keeping Streamlit Updated

Regularly update Streamlit to access new features and security fixes:

# Activate your virtual environment
source venv/bin/activate

# Update Streamlit
pip install --upgrade streamlit

Review the changelog before upgrading to catch potential breaking changes.

Managing Dependencies

Maintain a requirements.txt file:

# Generate requirements file
pip freeze > requirements.txt

# Install from requirements
pip install -r requirements.txt

Periodically review dependencies for updates, especially security patches.

Version Compatibility

When upgrading:

  1. Test in a development environment first
  2. Review changelogs for breaking changes
  3. Update your code to accommodate API changes
  4. Consider pinning version numbers for stability

Careful version management prevents unexpected behavior changes.

Troubleshooting Reference

Common Error Messages

  • “No module named streamlit”: Your environment isn’t activated or Streamlit isn’t installed
  • “Address already in use”: Port 8501 is occupied by another process
  • “Permission denied”: Check file and directory permissions
  • “ImportError: cannot import name X from Y”: Version compatibility issue
  • “RuntimeError: Another StreamlitRunner is already running”: Multiple instances conflict

Diagnostic Commands

Useful commands for troubleshooting:

# Check Streamlit version
streamlit --version

# Check installed packages
pip list

# Show running processes
ps aux | grep streamlit

# Check port usage
sudo lsof -i :8501

These commands help identify common issues quickly.

With these tools and knowledge, you’re well-equipped to install, configure, and maintain Streamlit applications on your Debian 12 system.

Congratulations! You have successfully installed Streamlit. Thanks for using this tutorial for installing the Streamlit on Debian 12 “Bookworm” system. For additional or useful information, we recommend you check the official Streamlit website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button