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

[Feature] Propagate contextvars to event handlers #1816

Open
nathanielobrown opened this issue Mar 17, 2023 · 2 comments
Open

[Feature] Propagate contextvars to event handlers #1816

nathanielobrown opened this issue Mar 17, 2023 · 2 comments

Comments

@nathanielobrown
Copy link

nathanielobrown commented Mar 17, 2023

When using the Playwright Python library, event callbacks registered with page.on() do not have the same contextvars as the parent code. This behavior can lead to issues when users expect shared context between the main code and event handlers.

It would be great if Playwright could propagate contextvars to event handlers by default to facilitate shared context.

Reproduction Code Sample:

This code demonstrates failure to get context var. Tested on Python 3.10, Playwright versions 1.31 and 1.29

import contextvars
from playwright.sync_api import sync_playwright

shared_var = contextvars.ContextVar("shared_var")

def on_request(request):
    try:
        print("Shared value in callback:", shared_var.get())
    except LookupError:
        print("Failed to get shared value in callback")

def main():
    shared_var.set("some value")

    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()

        page.on("request", on_request)

        # Perform some actions and trigger the event
        page.goto("https://example.com")
        browser.close()

if __name__ == "__main__":
    main()

Context

This came up for me because I used context managers to annotate logs but my logging of network requests in Playwright were not getting annotated.

@mxschmitt
Copy link
Member

Investigation note, we need to implement this greenlet functionality accordingly around here.

@chingyangtseng-houzz
Copy link

+1 for this. I would like to implement similar feature to consolidate the logs under the same session/request through the same id stored within the contextvars.

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

No branches or pull requests

3 participants