Skip to content

Instantly share code, notes, and snippets.

@brndnsmth
Created February 23, 2025 19:22
Show Gist options
  • Save brndnsmth/11debf628e487920061570dfa6509848 to your computer and use it in GitHub Desktop.
Save brndnsmth/11debf628e487920061570dfa6509848 to your computer and use it in GitHub Desktop.
FastAPI Setup and Run Script (Windows)
@echo off
setlocal
:: Get Python version
for /f "tokens=2 delims= " %%v in ('python --version 2^>NUL') do set PYTHON_VERSION=%%v
:: Extract major and minor version
for /f "tokens=1,2 delims=." %%a in ("%PYTHON_VERSION%") do set MAJOR=%%a & set MINOR=%%b
:: Check if Python is at least 3.8
if "%MAJOR%"=="Python 3" if %MINOR% LSS 8 (
echo Python 3.8+ is required. Please install it.
exit /b 1
)
:: Create virtual environment if it doesn't exist
if not exist .venv (
echo Creating virtual environment...
python -m venv .venv
)
:: Activate virtual environment
call .venv\Scripts\activate
:: Check if dependencies are installed
for /f %%i in ('pip freeze 2^>NUL') do set DEPENDENCIES=%%i
if not defined DEPENDENCIES (
echo Installing dependencies...
pip install -r requirements.txt
) else (
echo Dependencies already installed.
)
:: Detect the number of CPU cores
for /f "tokens=*" %%a in ('wmic cpu get NumberOfCores /value') do (
set %%a
)
:: Calculate recommended workers (2 * NumberOfCores + 1)
set /a WORKERS=2*%NumberOfCores%+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%)
set /p choice=Enter your choice (1, 2, 3, or 4):
if "%choice%"=="1" (
echo Running FastAPI using fastapi dev...
fastapi dev main.py
) else if "%choice%"=="2" (
echo Running FastAPI using Uvicorn...
uvicorn main:app --reload
) else if "%choice%"=="3" (
echo Running FastAPI using Uvicorn with %WORKERS% workers...
uvicorn main:app --workers %WORKERS% --reload
) else if "%choice%"=="4" (
:ask_workers
set /p custom_workers=Enter the number of workers:
if %custom_workers% le %WORKERS% (
echo Running FastAPI using Uvicorn with %custom_workers% workers...
uvicorn main:app --workers %custom_workers% --reload
) else (
echo The number of workers cannot exceed %WORKERS%. Please enter a valid number.
goto ask_workers
)
) else (
echo Invalid choice. Exiting.
exit /b 1
)
endlocal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment