#!/usr/bin/env python3 """ Development script to run the FastAPI server with database setup """ import os import sys import subprocess from pathlib import Path def run_command(command, cwd=None): """Run a command and return True if successful""" try: result = subprocess.run(command, shell=True, cwd=cwd, check=True) return result.returncode == 0 except subprocess.CalledProcessError as e: print(f"Error running command: {command}") print(f"Error: {e}") return False def main(): # Ensure we're in the backend directory backend_dir = Path(__file__).parent os.chdir(backend_dir) print("🍃 Starting Grocery Tracker Backend Development Server") print("=" * 50) # Check if virtual environment exists venv_path = backend_dir / "venv" if not venv_path.exists(): print("📦 Creating virtual environment...") if not run_command("python3 -m venv venv"): print("❌ Failed to create virtual environment") sys.exit(1) # Install dependencies print("📦 Installing dependencies...") pip_cmd = "venv/bin/pip" if os.name != 'nt' else "venv\\Scripts\\pip" if not run_command(f"{pip_cmd} install -r requirements.txt"): print("❌ Failed to install dependencies") sys.exit(1) # Create database tables print("🗄️ Creating database tables...") python_cmd = "venv/bin/python" if os.name != 'nt' else "venv\\Scripts\\python" create_tables_script = """ from models import Base from database import engine Base.metadata.create_all(bind=engine) print("Database tables created successfully!") """ with open("create_tables.py", "w") as f: f.write(create_tables_script) if not run_command(f"{python_cmd} create_tables.py"): print("⚠️ Database tables creation failed (this is normal if database doesn't exist yet)") # Clean up os.remove("create_tables.py") # Start the server print("🚀 Starting FastAPI server...") print("📍 API will be available at: http://localhost:8000") print("📚 API docs will be available at: http://localhost:8000/docs") print("🛑 Press Ctrl+C to stop the server") print("=" * 50) uvicorn_cmd = "venv/bin/uvicorn" if os.name != 'nt' else "venv\\Scripts\\uvicorn" run_command(f"{uvicorn_cmd} main:app --reload --host 0.0.0.0 --port 8000") if __name__ == "__main__": main()