Skip to content

Instantly share code, notes, and snippets.

@brndnsmth
Created February 23, 2025 19:21
Show Gist options
  • Save brndnsmth/a0cab204fb450d1de9482475942edc55 to your computer and use it in GitHub Desktop.
Save brndnsmth/a0cab204fb450d1de9482475942edc55 to your computer and use it in GitHub Desktop.
FastAPI Setup and Run Script (Mac and Linux)
#!/bin/bash
# Get Python version
PYTHON_VERSION=$(python3 --version 2>/dev/null | awk '{print $2}')
PYTHON_MAJOR=$(echo "$PYTHON_VERSION" | cut -d. -f1)
PYTHON_MINOR=$(echo "$PYTHON_VERSION" | cut -d. -f2)
# Check if Python is at least 3.8
if [ "$PYTHON_MAJOR" -eq 3 ] && [ "$PYTHON_MINOR" -lt 8 ]; then
echo "Python 3.8+ is required. Please install it."
exit 1
fi
# Create virtual environment if it doesn't exist
if [ ! -d ".venv" ]; then
echo "Creating virtual environment..."
python3 -m venv .venv
fi
# Activate virtual environment
source .venv/bin/activate
# Install dependencies if they are missing
if [ ! -d ".venv/lib" ] || [ -z "$(pip freeze)" ]; then
echo "Installing dependencies..."
pip install -r requirements.txt
else
echo "Dependencies already installed."
fi
# Detect number of CPU cores
NUM_CORES=$(nproc)
# Calculate recommended workers (2 * NUM_CORES + 1)
WORKERS=$((2 * NUM_CORES + 1))
# Prompt user for how to run FastAPI
echo "Choose how you want to run FastAPI:"
echo "1) fastapi dev (recommended for development)"
echo "2) uvicorn main:app --reload"
echo "3) uvicorn main:app with recommended workers ($WORKERS workers)"
echo "4) Set a custom number of workers (must be <= $WORKERS)"
read -p "Enter your choice (1, 2, 3, or 4): " choice
case "$choice" in
1)
echo "Running FastAPI using fastapi dev..."
fastapi dev main.py
;;
2)
echo "Running FastAPI using Uvicorn..."
uvicorn main:app --reload
;;
3)
echo "Running FastAPI using Uvicorn with $WORKERS workers..."
uvicorn main:app --workers $WORKERS --reload
;;
4)
# Ask user for custom number of workers
while true; do
read -p "Enter the number of workers: " custom_workers
if [ "$custom_workers" -le "$WORKERS" ]; then
echo "Running FastAPI using Uvicorn with $custom_workers workers..."
uvicorn main:app --workers "$custom_workers" --reload
break
else
echo "The number of workers cannot exceed $WORKERS. Please enter a valid number."
fi
done
;;
*)
echo "Invalid choice. Exiting."
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment