24 lines
817 B
Python
24 lines
817 B
Python
"""Playwright encapsulation & helpers"""
|
|
from contextlib import asynccontextmanager
|
|
from typing import AsyncGenerator
|
|
|
|
from playwright.async_api import BrowserContext, Route, async_playwright
|
|
|
|
from frontools.sources import Source
|
|
|
|
|
|
@asynccontextmanager
|
|
async def get_cached_browser(source: Source) -> AsyncGenerator[BrowserContext, None]:
|
|
"""Return a Playwright browser that will eventually get files from local cache"""
|
|
|
|
async def _cache_route(route: Route) -> None:
|
|
content = await source.get_url(route.request.url)
|
|
await route.fulfill(body=content)
|
|
|
|
async with async_playwright() as pwright:
|
|
browser = await pwright.firefox.launch()
|
|
context = await browser.new_context()
|
|
await context.route("*", _cache_route)
|
|
yield context
|
|
await browser.close()
|