blob: 22f229229ccda93717e300f7e0cce3c62b1b0ecb [file] [log] [blame]
22301110e361be52025-06-08 15:24:14 +08001import subprocess
2import time
3import requests
4import os
5import signal
6from flask import Flask
7from flask_cors import CORS
8
9
10
11NGROK_PORT = 6001
12NGROK_API = 'http://127.0.0.1:4040/api/tunnels'
13NGROK_URL_FILE = 'ngrok_url.txt'
14
15def start_backend():
16 print("🚀 启动 Flask 后端...")
17 return subprocess.Popen(
18 ["venv\\Scripts\\python.exe", "backend.py"],
19 creationflags=subprocess.CREATE_NEW_CONSOLE
20 )
21
22def start_ngrok():
23 print("🌐 启动 Ngrok 隧道(窗口隐藏)...")
24 startupinfo = subprocess.STARTUPINFO()
25 startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
26
27 return subprocess.Popen(
28 ["ngrok", "http", str(NGROK_PORT)],
29 stdout=subprocess.DEVNULL,
30 stderr=subprocess.DEVNULL,
31 startupinfo=startupinfo
32 )
33
34
35def fetch_ngrok_url(retries=10):
36 print("⏳ 正在获取 Ngrok 公网地址...")
37 for _ in range(retries):
38 try:
39 res = requests.get(NGROK_API).json()
40 tunnels = res.get("tunnels")
41 if tunnels:
42 public_url = tunnels[0]["public_url"]
43 with open(NGROK_URL_FILE, "w", encoding="utf-8") as f:
44 f.write(public_url)
45 print(f"✅ Ngrok 地址: {public_url} 已写入 {NGROK_URL_FILE}")
46 return public_url
47 except Exception:
48 pass
49 time.sleep(1)
50 print("❌ 获取 Ngrok 地址失败!")
51 return None
52
53if __name__ == "__main__":
54 backend_proc = start_backend()
55 time.sleep(3) # 等后端稍微先启动
56
57 ngrok_proc = start_ngrok()
58 time.sleep(3) # 等 ngrok 启动
59
60 try:
61 fetch_ngrok_url()
62 print("\n✅ 所有服务已启动,按 Ctrl+C 退出。")
63 while True:
64 time.sleep(1)
65 except KeyboardInterrupt:
66 print("\n🛑 正在关闭服务...")
67 backend_proc.terminate()
68 ngrok_proc.terminate()
69 print("✅ 已关闭")