upload
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
"""美团酒店任务看板 一键启动。
|
||||
|
||||
- 后端 FastAPI :8011(uvicorn,读 backend/.env)
|
||||
- 前端 Vite :5175(npm run dev,开发模式)
|
||||
- 启动完成后自动打开浏览器;Ctrl+C 自动清理子进程
|
||||
|
||||
可选参数:
|
||||
python start.py --no-browser 不自动打开浏览器
|
||||
python start.py --static 纯后端模式:页面由 8011 托管 frontend/dist,
|
||||
无需 Node/构建环境(需 dist 产物随项目携带)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
from urllib.request import urlopen
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
BACKEND = ROOT / "backend"
|
||||
FRONTEND = ROOT / "frontend"
|
||||
|
||||
API_PORT = 8011
|
||||
WEB_PORT = 5175
|
||||
HEALTH_URL = f"http://127.0.0.1:{API_PORT}/api/health"
|
||||
WEB_URL = f"http://localhost:{WEB_PORT}"
|
||||
|
||||
procs: list[subprocess.Popen] = []
|
||||
|
||||
|
||||
def eprint(msg: str) -> None:
|
||||
print(msg, flush=True)
|
||||
|
||||
|
||||
def port_in_use(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(0.5)
|
||||
return s.connect_ex(("127.0.0.1", port)) == 0
|
||||
|
||||
|
||||
def check_env(static: bool = False) -> None:
|
||||
"""前置检查:后端依赖 / 前端依赖 / dist 产物"""
|
||||
if not (BACKEND / ".env").exists():
|
||||
eprint("[WARN] backend/.env 不存在,将使用 config.py 默认值(多半连不上数据库)")
|
||||
try:
|
||||
import fastapi # noqa: F401
|
||||
import uvicorn # noqa: F401
|
||||
except ImportError:
|
||||
eprint("[ERROR] 后端依赖缺失,请先执行:pip install -r backend/requirements.txt")
|
||||
sys.exit(1)
|
||||
if static:
|
||||
if not (FRONTEND / "dist").exists():
|
||||
eprint("[ERROR] 静态模式需要 frontend/dist 构建产物(开发机执行 npm run build 后随项目拷贝)")
|
||||
sys.exit(1)
|
||||
return
|
||||
if not (FRONTEND / "node_modules").exists():
|
||||
eprint("[ERROR] 前端依赖缺失,请先执行:cd frontend && npm install")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def stop_all() -> None:
|
||||
"""终止全部子进程(Windows 杀进程树,避免残留 node/python)"""
|
||||
for p in procs:
|
||||
if p.poll() is None:
|
||||
try:
|
||||
subprocess.run(["taskkill", "/F", "/T", "/PID", str(p.pid)], capture_output=True)
|
||||
except Exception:
|
||||
try:
|
||||
p.terminate()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def wait_backend_ready(timeout: int = 40) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if any(p.poll() is not None for p in procs):
|
||||
eprint("[ERROR] 有进程提前退出,请查看上方日志")
|
||||
stop_all()
|
||||
sys.exit(1)
|
||||
try:
|
||||
with urlopen(HEALTH_URL, timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="美团酒店任务看板 一键启动")
|
||||
parser.add_argument("--no-browser", action="store_true", help="启动后不自动打开浏览器")
|
||||
parser.add_argument("--static", action="store_true", help="纯后端模式:用 8011 托管 frontend/dist")
|
||||
args = parser.parse_args()
|
||||
|
||||
eprint("=" * 40)
|
||||
eprint("美团酒店任务看板 启动" + ("(静态模式)" if args.static else ""))
|
||||
eprint("=" * 40)
|
||||
|
||||
check_env(static=args.static)
|
||||
|
||||
ports = [API_PORT] if args.static else [API_PORT, WEB_PORT]
|
||||
for port in ports:
|
||||
if port_in_use(port):
|
||||
eprint(f"[ERROR] 端口 {port} 已被占用(服务可能已在运行),请先关闭再启动。")
|
||||
sys.exit(1)
|
||||
|
||||
eprint(f"[1/2] 启动后端 FastAPI http://127.0.0.1:{API_PORT}")
|
||||
procs.append(
|
||||
subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(API_PORT)],
|
||||
cwd=str(BACKEND),
|
||||
)
|
||||
)
|
||||
|
||||
if args.static:
|
||||
eprint("[static] 纯后端模式(页面由 8011 托管 dist,无需 Node)")
|
||||
target = f"http://127.0.0.1:{API_PORT}"
|
||||
else:
|
||||
eprint(f"[2/2] 启动前端 Vite {WEB_URL}")
|
||||
npm = "npm.cmd" if os.name == "nt" else "npm"
|
||||
procs.append(subprocess.Popen([npm, "run", "dev"], cwd=str(FRONTEND)))
|
||||
target = WEB_URL
|
||||
|
||||
eprint("等待服务就绪 ...")
|
||||
if not wait_backend_ready():
|
||||
eprint("[ERROR] 后端在 40 秒内未就绪,请查看上方日志")
|
||||
stop_all()
|
||||
sys.exit(1)
|
||||
if not args.static:
|
||||
time.sleep(2) # 等 Vite 编译完成
|
||||
|
||||
eprint(f"✓ 启动完成,访问 {target}")
|
||||
if not args.no_browser:
|
||||
webbrowser.open(target)
|
||||
|
||||
eprint("按 Ctrl+C 停止服务 ...")
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
eprint("\n正在关闭服务 ...")
|
||||
stop_all()
|
||||
eprint("已退出")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user