From a2ba7e0a544821c9699a6baec1a596d7f43746bb Mon Sep 17 00:00:00 2001 From: Automated Action Date: Wed, 14 May 2025 01:26:28 +0000 Subject: [PATCH] Fix port binding issue with dynamic port selection 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) --- README.md | 16 ++++++++++++---- app/core/config.py | 1 + main.py | 17 ++++++++++++++++- 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 8395d5a..b5951a8 100644 --- a/README.md +++ b/README.md @@ -54,14 +54,22 @@ A fast, lightweight REST API service built with FastAPI and SQLite. Start the server with: ```bash -uvicorn main:app --reload +python main.py ``` -The API will be available at http://localhost:8000. +Or manually with uvicorn: + +```bash +uvicorn main:app --host 0.0.0.0 --port 8001 --reload +``` + +The application will automatically find an available port if the default port (8001) is already in use. + +The API will be available at http://localhost:8001. API documentation is available at: -- Swagger UI: http://localhost:8000/docs -- ReDoc: http://localhost:8000/redoc +- Swagger UI: http://localhost:8001/docs +- ReDoc: http://localhost:8001/redoc ## API Endpoints diff --git a/app/core/config.py b/app/core/config.py index a34669e..f5070ad 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -6,6 +6,7 @@ from pydantic_settings import BaseSettings class Settings(BaseSettings): API_V1_STR: str = "/api/v1" PROJECT_NAME: str = "Quick REST API Service" + PORT: int = 8001 # CORS settings BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = [] diff --git a/main.py b/main.py index 9979e03..7bb2eb7 100644 --- a/main.py +++ b/main.py @@ -1,10 +1,16 @@ 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", @@ -25,4 +31,13 @@ if settings.BACKEND_CORS_ORIGINS: app.include_router(api_router, prefix=settings.API_V1_STR) if __name__ == "__main__": - uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) \ No newline at end of file + # 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) \ No newline at end of file