Skip to main content

Playwright integration for Litestar.

Project description

litestar-playwright

CI PyPI - Version PyPI - Python Version License - MIT Latest Commit

Checked with mypy linting - Ruff GitHub Tag

Downloads Downloads/Month Downloads/Week

Playwright integration for Litestar.


Table of Contents

Features

  • 🎭 Browser Management: Manage Playwright browser instances
  • 🔧 Dependency Injection: Automatic injection of browser instances into route handlers
  • Async Support: Full async/await support for all operations

Installation

uv add litestar-playwright

Quick Start

from litestar import Litestar
from litestar_playwright.config import PlaywrightConfig
from litestar_playwright.plugin import PlaywrightPlugin

# Create the plugin with configuration
playwright_plugin = PlaywrightPlugin(
    config=PlaywrightConfig(
        browser_type="chromium",  # or "firefox", "webkit"
        headless=False,  # Show browser windows
    )
)

# Add to your Litestar app
app = Litestar(plugins=[playwright_plugin])

Configuration

The PlaywrightConfig class provides several configuration options:

@dataclass
class PlaywrightConfig:
    headless: bool = True
    """Whether to run browsers in headless mode."""

    browser_type: str = "chromium"
    """Type of browser to use (chromium, firefox, webkit)."""

    playwright_app_state_key: str = "playwright_browser"
    """Key used to store the browser instance in app state."""

Usage

Accessing Browser Instances

The plugin automatically injects browser instances into your route handlers:

from litestar import get
from playwright.async_api import Browser

@get("/my-route")
async def my_route(playwright_browser: Browser) -> str:
    # Create a new context
    context = await playwright_browser.new_context()

    # Create a new page
    page = await context.new_page()

    # Navigate to a URL
    await page.goto("https://example.com")

    return "Page loaded!"

Web Scraping Example

Here's a complete example of web scraping with the plugin:

from litestar import get
from playwright.async_api import Browser

@get("/scrape")
async def scrape_website(playwright_browser: Browser) -> dict:
    # Create a new context
    context = await playwright_browser.new_context()

    try:
        # Create a new page
        page = await context.new_page()

        # Navigate to a website
        await page.goto("https://example.com")

        # Extract information
        title = await page.title()
        content = await page.content()

        return {
            "title": title,
            "content_length": len(content)
        }
    finally:
        # Always clean up
        await context.close()

Multiple Playwright Plugins Example

You can use multiple Playwright plugins in a single application for different use cases:

from litestar import Litestar, get
from playwright.async_api import Browser
from litestar_playwright.config import PlaywrightConfig
from litestar_playwright.plugin import PlaywrightPlugin

# Create different configurations for various browsers
chrome_config = PlaywrightConfig(
    browser_type="chromium",
    headless=False,
    launch_kwargs={"args": ["--no-sandbox"]},
    playwright_browser_instance_state_key="chrome_browser",
)

firefox_config = PlaywrightConfig(
    browser_type="firefox",
    headless=False,
    playwright_browser_instance_state_key="firefox_browser",
)

# Route handlers can inject specific browser instances
@get("/chrome-info")
async def chrome_info(chrome_browser: Browser) -> dict:
    return {"browser": chrome_browser.browser_type.name}

@get("/firefox-info")
async def firefox_info(firefox_browser: Browser) -> dict:
    return {"browser": firefox_browser.browser_type.name}

# Use multiple plugins in your app
app = Litestar(
    plugins=[
        PlaywrightPlugin(config=chrome_config),
        PlaywrightPlugin(config=firefox_config),
    ],
    route_handlers=[chrome_info, firefox_info],
)

This approach is useful for:

  • Cross-browser testing: Test your application across different browsers
  • Specialized workflows: Use different browsers for different tasks
  • CI/CD scenarios: Run headless browsers for automated testing
  • Performance testing: Compare behavior across browser engines

Support :heart:

If you have any questions or need help, feel free to open an issue on the GitHub repository.

Author :person_with_crown:

This project is maintained by Hasan Sezer Taşan, It's me :wave:

Contributing :heart:

Any contributions are welcome! Please follow the Contributing Guidelines to contribute to this project.

Tasks

Clone the repository and cd into the project directory:

git clone https://github.com/hasansezertasan/litestar_playwright
cd litestar_playwright

The commands below can also be executed using the xc task runner, which combines the usage instructions with the actual commands. Simply run xc, it will pop up an interactive menu with all available tasks.

install

Install the dependencies:

uv sync
uv run playwright install

style

Run the style checks:

uv run --locked tox run -e style

ci

Run the CI pipeline:

uv run --locked tox run

run-simple

Run the simple example:

uv run python examples/simple.py

run-multiple-plugins

Run the multiple plugins example:

uv run python examples/multiple_plugins.py

License

litestar-playwright is distributed under the terms of the MIT license.

Changelog :memo:

For a detailed list of changes, please refer to the CHANGELOG.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

litestar_playwright-0.1.0.tar.gz (262.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

litestar_playwright-0.1.0-py3-none-any.whl (8.2 kB view details)

Uploaded Python 3

File details

Details for the file litestar_playwright-0.1.0.tar.gz.

File metadata

  • Download URL: litestar_playwright-0.1.0.tar.gz
  • Upload date:
  • Size: 262.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.8.15

File hashes

Hashes for litestar_playwright-0.1.0.tar.gz
Algorithm Hash digest
SHA256 a5e2b5a1a40191e079d1a26d1d39031db761fec8ed3c655b22b346d3fa1c4e97
MD5 b7047b125149f5d666c1d8fb4797ceab
BLAKE2b-256 d07ba4e8c0121dedc50839d0e1a6d7398114ffa0888e3519e8e1aa8f3d13a1fe

See more details on using hashes here.

File details

Details for the file litestar_playwright-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for litestar_playwright-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 71a6706195d18f71ea7517d6973f5a5a67316f6ff7eec2efb467a5a4a9c478c1
MD5 a5acf2a1fda12d139135eee1848034f6
BLAKE2b-256 16e1511ce73893271243f3766a141012cb2a905f668918224dd77f5761ed038f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page