Spaces:
Paused
Paused
File size: 1,552 Bytes
34a6637 ac2e86b 34a6637 a1e9803 34a6637 a1e9803 34a6637 12a1332 34a6637 990bdf1 34a6637 fa92d1e 34a6637 990bdf1 34a6637 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import threading, queue, time
from seleniumbase import SB
app = FastAPI()
class URLRequest(BaseModel):
url: str
url_queue = queue.Queue()
sb_ref = {"driver": None}
def browser_worker():
# ใช้เบราว์เซอร์จริง (ไม่ headless) แต่จอถูก Xvfb รับไว้จาก xvfb-run
# ระบุ browser="chromium" ให้ตรงกับแพ็กเกจที่ติดตั้ง
with SB(browser="chromium", uc=True, headless=False) as sb:
sb_ref["driver"] = sb
sb.get("https://www.google.com")
while True:
url = url_queue.get()
try:
print(f"[open] {url}")
sb.get(url)
time.sleep(0.3)
except Exception as e:
print("[error]", e)
finally:
url_queue.task_done()
@app.get("/healthz")
def healthz():
return {"ok": bool(sb_ref.get("driver"))}
@app.get("/cookies")
def get_cookies():
sb = sb_ref.get("driver")
if not sb:
raise HTTPException(503, "Browser not ready")
return sb.get_cookies()
@app.post("/open_url")
async def open_url(request: URLRequest):
if not sb_ref.get("driver"):
raise HTTPException(503, "Browser not ready")
print(f"[queue] {request.url}")
url_queue.put(request.url)
return {"status": "queued", "url": request.url}
threading.Thread(target=browser_worker, daemon=True).start() |