himanshu-muk commited on
Commit
928cdf1
·
1 Parent(s): a999b8c

Fix API to directly return flowPages value instead of parsing console logs

Browse files
Files changed (1) hide show
  1. app.py +27 -28
app.py CHANGED
@@ -1,4 +1,3 @@
1
- import json
2
  import asyncio
3
  from fastapi import FastAPI, HTTPException
4
  from playwright.async_api import async_playwright
@@ -8,41 +7,41 @@ app = FastAPI()
8
 
9
  @app.post("/run")
10
  async def run_flow_pages(url: str):
11
- console_result = None
12
-
13
  async with async_playwright() as p:
14
  browser = await p.chromium.launch(headless=True)
15
  page = await browser.new_page()
16
 
17
- # Capture console messages
18
- async def handle_console(msg):
19
- nonlocal console_result
20
- try:
21
- console_result = json.loads(msg.text())
22
- except Exception:
23
- pass # ignore non-JSON logs
24
-
25
- page.on("console", handle_console)
26
-
27
  try:
28
- await page.goto(url, wait_until="load")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- # Execute flowPages in browser console
31
- await page.evaluate("() => { console.log(flowPages); }")
 
 
 
32
 
33
- # Small wait to allow console log to be captured
34
- await asyncio.sleep(1)
35
 
36
  except Exception as e:
37
  await browser.close()
38
  raise HTTPException(status_code=500, detail=str(e))
39
-
40
- await browser.close()
41
-
42
- if console_result is None:
43
- raise HTTPException(
44
- status_code=500,
45
- detail="No JSON response received from flowPages"
46
- )
47
-
48
- return console_result
 
 
1
  import asyncio
2
  from fastapi import FastAPI, HTTPException
3
  from playwright.async_api import async_playwright
 
7
 
8
  @app.post("/run")
9
  async def run_flow_pages(url: str):
 
 
10
  async with async_playwright() as p:
11
  browser = await p.chromium.launch(headless=True)
12
  page = await browser.new_page()
13
 
 
 
 
 
 
 
 
 
 
 
14
  try:
15
+ await page.goto(url, wait_until="load", timeout=30000)
16
+
17
+ # Wait a bit for the page to fully load and flowPages to be available
18
+ await asyncio.sleep(2)
19
+
20
+ # Directly evaluate and return flowPages from the page
21
+ flow_pages_data = await page.evaluate("""() => {
22
+ // Check if flowPages exists in various scopes
23
+ if (typeof flowPages !== 'undefined') {
24
+ return flowPages;
25
+ }
26
+ if (typeof window !== 'undefined' && window.flowPages) {
27
+ return window.flowPages;
28
+ }
29
+ if (typeof globalThis !== 'undefined' && globalThis.flowPages) {
30
+ return globalThis.flowPages;
31
+ }
32
+ return null;
33
+ }""")
34
+
35
+ await browser.close()
36
 
37
+ if flow_pages_data is None:
38
+ raise HTTPException(
39
+ status_code=500,
40
+ detail="flowPages not found on the page"
41
+ )
42
 
43
+ return flow_pages_data
 
44
 
45
  except Exception as e:
46
  await browser.close()
47
  raise HTTPException(status_code=500, detail=str(e))