2025-05-16 01:16:35 +00:00

66 lines
2.1 KiB
Python

import os
import socket
import sys
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from api.routers import auth_router, health_router, todo_router, user_router
from db.database import create_tables
app = FastAPI(
title="SimpleTodoApp API",
description="API for a simple todo application with authentication",
version="0.1.0",
)
# CORS settings
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # For development, in production specify your frontend domain
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(auth_router.router, prefix="/api/auth", tags=["auth"])
app.include_router(user_router.router, prefix="/api/users", tags=["users"])
app.include_router(todo_router.router, prefix="/api/todos", tags=["todos"])
app.include_router(health_router.router, prefix="/api", tags=["health"])
# Create database tables on startup
@app.on_event("startup")
async def startup():
create_tables()
def is_port_in_use(port, host='0.0.0.0'):
"""Check if a port is in use."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind((host, port))
return False
except OSError:
return True
if __name__ == "__main__":
# Get port from environment variable or use default of 8000
port = int(os.environ.get("PORT", 8000))
host = os.environ.get("HOST", "0.0.0.0")
# If the preferred port is in use, try to find an available port
if is_port_in_use(port, host):
print(f"Port {port} is already in use. Trying alternative ports...")
for alt_port in [8001, 8002, 8003, 8004, 8005]:
if not is_port_in_use(alt_port, host):
port = alt_port
print(f"Found available port: {port}")
break
else:
print("No available ports found between 8000-8005. Exiting.")
sys.exit(1)
print(f"Starting server on {host}:{port}")
uvicorn.run("main:app", host=host, port=port, reload=True)