Skip to content

Python Streamlit

Edward Baitsewe edited this page Feb 17, 2025 · 1 revision

Home Loan App

Create an environment using venv

  1. Open a terminal and navigate to your project folder.
cd myproject
  1. Install pipenv
pip install pipenv
  1. Start the virtual environment
pipenv shell

A Pipfile for our virtual environment will be created which will list any packages that have installed. To install a new package use pipenv install django where django represents the package name.

Install Streamlit in your environment

  1. In the terminal with your environment activated, type:
pip install streamlit
  1. Test that the installation worked by launching the Streamlit Hello example app:
streamlit hello
If this doesn't work, use the long-form command:
python -m streamlit hello
  1. Streamlit's Hello app should appear in a new tab in your web browser!

Create Requirements

  1. To create requirements.txt with pipenv use this command:
pipenv lock
pipenv sync
pipenv run pip freeze > requirements.txt

Create the Dockerfile:

  1. Create a Dockerfile and save the following content to the file.
# Stage 1: Base build stage
FROM python:3.12-slim as build

# Create the app directory
RUN mkdir /app

# Set the working directory in the container
WORKDIR /app

# Set environment variables to optimize Python
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1 

# Install dependencies first for caching benefit
RUN pip install --upgrade pip
COPY requirements.txt /app/ 
RUN pip install --no-cache-dir -r requirements.txt

# Stage 2: Final build stage
FROM gcr.io/distroless/python3 as production

RUN useradd -m -r appuser && \
   mkdir /app && \
   chown -R appuser /app

# Copy the Python dependencies from the builder stage
COPY --from=build /usr/local/lib/python3.12/site-packages/ /usr/local/lib/python3.12/site-packages/
COPY --from=build /usr/local/bin/ /usr/local/bin/

# Set the working directory
WORKDIR /app

# Copy application code
COPY --chown=appuser:appuser . .

# Switch to non-root user
USER appuser

# Expose the application port for Streamlit
EXPOSE 8501 

# Make entry file executable
RUN chmod +x /app/entrypoint.prod.sh

# Start the application using entrypoint script
CMD ["streamlit", "run", "homeLoanApp.py", "--server.port=8501", "--server.address=0.0.0.0"]

Build & Run the Docker Container

  1. Build the Docker image:
docker build -t mortgage-calculator .
  1. Run the Docker container:
docker run -p 8501:8501 mortgage-calculator

This will allow you to access your Streamlit app at http://localhost:8501.

Clone this wiki locally