Skip to content

Commit e0215cf

Browse files
prioritize regular http and fallback to puppeteer instead of one or the
other Please enter the commit message for your changes. Lines starting
1 parent 7d71cc7 commit e0215cf

1 file changed

Lines changed: 22 additions & 27 deletions

File tree

app.py

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -177,17 +177,15 @@ async def html_parser(html):
177177

178178

179179
async def fetch_data(url):
180-
if not BROWSER_WS:
180+
try:
181181
async with aiohttp.ClientSession() as session:
182182
async with session.get(url) as response:
183-
if response.ok:
184-
try:
185-
return await response.json()
186-
except (aiohttp.ContentTypeError, json.JSONDecodeError):
187-
return await response.text()
188-
else:
189-
return f"Request failed with status code {response.status}"
190-
else:
183+
response.raise_for_status()
184+
try:
185+
return await response.json()
186+
except (aiohttp.ContentTypeError, json.JSONDecodeError):
187+
return await response.text()
188+
except:
191189
async with async_playwright() as playwright:
192190
browser = await playwright.chromium.connect(BROWSER_WS)
193191
async with browser:
@@ -357,29 +355,26 @@ async def dynamic_download(
357355
content: bytes = bytes()
358356
media_type: str = "application/octet-stream"
359357

360-
if not BROWSER_WS:
358+
try:
361359
async with aiohttp.ClientSession() as session:
362360
async with session.get(result) as response:
363361
response.raise_for_status()
364362
content = await response.read()
365-
else:
366-
try:
367-
async with async_playwright() as playwright:
368-
browser = await playwright.chromium.connect(BROWSER_WS)
369-
context = await browser.new_context()
370-
page = await context.new_page()
371-
response = await page.goto(result)
372-
if response.ok:
373-
content = await response.body()
374-
media_type = response.headers.get(
375-
"Content-Type", "application/octet-stream"
363+
except:
364+
async with async_playwright() as playwright:
365+
browser = await playwright.chromium.connect(BROWSER_WS)
366+
context = await browser.new_context()
367+
page = await context.new_page()
368+
response = await page.goto(result)
369+
async with response.finished():
370+
if not response.ok:
371+
raise Exception(
372+
f"{response.status}: {response.status_text}"
376373
)
377-
except PlaywrightError:
378-
async with aiohttp.ClientSession() as session:
379-
async with session.get(result) as response:
380-
response.raise_for_status()
381-
content = await response.read()
382-
374+
content = await response.body()
375+
media_type = response.headers.get(
376+
"Content-Type", "application/octet-stream"
377+
)
383378
return StreamingResponse(
384379
iter([content]),
385380
media_type=media_type,

0 commit comments

Comments
 (0)