Update fun.py
Browse files
fun.py
CHANGED
@@ -12,7 +12,7 @@ import random
|
|
12 |
from typing import Dict
|
13 |
from loguru import logger
|
14 |
from starlette.responses import StreamingResponse
|
15 |
-
|
16 |
app = FastAPI()
|
17 |
|
18 |
# 浏览器实例管理
|
@@ -47,7 +47,16 @@ def get_default_launch_args():
|
|
47 |
"--no-default-browser-check",
|
48 |
"--remote-allow-origins=*"
|
49 |
]
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
# BitBrowser风格API
|
52 |
@app.post("/browser/open")
|
53 |
async def open_browser(request: Request):
|
@@ -78,6 +87,9 @@ async def open_browser(request: Request):
|
|
78 |
deduped_args.append(arg)
|
79 |
args = [CHROME_PATH] + deduped_args
|
80 |
proc = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
|
|
|
|
|
81 |
async with httpx.AsyncClient() as client:
|
82 |
resp = await client.get(f"http://127.0.0.1:{port}/json/version")
|
83 |
if resp.status_code == 200:
|
|
|
12 |
from typing import Dict
|
13 |
from loguru import logger
|
14 |
from starlette.responses import StreamingResponse
|
15 |
+
import socket
|
16 |
app = FastAPI()
|
17 |
|
18 |
# 浏览器实例管理
|
|
|
47 |
"--no-default-browser-check",
|
48 |
"--remote-allow-origins=*"
|
49 |
]
|
50 |
+
def wait_port(host, port, timeout=5.0):
|
51 |
+
"""等待端口可用"""
|
52 |
+
start = time.time()
|
53 |
+
while time.time() - start < timeout:
|
54 |
+
try:
|
55 |
+
with socket.create_connection((host, port), timeout=0.5):
|
56 |
+
return True
|
57 |
+
except Exception:
|
58 |
+
time.sleep(0.1)
|
59 |
+
return False
|
60 |
# BitBrowser风格API
|
61 |
@app.post("/browser/open")
|
62 |
async def open_browser(request: Request):
|
|
|
87 |
deduped_args.append(arg)
|
88 |
args = [CHROME_PATH] + deduped_args
|
89 |
proc = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
90 |
+
if not wait_port("127.0.0.1", port, timeout=8):
|
91 |
+
proc.terminate()
|
92 |
+
return {"code": 2, "msg": f"chrome端口{port}未就绪"}
|
93 |
async with httpx.AsyncClient() as client:
|
94 |
resp = await client.get(f"http://127.0.0.1:{port}/json/version")
|
95 |
if resp.status_code == 200:
|