
Added port conflict resolution to handle cases where port 8001 is already in use. The app now checks if a port is available and incrementally tries higher ports until it finds one that's free. generated with BackendIM... (backend.im)
43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
import uvicorn
|
|
import socket
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
from app.api.v1 import api_router
|
|
from app.core.config import settings
|
|
|
|
def is_port_in_use(port: int) -> bool:
|
|
"""Check if a port is already in use"""
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
return s.connect_ex(('0.0.0.0', port)) == 0
|
|
|
|
app = FastAPI(
|
|
title=settings.PROJECT_NAME,
|
|
openapi_url=f"{settings.API_V1_STR}/openapi.json",
|
|
docs_url="/docs",
|
|
redoc_url="/redoc",
|
|
)
|
|
|
|
# Set all CORS enabled origins
|
|
if settings.BACKEND_CORS_ORIGINS:
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
|
|
|
if __name__ == "__main__":
|
|
# Start with the preferred port
|
|
port = settings.PORT
|
|
|
|
# If the port is in use, try the next port
|
|
while is_port_in_use(port):
|
|
print(f"Port {port} is already in use, trying port {port+1}")
|
|
port += 1
|
|
|
|
print(f"Starting server on port {port}")
|
|
uvicorn.run("main:app", host="0.0.0.0", port=port, reload=True) |