Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question]: Creating a playwright instance per thread with the async api #1619

Closed
LeilaSchooley opened this issue Nov 1, 2022 · 1 comment

Comments

@LeilaSchooley
Copy link

Your question

I saw this #623 (comment)
how would I adapt this example for the async api? It's required for a project.

import threading
from playwright.async_api import async_playwright
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor


class Tls(threading.local):

    def __init__(self) -> None:
        self.playwright = async_playwright().start()
        print("Create playwright instance in Thread", threading.current_thread().name)


class Worker:
    tls = Tls()

    async def run(self):
        print("Launched worker in ", threading.current_thread().name)
        browser = self.tls.playwright.chromium.launch(headless=False)
        context = browser.new_context()
        page = browser.new_page()
        page.goto("http://whatsmyuseragent.org/")
        page.screenshot(path=f"example-{threading.current_thread().name}.png")
        page.close()
        context.close()
        browser.close()
        print("Stopped worker in ", threading.current_thread().name)


if __name__ == "__main__":
    with ThreadPoolExecutor(max_workers=5) as executor:
        for _ in range(50):
            worker = Worker()
            executor.submit(worker.run)

Create playwright instance in Thread MainThread
:33: RuntimeWarning: coroutine 'Worker.run' was never awaited
executor.submit(worker.run)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
85: RuntimeWarning: coroutine 'Worker.run' was never awaited
del work_item
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
sys:1: RuntimeWarning: coroutine 'PlaywrightContextManager.start' was never awaited

@mxschmitt
Copy link
Member

For general Python support we recommend asking the question on StackOverflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants