Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)
Python
Make backend dev fall back to an open port
Abi Raja7902fa1be452
diff --git a/.zed/tasks.json b/.zed/tasks.jsonindex a6420be4..0598be45 100644--- a/.zed/tasks.json+++ b/.zed/tasks.json@@ -17,7 +17,7 @@},{"label": "Backend dev",- "command": "poetry run uvicorn main:app --reload --port 7001",+ "command": "poetry run python start.py","cwd": "$ZED_WORKTREE_ROOT/backend","use_new_terminal": false,"allow_concurrent_runs": false,diff --git a/backend/start.py b/backend/start.pyindex 96500403..ae847ca1 100644--- a/backend/start.py+++ b/backend/start.py@@ -1,9 +1,40 @@import argparse+import socketimport uvicorn++def is_port_available(host: str, port: int) -> bool:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ try:+ sock.bind((host, port))+ except OSError:+ return False++ return True+++def find_available_port(host: str, start_port: int, max_attempts: int) -> int:+ for port in range(start_port, start_port + max_attempts):+ if is_port_available(host, port):+ return port++ raise RuntimeError(+ f"No available port found from {start_port} to "+ f"{start_port + max_attempts - 1}"+ )++if __name__ == "__main__":parser = argparse.ArgumentParser()+ parser.add_argument("--host", default="127.0.0.1")parser.add_argument("--port", type=int, default=7001)+ parser.add_argument("--max-port-attempts", type=int, default=20)args = parser.parse_args()- uvicorn.run("main:app", port=args.port, reload=True)++ port = find_available_port(args.host, args.port, args.max_port_attempts)+ if port != args.port:+ print(f"Port {args.port} is in use. Starting backend on port {port}.")++ uvicorn.run("main:app", host=args.host, port=port, reload=True)diff --git a/backend/tests/test_start.py b/backend/tests/test_start.pynew file mode 100644index 00000000..2476fe3a--- /dev/null+++ b/backend/tests/test_start.py@@ -0,0 +1,11 @@+import start+++def test_find_available_port_skips_bound_port(monkeypatch):+ monkeypatch.setattr(+ start,+ "is_port_available",+ lambda _host, port: port == 7003,+ )++ assert start.find_available_port("127.0.0.1", 7001, 20) == 7003